在用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) #最小二乘建模
上面的代码报错,于是根据错误提示,修改后代码如下:
#修改后的代码
import numpy as np
from ma

在使用sklearn的LinearRegression进行最小二乘拟合时,遇到ValueError,提示需要2D数组而非1D。解决方案是通过reshape方法调整数据形状。例如,对于单特征数据,使用array.reshape(-1, 1)。通过实例展示,当预测x=30时,需传入类似模型训练数据格式的值进行预测。"
748920,114127,DirectX Graphics中的Mesh详解,"['3D模型', 'DirectX', '图形编程', '游戏开发', '数据结构']
最低0.47元/天 解锁文章
1364

被折叠的 条评论
为什么被折叠?



