image
LP小透明

当你感到无聊的时候,就去学习,因为一旦你开始认真学习,就会立刻发现比学习有趣的事来打断你的学习

Python-ARIMA

LP小透明    2019-06-27 17:01

 

这是一个关于洗发水预测的例子。数据集下载:shampoo.csv
首先,我们将保留最后一年的数据并评估此数据的预测。 鉴于数据是每月一次,这意味着最后12个观测值将用作测试数据。

我们将使用前瞻性验证方法来评估模型性能。 这意味着将枚举测试数据集中的每个时间步,在历史数据上构建模型,并将预测与预期值进行比较。 然后将观察结果添加到训练数据集中并重复该过程。

前瞻性验证是评估时间序列预测模型的现实方法,因为人们可以期望在新观察结果可用时更新模型。

最后,将使用均方根误差或RMSE来评估预测。 RMSE的好处在于它会对大错误进行处罚,并且得分与预测值(每月汽车销售额)的单位相同。

ARIMA(4,1,0)预测模型将用作探索模型的其他参数的基线。 这可能不是该问题的最佳模型,但通常对某些其他手动测试配置非常熟练。

总之,测试工具包括:

最近2年的数据使用了测试集。

模型评估的前瞻性验证。

用于报告模型技能的均方根误差。

ARIMA(4,1,0)模型将用作基线。

完整的代码:

from pandas import read_csv
from pandas import datetime
from pandas import DataFrame
from statsmodels.tsa.arima_model import ARIMA
from matplotlib import pyplot
from sklearn.metrics import mean_squared_error
 

def parser(x):
    ''' 解析时间标签
    '''
    return datetime.strptime('190'+x, '%Y-%m')

# 读取csv数据 
series = read_csv('./data/shampoo.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
X = series.values
# 生成训练集和测试集
size = int(len(X) * 0.66)
train, test = X[0:size], X[size:len(X)]
# 根据训练集获取历史数据
history = [x for x in train]
predictions = list()

for t in range(len(test)):
    # 模型参数 p = 5, d = 1, q = 0
    model = ARIMA(history, order=(5, 1, 0))
    model_fit = model.fit(disp=0)
    output = model_fit.forecast()
    yhat = output[0]
    # 预测值
    predictions.append(yhat)
    # 观测值
    obs = test[t]
    history.append(obs)
    # 打印观测值和预测值
    print('predicted=%f, expected=%f' % (yhat, obs))

# MSE是网络的均方误差
error = mean_squared_error(test, predictions)
print('Test MSE: %.3f' % error)

# plot 绘图
pyplot.plot(test)
pyplot.plot(predictions, color='red')
pyplot.show()
运行结果:
 
References:
  1. https://machinelearningmastery.com/tune-arima-parameters-python/
Last Modified: 2019-07-01 21:00
Views: 2.0K

[[total]] comments

Post your comment
  1. [[item.time]]
    [[item.user.username]] [[item.floor]]Floor
  2. Click to load more...
  3. Post your comment