python - 在线性回归中使用 PCA

标签 python machine-learning scikit-learn pca

我想在应用线性回归之前使用主成分分析来减少一些噪音。

我有 1000 个样本和 200 个特征

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA

X = np.random.rand(1000,200)
y = np.random.rand(1000,1)

有了这些数据,我可以训练我的模型:

model.fit(X,y)

但如果我在应用 PCA 后尝试同样的操作

pca = PCA(n_components=8)
pca.fit(X)
PCA(copy=True, iterated_power='auto', n_components=3, random_state=None,
  svd_solver='auto', tol=0.0, whiten=False)
principal_components =  pca.components_

model.fit(principal_components,y)

我收到这个错误:

ValueError: Found input variables with inconsistent numbers of samples: [8, 1000]

最佳答案

试试这个:

pca = PCA(n_components=8)
X_pca = pca.fit_transform(X)

model.fit(X_pca,y)

也就是说,您同时将 PCA 拟合到 X 并将其转换为名为 X_pca 的 (1000, 8) 数组。这就是你应该使用的而不是 pca.components_

关于python - 在线性回归中使用 PCA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41866841/

相关文章:

python - Matplotlib:如何在对数图中设置孪生轴的刻度

machine-learning - 池化与随时间池化

python - "Inconsistent numbers of samples"-scikit-学习

python - TfidfVectorizer.fit_transfrom 和 tfidf.transform 之间有什么区别?

python - 将 scikit 缩放数据映射回 ID

python - 在枚举列表中过滤枚举 sqlalchemy

python - 无法按请求登录网站

machine-learning - weka特征选择中 'InfoGainAttributeEval'的选择是如何发生的(过滤方法)

machine-learning - Fast.Ai EarlyStoppingCallback 不起作用

Pythonic 方式到 "run X before Y if Y fails"?