簡體   English   中英

如何在 python 中使用 .predict() 方法進行線性回歸?

[英]How to use .predict() method in python for linear regression?

我從我的 dataframe 估計了多元回歸 model。 我有三個獨立變量:月份(1 到 36)、價格和廣告日。

我想做出預測,改變條件:

- 未來 10 個月(37 到 47)的預測值,價格 = 85,廣告日 = 4

我估計我的 model 並嘗試:

Time1= np.arange(37,48)
Price1=85
Ads1=4
Lm.predict([Time1,Price1,Ads1])

但它不起作用

謝謝

你需要有一個二維數組

Lm.predict([[Time1,Price1,Ads1]])

假設您的 model 在沒有任何嵌套 arrays 的 2D 陣列上進行了訓練,問題是:

  1. 您要預測的輸入不是 2D
  2. 變量Time1本身就是一個數組,因此,您創建了一個嵌套數組: [Time1,Price1,Ads1]

您當前的預測調用如下所示:

Time1 = np.arange(37,48)
Price1=85
Ads1=4
print([Time1,Price1,Ads1])

看起來像:

[array([37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47]), 85, 4]

您可以將其轉換為所需的格式,如下所示:

import numpy as np
print(np.concatenate([Time1, [Price1, Ads1]]).reshape(1,-1))

這看起來像:

array([[37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 85,  4]])

首先使用過去觀察的訓練數據訓練 model。 在您的情況下,火車數據構成每個觀察的 3 個三個自變量和 1 個因變量。

一旦訓練了像樣的 model(使用超參數優化),您就可以使用它來進行預測。

示例代碼(內聯記錄)

import numpy as np
from sklearn.linear_model import LinearRegression

# sample dummy data 

# independent variables
time = np.arange(1,36)
price = np.random.randint(1,100,35)
ads = np.random.randint(1,10,35)
# dependent variable
y = np.random.randn(35)

# Reshape it into 35X3 where each row is an observation
train_X = np.vstack([time, price, ads]).T

# Fit the model
model = LinearRegression().fit(train_X, y)

# Sample observations for which 
# forecast of dependent variable has to be made
time1 = np.arange(37, 47)
price1 = np.array([85]*len(time1))
ads1 = np.array([4]*len(time1))

# Reshape such that each row is an observation
test_X = np.vstack([time1, price1, ads1]).T

# make the predictions
print (model.predict(test_X))'

Output:

array([0.22189608, 0.2269302 , 0.23196433, 0.23699845, 0.24203257,
       0.24706669, 0.25210081, 0.25713494, 0.26216906, 0.26720318])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM