import pandas as pdimport numpy as npfrom sklearn import linear_modelimport matplotlib.pyplot as pltdf = pd.read_csv('homeprices.csv')plt.xlabel('area')plt.ylabel('price')plt.scatter(df.area,df.price,color='red',marker='.')reg = linear_model.LinearRegression()reg.fit(df.area,df.price)
错误信息:
ValueError: 期望得到二维数组,但得到的是一维数组:array=[2600 3000 3200 3600 4000]。如果您的数据只有一个特征,请使用 array.reshape(-1, 1) 重塑数据;如果数据包含单个样本,请使用 array.reshape(1, -1) 重塑数据。
如果我这样写,代码可以正常运行:
reg.fit(df[['area']],df.price)
我想知道背后的原因,因为第二个参数是作为 df.price 传递的。
我的 CSV 文件内容如下:
- area,price
- 2600,550000
- 3000,565000
- 3200,610000
- 3600,680000
- 4000,725000
回答:
根据文档,变量 x 应声明为
X{array-like, sparse matrix} of shape (n_samples, n_features)
当你声明时:
-
x = df.area
或x = df['area']
,x
将变成Series
类型,大小为(n,)
。大小应为(n, z)
,其中z
可以是任何正整数。 -
x = df[['area']]
,x
将变成DataFrame
类型,大小为(5, 1)
,这使得x
成为可接受的输入。 -
y = df.price
,y
将变成Series
类型,大小为(5,)
,这是一个可接受的输入。
y: array-like of shape (n_samples,)
但如果我是你,我会这样声明 x
和 y
:
x = [[i] for i in df['area']]y = [i for i in df['price']]
这使得 x
和 y
都成为 list
结构,并将大小设置为 (5, 1)
,这样将来如果您想在任何机器学习库(tensorflow, pytorch, keras, …)中运行,就不会遇到任何困难。