当前位置: 首页 > 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;且第一个 和 最后一…...

内存分配函数malloc kmalloc vmalloc

内存分配函数malloc kmalloc vmalloc malloc实现步骤: 1)请求大小调整:首先,malloc 需要调整用户请求的大小,以适应内部数据结构(例如,可能需要存储额外的元数据)。通常,这包括对齐调整,确保分配的内存地址满足特定硬件要求(如对齐到8字节或16字节边界)。 2)空闲…...

C++:std::is_convertible

C++标志库中提供is_convertible,可以测试一种类型是否可以转换为另一只类型: template <class From, class To> struct is_convertible; 使用举例: #include <iostream> #include <string>using namespace std;struct A { }; struct B : A { };int main…...

对WWDC 2025 Keynote 内容的预测

借助我们以往对苹果公司发展路径的深入研究经验&#xff0c;以及大语言模型的分析能力&#xff0c;我们系统梳理了多年来苹果 WWDC 主题演讲的规律。在 WWDC 2025 即将揭幕之际&#xff0c;我们让 ChatGPT 对今年的 Keynote 内容进行了一个初步预测&#xff0c;聊作存档。等到明…...

将对透视变换后的图像使用Otsu进行阈值化,来分离黑色和白色像素。这句话中的Otsu是什么意思?

Otsu 是一种自动阈值化方法&#xff0c;用于将图像分割为前景和背景。它通过最小化图像的类内方差或等价地最大化类间方差来选择最佳阈值。这种方法特别适用于图像的二值化处理&#xff0c;能够自动确定一个阈值&#xff0c;将图像中的像素分为黑色和白色两类。 Otsu 方法的原…...

现代密码学 | 椭圆曲线密码学—附py代码

Elliptic Curve Cryptography 椭圆曲线密码学&#xff08;ECC&#xff09;是一种基于有限域上椭圆曲线数学特性的公钥加密技术。其核心原理涉及椭圆曲线的代数性质、离散对数问题以及有限域上的运算。 椭圆曲线密码学是多种数字签名算法的基础&#xff0c;例如椭圆曲线数字签…...

自然语言处理——Transformer

自然语言处理——Transformer 自注意力机制多头注意力机制Transformer 虽然循环神经网络可以对具有序列特性的数据非常有效&#xff0c;它能挖掘数据中的时序信息以及语义信息&#xff0c;但是它有一个很大的缺陷——很难并行化。 我们可以考虑用CNN来替代RNN&#xff0c;但是…...

2025季度云服务器排行榜

在全球云服务器市场&#xff0c;各厂商的排名和地位并非一成不变&#xff0c;而是由其独特的优势、战略布局和市场适应性共同决定的。以下是根据2025年市场趋势&#xff0c;对主要云服务器厂商在排行榜中占据重要位置的原因和优势进行深度分析&#xff1a; 一、全球“三巨头”…...

【Go语言基础【13】】函数、闭包、方法

文章目录 零、概述一、函数基础1、函数基础概念2、参数传递机制3、返回值特性3.1. 多返回值3.2. 命名返回值3.3. 错误处理 二、函数类型与高阶函数1. 函数类型定义2. 高阶函数&#xff08;函数作为参数、返回值&#xff09; 三、匿名函数与闭包1. 匿名函数&#xff08;Lambda函…...

多模态图像修复系统:基于深度学习的图片修复实现

多模态图像修复系统:基于深度学习的图片修复实现 1. 系统概述 本系统使用多模态大模型(Stable Diffusion Inpainting)实现图像修复功能,结合文本描述和图片输入,对指定区域进行内容修复。系统包含完整的数据处理、模型训练、推理部署流程。 import torch import numpy …...

离线语音识别方案分析

随着人工智能技术的不断发展&#xff0c;语音识别技术也得到了广泛的应用&#xff0c;从智能家居到车载系统&#xff0c;语音识别正在改变我们与设备的交互方式。尤其是离线语音识别&#xff0c;由于其在没有网络连接的情况下仍然能提供稳定、准确的语音处理能力&#xff0c;广…...