当前位置: 首页 > news >正文

时序预测SARIMAX模型

1. 项目背景

本文基于kaggle平台相关竞赛项目,具体连接如下:

Time Series Forecasting With SARIMAX

基本信息如内容说明、数据集、已提交代码、当前得分排名以及比赛规则等,如图【1】所示,可以认真阅读。

图 1

2. 数据读取

使用python得pandas包进行csv文件读取

# read train data
df = pd.read_csv("/kaggle/input/daily-climate-time-series-data/DailyDelhiClimateTrain.csv", parse_dates=['date'],  # change to date time formatindex_col="date")
df

2.1 数据信息图形化观测

定义图表模板,对不同维度的数据进行图形化分析。

# Get the 'xgridoff' template
grid_template = pio.templates['xgridoff']
grid_template.layout.font.color = 'black'  # Light gray font color# Adjust gridline color and width
grid_template.layout.xaxis.gridcolor = 'rgba(0, 0, 0, 0.3)'  # Light gray with transparency
grid_template.layout.yaxis.gridcolor = 'rgba(0, 0, 0, 0.3)'  # Light gray with transparency
grid_template.layout.xaxis.gridwidth = 1  # Set gridline width
grid_template.layout.yaxis.gridwidth = 1  # Set gridline width# Update Plotly templates with template
pio.templates['ts_template'] = grid_template# plot mean temperature, humidity, wind_speed, meanpressure for watch
fig_meantemp = px.line(df, x=df.index, y='meantemp', title='Mean Temperature Over Time')
fig_meantemp.update_layout(template='ts_template', title_x=0.5, xaxis_title="Date")
fig_meantemp.show()fig_humidity = px.line(df, x=df.index, y='humidity', title='Humidity Over Time')
fig_humidity.update_layout(template='ts_template', title_x=0.5, xaxis_title="Date")
fig_humidity.show()fig_wind_speed = px.line(df, x=df.index, y='wind_speed', title='Wind Speed Over Time')
fig_wind_speed.update_layout(template='ts_template', title_x=0.5, xaxis_title="Date")
fig_wind_speed.show()fig_meanpressure = px.line(df, x=df.index, y='meanpressure', title='Mean Pressure Over Time')
fig_meanpressure.update_layout(template='ts_template', title_x=0.5, xaxis_title="Date")
fig_meanpressure.show()

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
可以从图中看到平均温度,湿度,风速,气压等数据波形图,也可以宏观的看到数据的趋势信息,为后续进一步学习做初步探索。

2.3 数据分量

针对预测数据项平均温度,我们可以分解平均温度数据,进一步分析数据形态、特征。seasonal_decompose函数返回的是trend、seasonal和residual分别表示趋势、季节性和残留三部分的数据,observed代表原始序列。

from statsmodels.tsa.seasonal import seasonal_decompose
import plotly.subplots as sp# Perform seasonal decomposition
result = seasonal_decompose(df['meantemp'], model='additive', period=365)# Plot the decomposed components
fig = sp.make_subplots(rows=4, cols=1, shared_xaxes=True, subplot_titles=['Observed', 'Trend', 'Seasonal', 'Residual'])fig.add_trace(go.Scatter(x=df.index, y=result.observed, mode='lines', name='Observed'), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=result.trend, mode='lines', name='Trend'), row=2, col=1)
fig.add_trace(go.Scatter(x=df.index, y=result.seasonal, mode='lines', name='Seasonal'), row=3, col=1)
fig.add_trace(go.Scatter(x=df.index, y=result.resid, mode='lines', name='Residual'), row=4, col=1)fig.update_layout(template= 'ts_template',height=800, title='Seasonal Decomposition of Mean Temperature')
fig.show()

在这里插入图片描述
从图中可以看出,平均温度数据具有很强的季节性,趋势是逐渐升高的,但是受噪音影响有限。

2.4 特征选取

基于以上数据形态观测和分析,我们可以大致选定数据中的部分特征作为影响平均温度的因素(特征信息),这里就选定湿度和风速作为特征信息进行训练和预测。

df = df[['meantemp', 'humidity', 'wind_speed']]
df.head()

2.5 归一化

