python-arima模型statsmodels库实现-有数据集(续)-statsmodels-0.9.0版本

2023-10-13 02:12

本文主要是介绍python-arima模型statsmodels库实现-有数据集(续)-statsmodels-0.9.0版本,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

python-arima模型statsmodels库实现-有数据集(续)

这篇博客是上一篇python-arima模型statsmodels库实现的续集,上一篇采用的statsmodels版本应该要高一点,如果使用低版本的statsmodels代码会有bug,这一篇则是针对statsmodels-0.9.0版本的代码。

代码如下:

#coding=gbk
import  numpy  as np
import pandas as pd
import os
from numpy import NaN
from numpy import nan
import matplotlib.pyplot as plt
import statsmodels.api as sm     #acf,pacf图
from statsmodels.tsa.stattools import adfuller  #adf检验
from pandas.plotting import autocorrelation_plot
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.stats.diagnostic import acorr_ljungboximport statsmodels.api as sm
import matplotlib as mpl
path="E:/data/china_data.xlsx"
# 为了控制计算量,我们限制AR最大阶不超过6,MA最大阶不超过4。plt.style.use('fivethirtyeight')
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['font.serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
df=pd.read_excel(path)
#print(df)
#help(df)#for index, row in df.iterrows():df=df.replace(NaN, "null")
#  print(index, row)
print(df)
def  f(column):r=0inde1=0index2=len(column)-1for i in range(len(column)):#   print(column[len(column)-i-1])if   column[len(column)-i-1] is "null" and r==1:index2=ireturn index1,index2if   column[len(column)-i-1]!= "null" and r==0:index1=ir=1return index1,index2#df['时间(年)']=pd.to_datetime(df['时间(年)'])print(df.columns)
print(df[df.columns[0]])
indexz=df.columns[0]def adf_test(data):#小于0.05则是平稳序列# print("data:",data.values)data_z=np.array(list(data.values))#print(data_z.reshape(-1,))t = adfuller(data_z.reshape(-1,))print("p-value:",t[1])
def  box_pierce_test(data):#小于0.05,不是白噪声序列print(acorr_ljungbox(data, lags=1)) def  stability_judgment(data):fig = plt.figure(figsize=(12,8))ax1=fig.add_subplot(211)fig = sm.graphics.tsa.plot_acf(data,lags=5,ax=ax1)ax2 = fig.add_subplot(212)fig = sm.graphics.tsa.plot_pacf(data,lags=5,ax=ax2)plt.show()def  model_fit(data,df,index,length,index1,index2):data_diff=df[["时间(年)",index]][length-index2:length-index1]#  sm.tsa.arma_order_select_ic(data_diff,max_ar=6,max_ma=4,ic='aic')['aic_min_order']  # AIC#对模型进行定阶pmax = int(len(data) / 10)    #一般阶数不超过 length /10qmax = int(len(data) / 10)if  pmax>4:pmax=6if  qmax>4:qmax=4bic_matrix = []print("data",data)# help(sm.tsa.arima.ARIMA)for p in range(pmax +1):temp= []for q in range(qmax+1):try:#  ARIMA(train_data, order=(1,1,1))# print(sm.tsa.arima.ARIMA(data,order=(p,1,q)).fit())temp.append(sm.tsa.ARIMA(data,order=(p,1,q)).fit().bic)#  print(temp)except:temp.append(None)# temp.append(sm.tsa.arima.ARIMA(data,order=(p,1,q)).fit().bic)bic_matrix.append(temp)bic_matrix = pd.DataFrame(bic_matrix)   #将其转换成Dataframe 数据结构print("bic_matrix",bic_matrix)p,q = bic_matrix.stack().astype(float).idxmin()   #先使用stack 展平, 然后使用 idxmin 找出最小值的位置print(u'BIC 最小的p值 和 q 值:%s,%s' %(p,q))  #  BIC 最小的p值 和 q 值:0,1model = sm.tsa.ARIMA(data, order=(p,1,q)).fit()model.summary()        #生成一份模型报告predictions_ARIMA_diff = pd.Series(model.fittedvalues, copy=True)print(predictions_ARIMA_diff)model.forecast(5)   #为未来5天进行预测, 返回预测结果, 标准误差, 和置信区间for index, column in df.iteritems():if index==indexz:continueindex1,index2 =f(column)length=len(column)# print("index1 index2:",index1,index2)#  print(column[length-index2-1:length-index1])print(index)df[index]=df[index].replace( "null",0)df[index].astype('float')df[str(index)+"diff1"]=df[index].diff(1)df[str(index)+"diff2"]=df[index+"diff1"].diff(1)# 一阶差分还原# tmpdata2:原数据# pred:一阶差分后的预测数据#df_shift = tmpdata2['ecpm_tomorrow'].shift(1)#predict = pred.add(df_shift)# predict = pred + df_shift# print(index2-index1)#print(df[["时间(年)",index]][length-index2:length-index1])adf_test(df[[index]][length-index2:length-index1])box_pierce_test(df[[index]][length-index2:length-index1])model_fit(df[[index]][length-index2:length-index1],df,index,length,index1,index2)## model_fit(data,p,q)stability_judgment(df[[index]][length-index2:length-index1])stability_judgment(df[[str(index)+"diff1"]][length-index2:length-index1])#  stability_judgment(df[[str(index)+"diff2"]][length-index2:length-index1])plt.plot(df[["时间(年)"]][length-index2:length-index1],df[[index]][length-index2:length-index1],label="diff0")plt.plot(df[["时间(年)"]][length-index2:length-index1],df[[str(index)+"diff1"]][length-index2:length-index1],label="diff1")#   plt.plot(df[["时间(年)"]][length-index2:length-index1],df[[str(index)+"diff2"]][length-index2:length-index1],label="diff2")# df[["时间(年)",index]][length-index2:length-index1].plot(x=indexz,y=index,figsize=(9,9))plt.xlabel("时间(年)")plt.ylabel(index)plt.legend()plt.show()os.system("pause")

运行结果如下:
在这里插入图片描述
大家可在这里插入图片描述

大家可以学习一下哈。

这篇关于python-arima模型statsmodels库实现-有数据集(续)-statsmodels-0.9.0版本的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

SpringBoot集成redisson实现延时队列教程

《SpringBoot集成redisson实现延时队列教程》文章介绍了使用Redisson实现延迟队列的完整步骤,包括依赖导入、Redis配置、工具类封装、业务枚举定义、执行器实现、Bean创建、消费... 目录1、先给项目导入Redisson依赖2、配置redis3、创建 RedissonConfig 配

SpringBoot分段处理List集合多线程批量插入数据方式

《SpringBoot分段处理List集合多线程批量插入数据方式》文章介绍如何处理大数据量List批量插入数据库的优化方案:通过拆分List并分配独立线程处理,结合Spring线程池与异步方法提升效率... 目录项目场景解决方案1.实体类2.Mapper3.spring容器注入线程池bejsan对象4.创建

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF