Sklearn.decomposition.PCA: 按给定比例获取组件

Sklearn.decomposition.PCA: Get components by given ratio

我想对某些数据使用 PCA 来获取矩阵的顶级主成分,这些成分占总方差的 95%。我一直在寻找这样做的功能,但找不到方法。
我唯一能找到的是以下内容:

from sklearn.decomposition import PCA
# W_0 is a matrix 
pca = PCA().fit(W_0)
# get the index of the component which has variance higher than 0.95
index_component = np.min(np.argwhere(np.cumsum(pca.explained_variance_ratio_)>0.95))
# Now fit again with the given component 
pca = PCA(n_components= index_component+1)
pca.fit(W_0)

这种方法的问题是我拟合了两次,这是性能瓶颈。 有更好的方法吗?

documentation可以看出If 0 < n_components < 1 and svd_solver == 'full', select等分量的个数需要解释的方差量大于 n_components.

指定的百分比

要获得满足至少 95% 方差的组件,请使用 PCA(n_components=0.95, svd_solver='full')