时间序列预测-ARIMA

2024-08-23 13:38
文章标签 时间 预测 序列 arima

本文主要是介绍时间序列预测-ARIMA,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

参考资料1

https://pyflux.readthedocs.io/en/latest/arima.html#example

 

参考资料2

多元序列分析ARIMAX(p,I,q)

宇智波带土

宇智波带土

没事瞎折腾

4 人赞同了该文章

这里借助Python的statsmodels库和pyflux库进行多元时间序列分析,建立ARIMAX(p,I,q)模型用来预测二氧化碳浓度数据。其中pyflux库是一个专门用来建立时间序列模型的python库。该库的文档地址为:

https://pyflux.readthedocs.io/en/latest/getting_started.html​pyflux.readthedocs.io

 

文章中完整的jupyter notebook程序可在下面链接查看。

Jupyter Notebook Viewer​nbviewer.jupyter.org图标

数据集来自:

https://www.itl.nist.gov/div898/handbook/datasets/GAS_FURNACE.DAT​www.itl.nist.gov

 

 

1:数据准备和可视化

## 加载包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = "retina"
from matplotlib.font_manager import FontProperties
fonts = FontProperties(fname = "/Library/Fonts/华文细黑.ttf")import statsmodels.api as sm
import pyflux as pf
from sklearn.metrics import mean_absolute_error,mean_squared_error## 读取数据,数据来自https://www.itl.nist.gov/div898/handbook/datasets/GAS_FURNACE.DAT
datadf = pd.read_csv(".../data/gas furnace data.txt",sep="\s+")
datadf.columns = ["GasRate","C02"]
## GasRate:输入天然气速率,C02:输出二氧化碳浓度
datadf.head()

接下来可视化两列数据

## 可视化两列数据
plt.figure(figsize=(15,5))
plt.subplot(1,2,1)
datadf.GasRate.plot(c="r")
plt.xlabel("Observation")
plt.ylabel("Gas Rate")
plt.subplot(1,2,2)
datadf.C02.plot(c="r")
plt.xlabel("Observation")
plt.ylabel("C02")
plt.show()

切分数据集,前面百分之75做训练集,后面百分之25做测试集

## 前面百分之75做训练集,后面百分之25做测试集
trainnum = np.int(datadf.shape[0]*0.75)
traidata = datadf.iloc[0:trainnum,:]
testdata = datadf.iloc[trainnum:datadf.shape[0],:]
print(traidata.shape)
print(testdata.shape)(222, 2)
(74, 2)

2:平稳时间序列建模ARIMAX

2.1:单位根检验检验序列的平稳性

因为ARIMAX(p,i,q)要求所有的序列的是平稳的,所以要对序列进行单位根检验,判断序列的平稳性。

## 1:单位根检验检验序列的平稳性,ADF 检验
dftest = sm.tsa.adfuller(datadf.GasRate,autolag='BIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','Lags Used','Number of Observations Used'])
print("GasRate 检验结果:")
print(dfoutput)dftest = sm.tsa.adfuller(datadf.C02,autolag='BIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','Lags Used','Number of Observations Used'])
print("C02 检验结果:")
print(dfoutput)GasRate 检验结果:
Test Statistic                  -4.878952
p-value                          0.000038
Lags Used                        2.000000
Number of Observations Used    293.000000
dtype: float64
C02 检验结果:
Test Statistic                  -2.947057
p-value                          0.040143
Lags Used                        3.000000
Number of Observations Used    292.000000
dtype: float64

p-value均小于0.05,说明在置信度为95%水平下,两个序列均是平稳序列。

2.2:接下来可以可视化C02数据的自相关系数和偏相关系数。

## 可视化序列的自相关和偏相关图
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(211)
fig = sm.graphics.tsa.plot_acf(traidata.C02, lags=30, ax=ax1)
ax2 = fig.add_subplot(212)
fig = sm.graphics.tsa.plot_pacf(traidata.C02, lags=30, ax=ax2)
plt.subplots_adjust(hspace = 0.3)
plt.show()

2.3:接下来建立一个简单的ARIMAX模型,探索库中函数的相关使用方法。

