[英]How fix the error that I got in linear regression in scikit-learn
I am new in the concept of linear regression in Python.我是 Python 中线性回归概念的新手。 I am using the linear regression in scikit-learn to find the predicted value of y, here it is called y_new.我在 scikit-learn 中使用线性回归来找到 y 的预测值,这里称为 y_new。 The below code is what I have scripted so far:以下代码是我迄今为止编写的脚本:
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)
I can't get the value of the y_new due to this error message:由于此错误消息,我无法获取 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.
According to the documentation of LinearRegression fit method expects X and y input to be (n_samples, n_features) shape.根据LinearRegression fit 方法的文档预计 X 和 y 输入为(n_samples, n_features)形状。
if you check your x and y shapes,it is like this如果你检查你的 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,)
what error says,you need to reshape your x and y to shape (n_samples, n_features) using arr.reshape(-1,1)
.什么错误说,你需要使用arr.reshape(-1,1)
重塑你的 x 和 y 以塑造(n_samples, n_features arr.reshape(-1,1)
。 so what you need is reshape your x and y before fit to the LinearRegression.所以你需要的是在适合 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.