我正在尝试使用短剧学习来查找PCA的权重。但是,这些方法都不起作用。
代码:
import pandas as pd
import numpy as np
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
# load dataset into Pandas DataFrame
df = pd.read_csv(url, names=['sepal length','sepal width','petal length','petal width','target'])
from sklearn.preprocessing import StandardScaler
features = ['sepal length', 'sepal width', 'petal length', 'petal width']
# Separating out the features
x = df.loc[:, features].values
# Standardizing the features
x = StandardScaler().fit_transform(x)
from sklearn.decomposition import PCA
pca = PCA(n_components=1)
principalComponents = pca.fit_transform(x)
查找权重
方法 1
weights = pca.components_*np.sqrt(pca.explained_variance_)
# recovering original data
pca_recovered = np.dot(weights, x)
### This output is not matching with PCA
方法 2
# Standardising the weights then recovering
weights1 = weights/np.sum(weights)
pca_recovered = np.dot(weights1, x)
### This output is not matching with PCA
如果我在这里做错了什么,请帮助。或者,包装中缺少某些内容。
使用
weight = pca.components_
但输出
x.dot(pca.components_.T)
不同于
pca.fit_transform(x)
因为 PCA 输出是标准化的。 用
tmp = x.dot(pca.components_.T)
tmp-tmp.mean(axis=0)
您将获得相同的输出
而不是
weights = pca.components_*np.sqrt(pca.explained_variance_)
如果我简单地使用
weights = pca.components_
可能是第一次,当我尝试时,有计算错误。