## 建立ARIMAX(1,0,2)模型
model  = pf.ARIMAX(data=traidata,formula="C02~GasRate",ar=1,ma=2,integ=0)
model_1 = model.fit("MLE")
model_1.summary()Normal ARIMAX(1,0,2)                                                                                      
======================================================= ==================================================
Dependent Variable: C02                                 Method: MLE                                       
Start Date: 2                                           Log Likelihood: -71.9362                          
End Date: 221                                           AIC: 155.8725                                     
Number of observations: 220                             BIC: 176.2343                                     
==========================================================================================================
Latent Variable                          Estimate   Std Error  z        P>|z|    95% C.I.                 
======================================== ========== ========== ======== ======== =========================
AR(1)                                    0.9086     0.0191     47.5425  0.0      (0.8712 | 0.9461)        
MA(1)                                    1.0231     0.0552     18.5272  0.0      (0.9149 | 1.1314)        
MA(2)                                    0.6231     0.0442     14.1127  0.0      (0.5365 | 0.7096)        
Beta 1                                   4.8793     1.0166     4.7996   0.0      (2.8868 | 6.8719)        
Beta GasRate                             -0.4057    0.0533     -7.613   0.0      (-0.5102 | -0.3013)      
Normal Scale                             0.3356                                                           
==========================================================================================================

model_1.summary()方法可以输出模型的拟合的相关信息。

## 可视化模型在训练集上的拟合情况
model.plot_fit(figsize=(10,5))

model.plot_fit()方法可以将在训练数据中模型的拟合情况进行可视化。可以发现在训练集上模型的拟合效果很好。

