如何在python中使用.predict()方法进行线性回归?

2024-09-24 22:29:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我根据我的数据框估计了多元回归模型。我有三个独立变量:月份(1到36),价格和广告日

我想做出预测,改变条件:

-未来10个月(37至47)的预测值,价格=85,广告日=4

我评估了我的模型并尝试:

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

但它不起作用

谢谢


Tags: 数据模型np价格条件predict广告lm
3条回答

首先使用过去观测的训练数据训练模型。在您的情况下,列车数据由3个自变量和1个因变量组成

一旦一个像样的模型得到训练(使用超参数优化),你就可以用它来做预测

示例代码(内联文档化)

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))'

输出:

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

假设您的模型是在没有任何嵌套阵列的二维阵列上训练的,则问题如下:

  1. 您要预测的输入不是2D
  2. 变量Time1本身就是一个数组,因此,您创建了一个嵌套数组:[Time1,Price1,Ads1]

您当前对predict的调用如下所示:

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]])

你需要有一个二维数组

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

相关问题 更多 >