from sklearn.preprocessing import RobustScaler, MinMaxScalerrobust_scaler = RobustScaler()   # scaler for wind_speed
minmax_scaler = MinMaxScaler()  # scaler for humidity
target_transformer = MinMaxScaler()   # scaler for target (meantemp)dl_train['wind_speed'] = robust_scaler.fit_transform(dl_train[['wind_speed']])  # robust for wind_speed
dl_train['humidity'] = minmax_scaler.fit_transform(dl_train[['humidity']]) # minmax for humidity
dl_train['meantemp'] = target_transformer.fit_transform(dl_train[['meantemp']]) # targetdl_test['wind_speed'] = robust_scaler.transform(dl_test[['wind_speed']])
dl_test['humidity'] = minmax_scaler.transform(dl_test[['humidity']])
dl_test['meantemp'] = target_transformer.transform(dl_test[['meantemp']])display(dl_train.head())

3. 序列稳定性验证

import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller, kpssdef check_stationarity(series):print(f'\n___________________Checking Stationarity for: {series.name}___________________\n')# ADF Testadf_test = adfuller(series.values)print('ADF Test:\n')print('ADF Statistic: %f' % adf_test[0])print('p-value: %f' % adf_test[1])print('Critical Values:')for key, value in adf_test[4].items():print('\t%s: %.3f' % (key, value))if (adf_test[1] <= 0.05) & (adf_test[4]['5%'] > adf_test[0]):print("\u001b[32mSeries is Stationary (ADF Test)\u001b[0m")else:print("\x1b[31mSeries is Non-stationary (ADF Test)\x1b[0m")print('\n' + '-'*50 + '\n')# KPSS Testkpss_test = kpss(series.values, regression='c', nlags='auto')print('KPSS Test:\n')print('KPSS Statistic: %f' % kpss_test[0])print('p-value: %f' % kpss_test[1])print('Critical Values:')for key, value in kpss_test[3].items():print('\t%s: %.3f' % (key, value))if kpss_test[1] > 0.05:print("\u001b[32mSeries is Stationary (KPSS Test)\u001b[0m")else:print("\x1b[31mSeries is Non-stationary (KPSS Test)\x1b[0m")

那么我们就可以针对选取的特征进行稳定性分析。

# Check initial stationarity for each feature
check_stationarity(df['meantemp'])
check_stationarity(df['humidity'])
check_stationarity(df['wind_speed'])
___________________Checking Stationarity for: meantemp___________________ADF Test:ADF Statistic: -2.021069
p-value: 0.277412
Critical Values:1%: -3.4355%: -2.86410%: -2.568
Series is Non-stationary (ADF Test)--------------------------------------------------KPSS Test:KPSS Statistic: 0.187864
p-value: 0.100000
Critical Values:10%: 0.3475%: 0.4632.5%: 0.5741%: 0.739
Series is Stationary (KPSS Test)___________________Checking Stationarity for: humidity___________________ADF Test:ADF Statistic: -3.675577
p-value: 0.004470
Critical Values:1%: -3.4355%: -2.86410%: -2.568
Series is Stationary (ADF Test)--------------------------------------------------KPSS Test:KPSS Statistic: 0.091737
p-value: 0.100000
Critical Values:10%: 0.3475%: 0.4632.5%: 0.5741%: 0.739
Series is Stationary (KPSS Test)___________________Checking Stationarity for: wind_speed___________________ADF Test:ADF Statistic: -3.838097
p-value: 0.002541
Critical Values:1%: -3.4355%: -2.86410%: -2.568
Series is Stationary (ADF Test)--------------------------------------------------KPSS Test:KPSS Statistic: 0.137734
p-value: 0.100000
Critical Values:10%: 0.3475%: 0.4632.5%: 0.5741%: 0.739
Series is Stationary (KPSS Test)

可以看到平均温度是不稳定的,那么就需要进行差分处理。具体什么是差分及差分阶数请自行查阅。

# 1st degree differencing
df['meantemp_diff'] = df['meantemp'].diff().fillna(0)  # diff() default is 1st degree differencing 
check_stationarity(df['meantemp_diff']);
___________________Checking Stationarity for: meantemp_diff___________________ADF Test:ADF Statistic: -16.294070
p-value: 0.000000
Critical Values:1%: -3.4355%: -2.86410%: -2.568
Series is Stationary (ADF Test)--------------------------------------------------KPSS Test:KPSS Statistic: 0.189493
p-value: 0.100000
Critical Values:10%: 0.3475%: 0.4632.5%: 0.5741%: 0.739
Series is Stationary (KPSS Test)

3. 模型训练和预测

