繁体   English   中英

如何修复我在 scikit-learn 中的线性回归中得到的错误

[英]How fix the error that I got in linear regression in scikit-learn

我是 Python 中线性回归概念的新手。 我在 scikit-learn 中使用线性回归来找到 y 的预测值,这里称为 y_new。 以下代码是我迄今为止编写的脚本:

import numpy as np 
#creating data for the run
x=spendings = np.linspace(0,5,4000)
y=sales = np.linspace(0,0.5,4000)
#defining the training function
def train(x,y):
    from sklearn.linear_model import LinearRegression
    model = LinearRegression().fit(x,y)
    return model 
model = train(x,y)
x_new = 23.0
y_new = model.predict([[x_new]])
print(y_new)

由于此错误消息,我无法获取 y_new 的值:

Expected 2D array, got 1D array instead:
array=[0.00000000e+00 1.25031258e-03 2.50062516e-03 ... 4.99749937e+00
 4.99874969e+00 5.00000000e+00].
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. 

根据LinearRegression fit 方法的文档预计 X 和 y 输入为(n_samples, n_features)形状。

如果你检查你的 x 和 y 形状,它是这样的

x=spendings = np.linspace(0,5,4000)
y=sales = np.linspace(0,0.5,4000)
print(x.shape)
print(y.shape)

(4000,)
(4000,)

什么错误说,你需要使用arr.reshape(-1,1)重塑你的 x 和 y 以塑造(n_samples, n_features arr.reshape(-1,1) 所以你需要的是在适合 LinearRegression 之前重塑你的 x 和 y。

x = x.reshape(-1,1)
y = y.reshape(-1,1)
print(x.shape)
print(y.shape)
(4000, 1)
(4000, 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM