在用sklearn的LinearRegression做最小二乘时遇到如下错误:
ValueError: Expected 2D array, got 1D array instead:
array=[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.
翻译过来是:
ValueError:预期为2D数组,改为获取1D数组:
数组= [5.]。
如果数据具有单个功能,则使用array.reshape(-1,1)重整数据;如果包含单个样本,则使用array.reshape(1,-1)重整数据。
也就是需要使用reshape改变原始数组的形状。
下面拿一个简单例子来说明:
#原来的代码
import numpy as np
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
#目的:建立x与y的最小二乘方程
x=np.array([2,5,8,8,13,15,17,19,21,24])
y=np.array([12,31,45,52,79,85,115,119,135,145])
plt.scatter(x,y) #查看散点图
regression=LinearRegression()
model=regression.fit(x,y