【发布时间】:2021-08-25 13:04:36
【问题描述】:
from sklearn.decomposition import PCA
pca = PCA(n_components=1, random_state=42).fit_transform(X_train)
# 43 components according to the graph, but it only allows 1.
pca = pd.DataFrame(pca,columns=['pca'])
#pca
#X_train= pd.concat([X_train,pca],axis=1)
如果我将 n_components 更改为任何其他数字(例如,43),它将显示如下错误:
ValueError: Shape of passed values is (54708, 43), indices imply (54708, 1)
我在我的代码中使用了这个来帮助我了解我应该使用的组件数量,即 43:
# find n components to explain variance.
# Code source: https://www.mikulskibartosz.name/pca-how-to-choose-the-number-of-components/
from sklearn.decomposition import PCA
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
data_rescaled = scaler.fit_transform(X_train)
pca = PCA().fit(data_rescaled)
% matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (24,12)
fig, ax = plt.subplots()
xi = np.arange(1, 117, step=1)
# The number 117 is to match y, otherwise it gives me error.
y = np.cumsum(pca.explained_variance_ratio_)
# (explained_variance_ratio_)
# Percentage of variance explained by each of the selected components.
# np.cumsum
# Return the cumulative sum of the elements along a given axis.
plt.ylim(0.0,1.1)
plt.plot(xi, y, marker='o', linestyle='--', color='b')
plt.xlabel('Number of Components')
plt.xticks(np.arange(0, 117, step=1)) #change from 0-based array index to 1-based human-readable label
plt.ylabel('Cumulative variance (%)')
plt.title('The number of components needed to explain variance')
plt.axhline(y=0.95, color='r', linestyle='-')
plt.text(0.5, 0.85, '95% cut-off threshold', color = 'red', fontsize=16)
ax.grid(axis='x')
plt.show()
# 43 number of components.
来自代码结果的图表:
【问题讨论】:
-
您的问题是什么?第一个代码块还是第二个代码块?
-
对不起,我的问题是为什么我不能将ncomponent的值更改为1以外的数字,这是第一个代码块。第二个代码块只是为了提供一些上下文。
-
我认为错误来自
pca = pd.DataFrame(pca,columns=['pca'])这一行,而不是来自 PCA。 -
@FlaviaGiammarino 是的,它不允许我制作数据框。
-
那是因为你有 43 列,但是
columns=['pca']你只传递一个列名。您可以使用columns=['pca' + str(i) for i in range(n_components)]和n_components=43创建一个包含 43 个列名的列表。
标签: python machine-learning pca