师,
当选择主成分数(k)时,我们选择k作为最小值,以便保留例如99%的方差。
但是,在Python Scikit学习中,我不是100%肯定pca.explained_variance_ratio_ = 0.99等于“99%的方差被保留”?谁能开导?感谢。
答案 0 :(得分:45)
是的,你几乎是对的。 pca.explained_variance_ratio_
参数返回由每个维度解释的方差的向量。因此pca.explained_variance_ratio_[i]
给出的方差仅由i + 1st维度解释。
您可能想要pca.explained_variance_ratio_.cumsum()
。这将返回一个向量x
,以便x[i]
返回由第一个i + 1维度解释的累积方差。
import numpy as np
from sklearn.decomposition import PCA
np.random.seed(0)
my_matrix = np.random.randn(20, 5)
my_model = PCA(n_components=5)
my_model.fit_transform(my_matrix)
print my_model.explained_variance_
print my_model.explained_variance_ratio_
print my_model.explained_variance_ratio_.cumsum()
[ 1.50756565 1.29374452 0.97042041 0.61712667 0.31529082]
[ 0.32047581 0.27502207 0.20629036 0.13118776 0.067024 ]
[ 0.32047581 0.59549787 0.80178824 0.932976 1. ]
所以在我的随机玩具数据中,如果我选择了k=4
,我将保留93.3%的差异。
答案 1 :(得分:16)
虽然这个问题超过2年,但我想提供更新。 我想做同样的事情,看起来sklearn现在提供了开箱即用的功能。
如docs
中所述如果0< n_components< 1和svd_solver =='full',选择组件数量,使得需要解释的方差量大于n_components指定的百分比
所以现在需要的代码是
my_model = PCA(n_components=0.99, svd_solver='full')
my_model.fit_transform(my_matrix)
答案 2 :(得分:0)
这对我有用,甚至在“ PCA”部分中键入的内容更少。 为了方便起见,添加了其余的内容。只需在早期阶段定义“数据”即可。
import sklearn as sl
from sklearn.preprocessing import StandardScaler as ss
from sklearn.decomposition import PCA
st = ss().fit_transform(data)
pca = PCA(0.80)
pc = pca.fit_transform(st) # << to retain the components in an object
pc
#pca.explained_variance_ratio_
print ( "Components = ", pca.n_components_ , ";\nTotal explained variance = ",
round(pca.explained_variance_ratio_.sum(),5) )