【问题标题】:Plotting multidimensional data on a graph在图表上绘制多维数据
【发布时间】:2018-07-12 10:45:28
【问题描述】:

我有一个包含 1700 行的数据,每行包含 9 个房屋特征和一个包含与这些特征相对应的价格的数组。我已经在这些数据上建立了一个线性回归模型,但我想将其可视化。我可以使用 PCA 以某种方式将这 9 个功能转换为单个功能吗?我已经尝试过了,但我仍然收到错误说 x, y 需要具有相同的大小。

from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.decomposition import PCA

clf = linear_model.LinearRegression()
pca = PCA(n_components = 9)
# features contains 1700 rows of 9 feature data, y contains 1700 price values
x_train, x_test, y_train, y_test = train_test_split(features, y)
pca.fit(x_train)
x_train = pca.transform(x_train)
x_test = pca.transform(x_test)
clf.fit(x_train, y_train)
pred = clf.predict(x_test)
plt.scatter(x_train, y_train)
plt.show()

plt.scatter()函数出现错误,feature.shape = (17000, 9), y.shape = (17000, 1)

【问题讨论】:

  • 错误出现在哪一行?此外,数组的形状会有所帮助
  • @Varsha 错误显示在 'plt.scatter(x_train, y_train)' 行。 “特征”的形状:(17000, 9),“y”的形状:(17000, 1)
  • 尝试将 n_components 设置为 1,然后 pca 的结果输出将成为单个功能。
  • @error 我明白了,非常感谢
  • @error 请给出答案

标签: python scikit-learn pca


【解决方案1】:

您得到的错误是由于plt.scatter 的输入形状不相等。 x_train 是一个有 17000 行和 9 列的数组。而y_train 是一个包含 17000 行和一列的数组。

您可以通过索引x_train 来修复该错误,并且只从其中选择一个列。

x_train[:,0] 选择x_train 的第一列。

另一种方法是将n_components 设置为1。n_components 确定pca 返回的特征数。设置为 1 返回 1 设置为 9 返回 9。

【讨论】:

  • 我虽然 n_features 代表我拥有的功能数量,但我错误地将它设置为 9,它应该是一个
猜你喜欢
  • 1970-01-01
  • 2014-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 2019-12-12
相关资源
最近更新 更多