属性错误:“OLSResults”对象没有属性预测

问题描述 投票:0回答:0

运行以下脚本时,在forecast=model.forecast 后显示错误信息。 这是脚本:

import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt

df = pd.read_excel('testregressiondata.xlsx')


y = df['Load']
X_all = df[['HDDs', 'Wind']]`
X_labels = ['HDDs', 'Wind'] 

获取用户输入以包含和排除自变量

while True:
    print(f'Independent variables in dataset: {X_labels}')
    include = input('Enter independent variables to include (comma-separated): ')
    exclude = input('Enter independent variables to exclude (comma-separated): ')
    if include == '' and exclude == '':
        print('Please enter at least one independent variable to include or exclude.')
    else:
        include = include.split(',') if include else []
        exclude = exclude.split(',') if exclude else []
        if not set(include).issubset(X_labels):
            print('One or more included independent variables are not in the dataset.')
        elif not set(exclude).issubset(X_labels):
            print('One or more excluded independent variables are not in the dataset.')
        else:
            break

根据用户输入过滤自变量

X_labels = [x for x in X_labels if x not in exclude]
X_labels += include
X = X_all[X_labels]

将常量添加到自变量

X = sm.add_constant(X)

执行回归分析

model = sm.OLS(y, X).fit()

打印回归结果

print(model.summary())

对接下来的5个时期进行动态预测

forecast = model.forecast(steps=5, exog=X[-5:])
forecast_index = pd.date_range(start=df.index[-1], periods=5, freq='M')

使用预测的最佳拟合线创建图表

fig, ax = plt.subplots()
ax.plot(df.index, y, label='Actual Data')
ax.plot(forecast_index, forecast, label='Forecasted Data')
ax.set_xlabel('Date')
ax.set_ylabel('A')
ax.legend()

显示图表与预测的最佳拟合线

plt.show()

有什么我可以解决的想法吗?非常感谢所有帮助。 谢谢

python statsmodels attributeerror forecasting
© www.soinside.com 2019 - 2024. All rights reserved.