# Split the data into training and testing sets
train_size = int(len(df) * 0.8)
train, test = df.iloc[:train_size], df.iloc[train_size:]
# SARIMAXfrom statsmodels.tsa.statespace.sarimax import SARIMAX
from sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error# Define the SARIMA model parameters
order = (1, 1, 6)  # Non-seasonal order (p, d, q)
seasonal_order = (1, 1, 1, 7)  # Seasonal order (P, D, Q, S)  # Fit the SARIMA model
sarima_model = SARIMAX(endog=train['meantemp'], exog=train[['humidity', 'wind_speed']],order=order, seasonal_order=seasonal_order)
sarima_model_fit = sarima_model.fit()# Make predictions
sarima_pred = sarima_model_fit.predict(start=test.index[0], end=test.index[-1],exog=test[['humidity', 'wind_speed']])# Calculate error
mse = mean_squared_error(test['meantemp'], sarima_pred)
r2 = r2_score(test['meantemp'], sarima_pred)
print('Test MSE:', mse)
print('Test R²: %.3f' % r2)# Plot the results
plt.figure(figsize=(10, 5))
plt.plot(test.index, test['meantemp'], label='Actual')
plt.plot(test.index, sarima_pred, color='red', label='SARIMA Forecast')
plt.xlabel('Date')
plt.ylabel('Meantemp')
plt.title('SARIMA Forecast')
plt.legend()
plt.show()

在这里插入图片描述
如上图所示,可以看到实际数据和预测数据的曲线图,从图中可以看到,预测值与实际值之间存在较大gap,这就说明模型泛化能力不好,对未来数据不能很好的预测。这就需要我们对模型参数进行调整,以期达到更好的效果。当然有些是受限于模型本身的局限性,始终无法对数据做出合理预测,那就需要我们寻找其他的模型,比如RNN、CNN、LSTM等更强大的深度学习模型来进行训练和预测。

参考文档

  1. ARIMA Model for Time Series Forecasting
  2. 季节性ARIMA模型
  3. https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average

如有侵权,烦请联系删除

相关文章:

时序预测SARIMAX模型

1. 项目背景 本文基于kaggle平台相关竞赛项目&#xff0c;具体连接如下&#xff1a; Time Series Forecasting With SARIMAX 基本信息如内容说明、数据集、已提交代码、当前得分排名以及比赛规则等&#xff0c;如图【1】所示&#xff0c;可以认真阅读。 图 1 2. 数据读取 …...

gin集成jaeger中间件实现链路追踪

1. 背景 新业务线带来新项目启动&#xff0c;需要改进原有项目的基础框架和组件能力&#xff0c;以提升后续开发和维护效率。项目搭建主要包括技术选型、框架搭建、基础服务搭建等。这其中就涉及到链路追踪的内容&#xff0c;结合其中的踩坑情况&#xff0c;用一篇文章来说明完…...

前端层面----监控与埋点

前言&#xff1a; 站在产品的视角&#xff0c;经常会问如下几个问题&#xff1a; 产品有没有用户使用 用户用得怎么样 系统会不会经常出现异常 如何更好地满足用户需求服务用户 当站在技术视角时&#xff0c;经常会问如下几个问题&#xff1a; 系统出现异常的频率如何 异常…...

linux Command

linux Command 1. 系统监控命令 1.1 top top [param] top -H -p pid&#xff0c;查看进程pid下面的子线程。-b以处理模式操作-c显示完整的命令行而不只是显示命令名。-d 屏幕刷新间隔时间。-l 忽略失效过程。-s 保密模式。-S 累积模式。-u 【用户名】 指定用户名。-p 【进程…...

uniapp登录页面( 适配:pc、小程序、h5)

<!-- 简洁登录页面 --> <template><view class"login-bg"><image class"img-a" src"https://zhoukaiwen.com/img/loginImg/2.png"></image><image class"img-b" src"https://zhoukaiwen.com/im…...

关于OceanBase 多模一体化的浅析

在当今多元化的业务生态中&#xff0c;各行各业对数据库系统的需求各有侧重。举例来说&#xff0c;金融风控领域对数据库的高效事务处理&#xff08;TP&#xff09;和分析处理&#xff08;AP&#xff09;能力有着严格要求&#xff1b;游戏行业则更加注重文档数据库的灵活性和性…...

快速git

下载 sudo apt install git配置 $ git config --global user.name "John Doe" $ git config --global user.email johndoeexample.com没有空格可以不加双引号如果~/.ssh没有先创建&#xff08;下一步用&#xff09; ssh方式制作密钥 github解释 #以邮箱作为标签…...

欺诈文本分类检测(十四):GPTQ量化模型

