【问题标题】:How to reshape 'year' from a single feature?如何从单一特征重塑“年份”?
【发布时间】:2021-09-23 23:46:51
【问题描述】:

我有一个包含“年”和“人均收入(美元)”列的 df。

plt.scatter(df.year, df['per capita income (US$)'], color='red')
plt.xlabel('Year')
plt.ylabel('Per Capita Income (US$)')
plt.show()

reg = linear_model.LinearRegression()
reg.fit(df[['year']], df['per capita income (US$)'])

reg.predict(2011) 

收到错误消息:

ValueError: Expected 2D array, got scalar array instead:
array=2011.
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

我将 reg.predict() 的调用调整为:

reg.predict([[2011]])

代码执行没有错误,但是.predict() 函数没有返回所需的输出。

print(df.columns)

Index(['year', 'per capita income (US$)'], dtype='object')

【问题讨论】:

  • 能分享一下数据集的基本格式吗? (以及你得到的结果)在 ML 中,构成数据集的格式和数据类型与模型本身同样重要。我无法重现您的错误,因为我没有数据,但我的第一直觉是您的 df['perpersonal income (US$)'] 可能是字符串格式,而不是 double/float/int 等...
  • 更新了原始问题!感谢您的及时回复!
  • df['year'] 是一个整数。 xxxx 格式,而 df['人均收入 (USD$)'] 是浮点数。 xxxx.xxxx 格式。

标签: python machine-learning scikit-learn linear-regression


【解决方案1】:

您应该将您的 X 重塑为 2D 数组而不是 1D 数组。拟合模型需要一个二维数组。即(n_samples,n_features)。
当您使用.reshape(-1,1) 时,它会向数据添加一维。

X = df['year'].values.reshape(-1,1)
y = df['per capita income (US$)'].values
reg = linear_model.LinearRegression()
reg.fit(X,y)
print(reg.predict([[2011]]))

【讨论】:

  • 这是针对所提供问题的最佳解决方案说明。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-10
  • 2018-11-18
  • 1970-01-01
  • 2018-10-10
  • 2020-07-03
  • 2020-05-21
  • 1970-01-01
相关资源
最近更新 更多