## 可视化模型的在测试集上的预测结果
model.plot_predict(h=testdata.shape[0], ## 往后预测多少步oos_data=testdata,  ## 测试数据集past_values=traidata.shape[0], ## 图像显示训练集的多少数据 figsize=(15,5))
## 可视化原始数据
datadf.C02.plot(figsize=(15,5))
plt.xlabel("Time")
plt.ylabel("C02")
plt.show()

model.plot_predict()方法可以将预测结果可视化

使用model.predict()方法可以用来预测新的数据集

## 预测新的数据
C02pre = model.predict(h=testdata.shape[0], ## 往后预测多少步oos_data=testdata,  ## 测试数据集intervals=True, ## 同时预测置信区间)
print("在测试集上mean absolute error:",mean_absolute_error(testdata.C02,C02pre.C02))
print("在测试集上mean squared error:",mean_squared_error(testdata.C02,C02pre.C02))
C02pre.head()在测试集上mean absolute error: 1.5731456243696424
在测试集上mean squared error: 3.8376299478820215

## 可视化原始数据和预测数据进行对比
datadf.C02.plot(figsize=(15,5),c="b",label="C02")
C02pre.C02.plot(c = "r",label="Prediction")
plt.xlabel("Time")
plt.ylabel("C02")
plt.legend(loc=0)
plt.show()

从图像上可以看出预测的效果和实际数据的差异。

3.通过遍历寻找合适的P,Q

p = np.arange(6)
q = np.arange(6)
pp,qq = np.meshgrid(p,q)
resultdf = pd.DataFrame(data = {"arp":pp.flatten(),"mrq":qq.flatten()})
resultdf["bic"] = np.double(pp.flatten())
resultdf["mae"] = np.double(qq.flatten())
## 迭代循环建立多个模型
for ii in resultdf.index:model_i = pf.ARIMAX(data=traidata,formula="C02~GasRate",ar=resultdf.arp[ii],ma=resultdf.mrq[ii],integ=0)try: modeli_fit = model_i.fit("MLE")bic = modeli_fit.bicC02_pre = model.predict(h=testdata.shape[0],oos_data=testdata)mae = mean_absolute_error(testdata.C02,C02_pre.C02)except:bic = np.nanresultdf.bic[ii] = bicresultdf.mae[ii] = mae
print("模型迭代结束")模型迭代结束## 按照BIC寻找合适的模型
resultdf.sort_values(by="bic").head()

## 重新建立效果较好的模型
model  = pf.ARIMAX(data=traidata,formula="C02~GasRate",ar=4,ma=1,integ=0)
model_1 = model.fit("MLE")
model_1.summary()Normal ARIMAX(4,0,1)                                                                                      
======================================================= ==================================================
Dependent Variable: C02                                 Method: MLE                                       
Start Date: 4                                           Log Likelihood: 21.1205                           
End Date: 221                                           AIC: -26.2409                                     
Number of observations: 218                             BIC: 0.835                                        
==========================================================================================================
Latent Variable                          Estimate   Std Error  z        P>|z|    95% C.I.                 
======================================== ========== ========== ======== ======== =========================
AR(1)                                    2.4472     0.0647     37.8416  0.0      (2.3205 | 2.574)         
AR(2)                                    -2.1984    0.1625     -13.5296 0.0      (-2.5169 | -1.8799)      
AR(3)                                    0.7821     0.149      5.2483   0.0      (0.49 | 1.0741)          
AR(4)                                    -0.0596    0.0496     -1.2008  0.2298   (-0.1569 | 0.0377)       
MA(1)                                    -0.9278    0.0268     -34.6168 0.0      (-0.9803 | -0.8752)      
Beta 1                                   1.5274     0.1027     14.869   0.0      (1.326 | 1.7287)         
Beta GasRate                             -0.1015    0.0071     -14.2897 0.0      (-0.1154 | -0.0876)      
Normal Scale                             0.2189                                                           
==========================================================================================================## 可视化潜在变量
model.plot_z()

model.plot_z()可以对潜在变量进行可视化

预测新的数据并可视化

## 预测新的数据
C02pre = model.predict(h=testdata.shape[0], ## 往后预测多少步oos_data=testdata,  ## 测试数据集)
print("在测试集上mean absolute error:",mean_absolute_error(testdata.C02,C02pre.C02))
## 可视化原始数据和预测数据进行对比
datadf.C02.plot(figsize=(15,5),c="b",label="C02")
C02pre.C02.plot(c = "r",label="Prediction")
plt.xlabel("Time")
plt.ylabel("C02")
plt.legend(loc=0)
plt.show()

这篇关于时间序列预测-ARIMA的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1099539

相关文章

如何利用Java获取当天的开始和结束时间

《如何利用Java获取当天的开始和结束时间》:本文主要介绍如何使用Java8的LocalDate和LocalDateTime类获取指定日期的开始和结束时间,展示了如何通过这些类进行日期和时间的处... 目录前言1. Java日期时间API概述2. 获取当天的开始和结束时间代码解析运行结果3. 总结前言在J

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

关于最长递增子序列问题概述

《关于最长递增子序列问题概述》本文详细介绍了最长递增子序列问题的定义及两种优化解法:贪心+二分查找和动态规划+状态压缩,贪心+二分查找时间复杂度为O(nlogn),通过维护一个有序的“尾巴”数组来高效... 一、最长递增子序列问题概述1. 问题定义给定一个整数序列,例如 nums = [10, 9, 2

修改若依框架Token的过期时间问题

《修改若依框架Token的过期时间问题》本文介绍了如何修改若依框架中Token的过期时间,通过修改`application.yml`文件中的配置来实现,默认单位为分钟,希望此经验对大家有所帮助,也欢迎... 目录修改若依框架Token的过期时间修改Token的过期时间关闭Token的过期时js间总结修改若依

Go Mongox轻松实现MongoDB的时间字段自动填充

《GoMongox轻松实现MongoDB的时间字段自动填充》这篇文章主要为大家详细介绍了Go语言如何使用mongox库,在插入和更新数据时自动填充时间字段,从而提升开发效率并减少重复代码,需要的可以... 目录前言时间字段填充规则Mongox 的安装使用 Mongox 进行插入操作使用 Mongox 进行更

对postgresql日期和时间的比较

《对postgresql日期和时间的比较》文章介绍了在数据库中处理日期和时间类型时的一些注意事项,包括如何将字符串转换为日期或时间类型,以及在比较时自动转换的情况,作者建议在使用数据库时,根据具体情况... 目录PostgreSQL日期和时间比较DB里保存到时分秒,需要和年月日比较db里存储date或者ti

Python 标准库time时间的访问和转换问题小结

《Python标准库time时间的访问和转换问题小结》time模块为Python提供了处理时间和日期的多种功能,适用于多种与时间相关的场景,包括获取当前时间、格式化时间、暂停程序执行、计算程序运行时... 目录模块介绍使用场景主要类主要函数 - time()- sleep()- localtime()- g

如何用Java结合经纬度位置计算目标点的日出日落时间详解

《如何用Java结合经纬度位置计算目标点的日出日落时间详解》这篇文章主详细讲解了如何基于目标点的经纬度计算日出日落时间,提供了在线API和Java库两种计算方法,并通过实际案例展示了其应用,需要的朋友... 目录前言一、应用示例1、天安门升旗时间2、湖南省日出日落信息二、Java日出日落计算1、在线API2

如何使用 Bash 脚本中的time命令来统计命令执行时间(中英双语)

《如何使用Bash脚本中的time命令来统计命令执行时间(中英双语)》本文介绍了如何在Bash脚本中使用`time`命令来测量命令执行时间,包括`real`、`user`和`sys`三个时间指标,... 使用 Bash 脚本中的 time 命令来统计命令执行时间在日常的开发和运维过程中,性能监控和优化是不

python中的与时间相关的模块应用场景分析

《python中的与时间相关的模块应用场景分析》本文介绍了Python中与时间相关的几个重要模块:`time`、`datetime`、`calendar`、`timeit`、`pytz`和`dateu... 目录1. time 模块2. datetime 模块3. calendar 模块4. timeit