1. 引言 量化的本质&#xff1a;通过将模型参数从高精度&#xff08;例如32位&#xff09;降低到低精度&#xff08;例如8位&#xff09;&#xff0c;来缩小模型体积。 本文将采用一种训练后量化方法GPTQ&#xff0c;对前文已经训练并合并过的模型文件进行量化&#xff0c;通…...

2024.9.14(RC和RS)

一、replicationcontroller &#xff08;RC&#xff09; 1、更改镜像站 [rootk8s-master ~]# vim /etc/docker/daemon.json {"registry-mirrors": ["https://do.nark.eu.org","https://dc.j8.work","https://docker.m.daocloud.io",&…...

【算法随想录04】KMP 字符串匹配算法

这是字符串模式匹配经典算法。 给定一个文本 t 和一个字符串 s&#xff0c;我们尝试找到并展示 s 在 t 中的所有出现&#xff08;occurrence&#xff09;。 #include<bits/stdc.h>using namespace std;vector<int> KMP(string s) {int n s.size();vector<int&g…...

TCP和MQTT通信协议

协议分层 网络分层 协议应用层 Co AP MQTT HTTP传输层 UDP TCP网络层 IP链路层 Enternet 网络分层中最…...

Python Pickle 与 JSON 序列化详解:存储、反序列化与对比

Python Pickle 与 JSON 序列化详解&#xff1a;存储、反序列化与对比 文章目录 Python Pickle 与 JSON 序列化详解&#xff1a;存储、反序列化与对比一 功能总览二 Pickle1 应用2 序列化3 反序列化4 系统资源对象1&#xff09;不能被序列化的系统资源对象2&#xff09;强行序列…...

第二百三十二节 JPA教程 - JPA教程 - JPA ID自动生成器示例、JPA ID生成策略示例

JPA教程 - JPA ID自动生成器示例 我们可以将id字段标记为自动生成的主键列。 数据库将在插入时自动为id字段生成一个值数据到表。 例子 下面的代码来自Person.java。 package cn.w3cschool.common;import javax.persistence.Entity; import javax.persistence.GeneratedValu…...

计算机网络 ---- 计算机网络的体系结构【计算机网络的分层结构】

一、以快递网络来引入分层思想 1.1 “分层” 的设计思想【将庞大而复杂的问题&#xff0c;转化为若干较小的局部问题】 从我们最熟悉的快递网络出发&#xff0c;在你家附近会有一个快递终点站A&#xff0c;在其他的城市&#xff0c;也会有这种快递终点站&#xff0c;比如说快递…...

Vite + Electron 时,Electron 渲染空白,静态资源加载错误等问题解决

问题 如果在 electron 里直接引入 vite 打包后的东西&#xff0c;那么有些资源是请求不到的 这是我的引入方式 根据报错&#xff0c;我们来到 vite 打包后的路径看一看 &#xff0c;修改一下 dist 里的文件路径试了一试 修改后的样子&#xff0c;发现是可以的了 原因分析 …...

ZAB协议(算法)

一、ZAB&#xff08;ZooKeeper Atomic Broadcast&#xff09;介绍 ZAB 即 ZooKeeper Atomic Broadcast&#xff0c;是 ZooKeeper 实现分布式数据一致性的核心算法。它是一种原子广播协议&#xff0c;用于确保在分布式环境中&#xff0c;多个 ZooKeeper 服务器之间的数据一致性。…...

多个音频怎么合并?把多个音频合并在一起的方法推荐

多个音频怎么合并&#xff1f;无论是制作连贯的播客节目还是将音乐片段整合成专辑&#xff0c;音频合并已成为许多创作者的常见需求。通过有效合并音频&#xff0c;可以显著提升项目的整体质量&#xff0c;确保内容的连续性和一致性。然而&#xff0c;合并后的文件通常比原始单…...

【Django】Django Class-Based Views (CBV) 与 DRF APIView 的区别解析

Django Class-Based Views (CBV) 与 DRF APIView 的区别解析 在 Django 开发中&#xff0c;基于类的视图&#xff08;Class-Based Views, CBV&#xff09;是实现可重用性和代码结构化的利器。而 Django REST Framework (DRF) 提供的 APIView 是针对 API 开发的扩展。 一、CBV …...

如何增加Google收录量?

想增加Google收录量&#xff0c;首先自然是你的页面数量就要多&#xff0c;但这些页面的内容也绝对不能敷衍&#xff0c;你的网站都没多少页面&#xff0c;谷歌哪怕想收录都没办法&#xff0c;当然&#xff0c;这是一个过程&#xff0c;持续缓慢的增加页面&#xff0c;增加网站…...

leetcode练习 格雷编码

