我一直在尝试使用 sklearn 进行线性回归。有时会遇到值错误,有时又能正常运行。我不确定应该使用哪种方法。错误信息如下:
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/linear_model/base.py", line 512, in fit y_numeric=True, multi_output=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 531, in check_X_y check_consistent_length(X, y) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 181, in check_consistent_length " samples: %r" % [int(l) for l in lengths])ValueError: Found input variables with inconsistent numbers of samples: [1, 200]
代码大致如下:
import pandas as pdfrom sklearn.linear_model import LinearRegressiondata = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0);x = data['TV']y = data['Sales']lm = LinearRegression()lm.fit(x,y)
请帮帮我。我是一名学生,正在学习机器学习的基础知识。
回答:
lm.fit
期望 X
是一个
numpy 数组或稀疏矩阵,形状为 [n_samples,n_features]
你的 x
的形状是:
In [6]: x.shapeOut[6]: (200,)
只需使用:
lm.fit(x.reshape(-1,1) ,y)