# 用训练集的数据进行训练
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
# regressor = regressor.fit(X_train, Y_train) # 版本过高,fit方法的参数形式改变
# print(help(regressor.fit))
regressor = regressor.fit(X_train.reshape(-1, 1), Y_train.reshape(-1, 1))
# 对测试集进行预测
Y_pred = regressor.predict(X_test.reshape(-1, 1))
报错提示信息
ValueError: Expected 2D array, got 1D array instead:array=[7.8 6.9 1.1 5.1 7.7 3.3 8.3 9.2 6.1 3.5 2.7 5.5 2.7 8.5 2.5 4.8 8.9 4.5].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.
报错原因
报错提示:参数的shape不对,高版本的sklaearn的LinearRegression中的fit方法的参数要求改变。可通过help(regressor.fit)查看具体的参数要求
解决办法
因为这里只是对单变量线性回归,所以变成一维的行向量即可。
regressor = regressor.fit(X_train.reshape(-1, 1), Y_train.reshape(-1, 1))
注意事项
在调用Y_pred = regressor.predict(X_test.reshape(-1, 1))时,需要注意predict的参数形状,否则也会报错!