n 位格雷码序列 是一个由 2n 个整数组成的序列&#xff0c;其中&#xff1a; 每个整数都在范围 [0, 2n - 1] 内&#xff08;含 0 和 2n - 1&#xff09;第一个整数是 0一个整数在序列中出现 不超过一次每对 相邻 整数的二进制表示 恰好一位不同 &#xff0c;且第一个 和 最后一…...

【LLM:Gemini】文本摘要、信息提取、验证和纠错、重新排列图表、视频理解、图像理解、模态组合

开始使用Gemini 目录 开始使用Gemini Gemini简介 Gemini实验结果 Gemini的多模态推理能力 文本摘要 信息提取 验证和纠错 重新排列图表 视频理解 图像理解 模态组合 Gemini多面手编程助理 库的使用 引用 本文概述了Gemini模型和如何有效地提示和使用这些模型。本…...

CMS之Wordpress建设

下载 https://cn.wordpress.org/ 宝塔安装Wordpress 创建网站 上传文件、并解压、剪切文件到项目根目录 安装 -> 数据库信息 -> 标题信息 http://wordpress.xxxxx.com 登录 http://wordpress.xxxxxxxxx.com/wp-admin/ 1. 主题(模板) wordpress-基本使用-02-在主题…...

使用Neo4j存储聊天记录的简单教程

引言 在当今的数据驱动世界中&#xff0c;关系型数据库有时难以处理复杂的、相互关联的数据集。Neo4j作为一款开源图数据库&#xff0c;以其高效管理高连接数据的能力而广受欢迎。本篇文章将详细介绍如何使用Neo4j来存储聊天信息历史&#xff0c;引导您在实际项目中利用其强大…...

前端面试常考算法

快速排序 #include<iostream> #include<cstdio> using namespace std; const int N 100005; int a[N];void quick_sort(int a[], int l, int r) {if (l > r) return;int x a[l r >> 1];int i l - 1, j r 1;while (i < j) {while (a[i] < x);…...

【机试准备】常用容器与函数

Vector详解 原文链接&#xff1a;【超详细】C vector 详解 例题&#xff0c;这一篇就够了-CSDN博客 向量&#xff08;Vector&#xff09;是一个封装了动态大小数组的顺序容器&#xff08;Sequence Container&#xff09;。跟任意其它类型容器一样&#xff0c;它能够存放各种…...

Base 社区见面会 | 新加坡站

活动信息 备受期待的 Base 社区见面会将于 Token2049 期间在新加坡举行&#xff0c;为 Base 爱好者和生态系统建设者提供一个独特的交流机会。本次活动由 DAOBase 组织&#xff0c;Base 和 Coinbase 提供支持&#xff0c;并得到了以下合作伙伴的大力支持&#xff1a; The Sand…...

麒麟操作系统搭建Nacos集群

Nacos 集群搭建 2.4.2 环境介绍 操作系统Kylin Linux Advanced Server V10 (Lance)Kylin Linux Advanced Server V10 (Lance)Kylin Linux Advanced Server V10 (Lance)内核版本Linux 4.19.90-52.22.v2207.ky10.aarch64Linux 4.19.90-52.22.v2207.ky10.aarch64Linux 4.19.90-52…...

Imagination推出性能最高且具有高等级功能安全性的汽车GPU IP

Imagination DXS GPU 进一步扩大其在汽车领域的领先地位 产品亮点 &#xff1a; 峰值性能比 Imagination 上一代汽车 GPU 提高了 50%&#xff0c;可扩展至 192GPixel/s、6 TFLOPS 和 24TOPS计算工作负载的性能提升多达十倍引入创新的分布式功能安全机制&#xff0c;以最小的…...

端口大全说明,HTTP,TCP,UDP常见端口对照表

HTTP,TCP,UDP常见端口对照表,下面罗列了包括在Linux 中的服务、守护进程、和程序所使用的最常见的通信端口小贴士&#xff1a;CtrlF 快速查找 Http端口号&#xff08;点标题可收缩或展开&#xff09; No1.最常用端口 端口号码/层名称注释1tcpmuxTCP端口服务多路复用5rje远程作…...

dplyr、tidyverse和ggplot2初探

dplyr、tidyverse 和 ggplot2 之间有紧密的联系&#xff0c;它们都是 R 语言中用于数据处理和可视化的工具&#xff0c;且都源于 Hadley Wickham 的工作。它们各自有不同的功能&#xff0c;但可以无缝协作&#xff0c;帮助用户完成从数据处理到数据可视化的工作流。以下是它们之…...