簡體   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