Sklearn一元线性回归的程序
from sklearn.linear_model import LinearRegression
#创建并拟合模型
model = LinearRegression()
X = [[6],[8],[10],[14],[18]]
Y = [[7],[9],[13],[17.5],[18]]
model.fit(X,Y)
print("预测12英寸披萨价格:$%.2f"%model.predict([12])[0])
运行出现问题
ValueError: Expected 2D array, got 1D array instead:
array=[12].
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数组——[12]。
如果数据具有单个功能,则使用array.reshape(-1,1)重整数据;如果包含单个样本,则使用array.reshape(1,-1)重整数据。
总之一句话,用array.reshape(1,-1)重整数据。
解决方法
增加第二行和修改最后一行。第二行调用是为了使用reshape函数。最后一行以np.array(矩阵).reshape(-1,1)的形式进行reshape。
from sklearn.linear_model import LinearRegression
import numpy as np
#创建并拟合模型
model = LinearRegression()
X = [[6],[8],[10],[14],[18]]
Y = [[7],[9],[13],[17.5],[18]]
model.fit(X,Y)
print("预测12英寸披萨价格:$%.2f"%model.predict(np.array([12]).reshape(-1, 1))[0])
笔者的其他博客,欢迎大家阅读学习,共同进步
傻瓜攻略(一)——MATLAB主成分分析代码及结果分析实例