【发布时间】:2020-07-04 10:47:22
【问题描述】:
我是 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.
【问题讨论】:
-
请edit 包含完整的错误回溯,以查看导致错误的行;话虽如此,您是否按照错误消息的提示进行操作? “如果您的数据具有单个特征,请使用
array.reshape(-1, 1),如果包含单个样本,请使用array.reshape(1, -1)”? -
-@G.Anderson,错误与定义的函数“train”有关。完整的错误回溯给出了这个消息。我不得不从错误中删掉几句话以在此处适合此消息:----> 9 model = train(x,y) ----> 6 model = LinearRegression().fit(x,y) - -> 463 y_numeric=True, multi_output=True) --> 719 estimator=estimator) --> 521 "如果它包含单个样本。".format(array))
-
它告诉你问题:“预期的二维数组,得到一维数组”,它告诉你解决方案:
array.reshape(-1, 1),所以你有没有尝试将你的数据重塑成正确的形状,并且你的结果是什么? -
_@G.Anderson,由于我是这个领域的新手,我不知道如何重塑数据,到目前为止我没有得到任何结果。
-
-@AMC,我不明白错误消息的内容,也不明白给定错误消息中建议的解决方案是什么。
标签: python scikit-learn linear-regression