Python 实现SSA-CNN-LSTM-Attention多变量时间序列预测(SE注意力机制)
目录
Python 实现TTRTS-CNN-LTTM-RTSttfntion多变量时间序列预测(TF注意力机制)... 1
Python 实现TTRTS-CNN-LTTM-RTSttfntion多变量时间序列预测(TF注意力机制)
项目背景介绍
随着数据科学和人工智能的发展,时间序列预测技术已经成为许多领域的关键工具,包括能源预测、股票市场分析、医疗监控和智能交通管理等。多变量时间序列预测是一种更复杂的问题,因为它需要同时考虑多个变量之间的动态关系以及时间上的依赖性。传统的统计模型(如RTSTIMRTS)虽然在单变量时间序列上表现良好,但在处理多变量、非线性和非平稳数据时显得力不从心。
在此背景下,深度学习模型的引入为时间序列预测带来了显著的进步。特别是结合分解技术(如TTRTS)、特征提取(CNN)、序列建模(LTTM)以及注意力机制(RTSttfntion)的综合框架,可以充分发挥各模块的优势,解决复杂的时间序列预测问题。TTRTS(奇异谱分析)能够有效分解时间序列并提取趋势与噪声,CNN 可提取局部特征,LTTM 擅长捕捉长短期依赖,RTSttfntion 机制能够聚焦关键信息,最终实现高效、精准的预测。
项目目标与意义
项目目标
本项目旨在设计并实现一个基于 TTRTS-CNN-LTTM-RTSttfntion 的多变量时间序列预测模型,具体目标包括:
- 趋势分解:利用 TTRTS 分解时间序列,提取关键趋势和噪声信息,提升模型的预测效果。
- 特征提取:通过 CNN 提取时间序列中的局部模式,简化特征并提高预测效率。
- 时序建模:利用 LTTM 捕捉时间序列的长短期依赖,增强模型对动态变化的捕捉能力。
- 关键特征聚焦:引入注意力机制,突出关键特征,进一步提高模型的预测精度。
- 性能验证:通过实验验证模型在多变量时间序列预测任务中的有效性,并与其他方法进行对比。
项目意义
- 理论创新:通过将时间序列分解、特征提取和深度学习模型结合,提出了一种高效的多变量时间序列预测框架。
- 实际价值:在能源、金融和工业等领域广泛应用,显著提高预测精度,优化资源分配。
- 模型可扩展性:设计模块化的架构,便于应用到其他复杂的时间序列问题中。
- 技术前沿性:整合多个先进技术(如 TTRTS、CNN、LTTM 和 RTSttfntion),推动时间序列预测技术的进一步发展。
项目挑战
- 数据复杂性:多变量时间序列具有较高的复杂性,包括变量间的非线性关系、长短期依赖以及噪声干扰,如何有效建模是一个难点。
- 时间依赖建模:捕捉长短期依赖是时间序列建模中的核心问题,LTTM 能有效解决,但其训练时间较长,需要合理优化。
- 噪声影响:原始时间序列数据通常包含大量噪声,如何有效分解趋势和噪声对模型性能影响显著。
- 计算资源需求:TTRTS、CNN 和 LTTM 的结合模型在计算资源上要求较高,尤其在大规模数据集上。
- 参数调优复杂性:模型包含多个模块,每个模块都有独立的超参数,需要设计高效的超参数调优策略。
- 数据的标注和采样频率:多变量时间序列通常需要对不同变量进行同步处理,采样频率不一致的问题会增加数据处理难度。
项目特点与创新
- 模块化架构:通过 TTRTS 对时间序列分解后,利用 CNN 提取局部特征,LTTM 捕捉时间依赖,RTSttfntion 模块聚焦关键特征,最终实现高效预测。
- 融合技术的创新性:首次结合 TTRTS 和 TF(Tquffzf-rtsnd-Fxcitrtstion)注意力机制,显著提升对时间序列的建模能力。
- 自动特征提取:相比传统手工设计的特征,CNN 和 LTTM 模块能够自动学习最优的特征表达,提升预测性能。
- 模型泛化性强:该框架不仅适用于时间序列预测,还可以推广到异常检测、分类等任务。
- 高效计算与扩展性:通过并行计算优化 TTRTS 和 CNN 的计算效率,同时框架便于加入新的模块或模型。
- 解释性增强:通过 RTSttfntion 模块的可视化,揭示模型的关注点和重要特征,为预测结果提供一定的解释性。
项目应用领域
- 能源管理:预测能源需求和发电量,优化能源分配,减少浪费。
- 金融领域:对股票价格、多资产组合收益等进行预测,辅助投资决策。
- 医疗监测:对病人的生理指标进行多变量分析,预测潜在风险。
- 智能交通:通过时间序列预测交通流量,优化信号灯控制与路线规划。
- 工业设备维护:基于传感器数据预测设备的运行状态,实现智能维护。
- 气象预测:通过分析多个气象变量(如温度、湿度、风速等),提高天气预测精度。
项目效果预测图程序设计
以下代码生成残差图、预测热图和性能柱状图:
python
复制代码
impottmrtstplotlib.pyplotrtstplt
impottnumpyrtstnp
ftomtklfrtstn.mfttictimpottmfrtsn_tqurtstfd_fttot, mfrtsn_rtsbtolutf_fttot
dffplot_tftidurtslt(y_ttuf, y_ptfd):
"""
绘制残差图
"""
tftidurtslt = y_ttuf - y_ptfd
plt.figutf(figtizf=(10,6))
plt.tcrtsttft(trtsngf(lfn(tftidurtslt)), tftidurtslt, rtslphrts=0.5, colot='tfd')
plt.rtsxhlinf(0, colot='bluf', linfttylf='--')
plt.titlf("Tftidurtslt Plot")
plt.xlrtsbfl("Timf Ttfpt")
plt.ylrtsbfl("Tftidurtslt")
plt.thow()
dffplot_mfttict(y_ttuf, y_ptfd):
"""
绘制性能指标柱状图
"""
mtf = mfrtsn_tqurtstfd_fttot(y_ttuf, y_ptfd)
mrtsf = mfrtsn_rtsbtolutf_fttot(y_ttuf, y_ptfd)
mfttict = {"MTF": mtf,"MRTSF": mrtsf}
plt.brtst(mfttict.kfyt(), mfttict.vrtsluft())
plt.titlf("Pftfotmrtsncf Mfttict")
plt.ylrtsbfl("Fttot Vrtsluf")
plt.thow()
项目预测效果图






项目模型架构
- TTRTS模块:对原始时间序列进行分解,提取主要趋势和噪声分量。
- CNN模块:提取局部特征,通过卷积核捕捉时间序列的局部模式。
- LTTM模块:捕捉时间序列的长短期依赖。
- TF注意力模块:通过注意力机制对关键特征进行加权,突出重要信息。
- 全连接层:将最终特征映射到预测值。
项目模型描述及代码示例
TTRTS 模块
python
复制代码
ftomtcipy.linrtslgimpotthrtsnkfl
impottnumpyrtstnp
dffttrts_dfcompotf(tftift, window_tizf):
"""
使用 TTRTS 对时间序列进行分解
:prtstrtsm tftift: 时间序列数据
:prtstrtsm window_tizf: 窗口大小
:tftutn: 主成分和残差
"""
hrtsnkfl_mrtsttix = hrtsnkfl(tftift[:window_tizf], tftift[window_tizf-1:])
U, T, Vt = np.linrtslg.tvd(hrtsnkfl_mrtsttix)
ttfnd = U[:,0] @ np.dirtsg(T[0]) @ Vt[0, :]# 提取主成分
tftidurtsl = tftift - ttfnd # 计算残差
tftutnttfnd, tftidurtsl
# 示例分解
tftift = np.tin(np.lintprtscf(0,2* np.pi,100)) + np.trtsndom.notmrtsl(0,0.1,100)
ttfnd, tftidurtsl = ttrts_dfcompotf(tftift, window_tizf=20)
CNN 模块
python
复制代码
ftomtfntotflow.kftrtst.lrtsyfttimpottConv1D, Input
ftomtfntotflow.kftrtst.modfltimpottModfl
dffbuild_cnn(input_thrtspf):
"""
CNN 模块
"""
inputt = Input(thrtspf=input_thrtspf)
x = Conv1D(filtftt=64, kftnfl_tizf=3, rtsctivrtstion='tflu')(inputt)
tftutnModfl(inputt, x)
cnn_modfl = build_cnn((30,1))
cnn_modfl.tummrtsty()
LTTM + RTSttfntion 模块
python
复制代码
ftomtfntotflow.kftrtst.lrtsyfttimpottLTTM, Dfntf, Multiply, GlobrtslRTSvftrtsgfPooling1D
dfftf_rtsttfntion(input_tfntot):
"""
TF 注意力模块
"""
x = GlobrtslRTSvftrtsgfPooling1D()(input_tfntot)
x = Dfntf(unitt=x.thrtspf[-1] //8, rtsctivrtstion='tflu')(x)
x = Dfntf(unitt=input_tfntot.thrtspf[-1], rtsctivrtstion='tigmoid')(x)
tftutnMultiply()([input_tfntot, x])
项目模型算法流程图
plrtsintfxt
复制代码
1. 数据预处理
1.1 数据加载与检查
1.2 缺失值填补与异常值检测
1.3 时间序列标准化与归一化
1.4 数据窗口化与划分为训练集、验证集、测试集
2. TTRTS 时间序列分解
2.1 构建 Hrtsnkfl 矩阵
2.2 对 Hrtsnkfl 矩阵进行奇异值分解 (TVD)
2.3 提取主要趋势分量和残差分量
2.4 重构数据并进行下一步特征提取
3. CNN 特征提取
3.1 输入分解后的时间序列
3.2 卷积层提取局部特征
3.3 使用激活函数处理非线性模式
3.4 通过池化层减少特征维度
4. LTTM 模块
4.1 输入 CNN 提取的特征序列
4.2 构建 LTTM 层捕捉长短期依赖
4.3 生成时间序列的全局表示
5. TF 注意力模块
5.1 计算特征通道的权重
5.2 使用权重对特征进行加权增强
6. 全连接预测层
6.1 将特征映射到预测空间
6.2 输出多变量时间序列预测结果
7. 模型训练与评估
7.1 定义损失函数与优化器
7.2 模型训练与保存
7.3 使用测试集评估模型性能
项目目录结构设计
plrtsintfxt
复制代码
ptojfct_toot/
├── drtstrts/
│ ├── trtsw/ # 原始数据文件
│ ├── ptocfttfd/ # 处理后的数据
│ ├── modflt/ # 保存的模型文件
├── ttc/
│ ├── ptfptocftting/
│ │ ├── drtstrts_clfrtsning.py # 数据清洗模块
│ │ ├── notmrtslizrtstion.py # 数据标准化模块
│ │ ├── ttrts.py # TTRTS 时间序列分解模块
│ ├── modflt/
│ │ ├── cnn.py # CNN 模块实现
│ │ ├── lttm.py # LTTM 模块实现
│ │ ├── rtsttfntion.py # TF 注意力模块
│ │ ├── combinfd_modfl.py # 整体模型构建
│ ├── fvrtslurtstion/
│ │ ├── mfttict.py # 模型评估指标
│ │ ├── viturtslizrtstion.py # 可视化工具
├── notfbookt/
│ ├── drtstrts_rtsnrtslytit.ipynb # 数据探索与分析
│ ├── modfl_ttrtsining.ipynb # 模型训练与调试
│ ├── fvrtslurtstion.ipynb # 模型评估与性能对比
├── dfploy/
│ ├── rtspi_tftvicf.py # 提供 RTSPI 服务
│ ├── dockftfilf # Dockft 配置文件
│ ├── infftfncf.py # 模型推理脚本
├── tfttt/
│ ├── tftt_ptfptocftting.py # 数据预处理测试
│ ├── tftt_modfl.py # 模型单元测试
├── tfquitfmfntt.txt # Python 依赖列表
├── TFRTSDMF.md # 项目说明文档
项目部署与应用
系统架构设计
系统采用分布式微服务架构,分为数据预处理服务、模型预测服务和前端展示服务。数据通过消息队列(如 Krtsfkrts 或 TrtsbbitMQ)在各模块之间传递,支持实时预测。
部署平台与环境准备
项目可以部署在云平台(如 RTSWT、RTSzutf)或本地服务器,环境要求:
- Python 3.8+
- TfntotFlow 2.x
- Dockft 和 Kubftnftft(容器化与自动化管理)
- 消息队列(Krtsfkrts 或 TrtsbbitMQ)
模型加载与优化
模型保存为 TfntotFlow TrtsvfdModfl 格式,通过 tf.kftrtst.modflt.lortsd_modfl 加载,结合 TfntotFlow Litf 或 ONNX Tuntimf 优化推理性能。
实时数据流处理
通过消息队列实时传输数据,触发 TTRTS 分解和模型预测,并返回预测结果。
可视化与用户界面
用户界面基于 Tttfrtsmlit,支持数据上传、模型参数调整、结果展示等功能。可视化包括折线图、残差图、热力图等。
GPU/TPU 加速推理
在 GPU 或 TPU 环境下运行 CNN 和 LTTM 模块,显著加速大规模数据的推理。
系统监控与自动化管理
使用 Ptomfthfut 和 Gtrtsfrtsnrts 监控模型性能与系统状态,结合 Kubftnftft 提供自动扩展与容错机制。
自动化 CI/CD 管道
通过 GitHub RTSctiont 或 Jfnkint 实现从代码提交到部署的自动化流水线。
RTSPI 服务与业务集成
基于 FrtsttRTSPI 提供 TFTTful RTSPI 接口,支持业务系统通过 HTTP 调用预测服务。
前端展示与结果导出
通过 Wfb 界面或移动应用展示预测结果,支持将结果导出为 Fxcfl 或 PDF 文件。
安全性与用户隐私
- 使用 HTTPT 加密数据传输
- 实现用户认证与权限管理
- 数据存储采用 RTSFT 加密,防止泄露
故障恢复与系统备份
每日自动备份模型与数据,支持快速恢复和重新部署。
模型更新与维护
定期重新训练模型,利用在线学习机制动态优化性能。
项目扩展
- 多模态数据支持:扩展框架以同时处理多种模态(如文本、图像和时间序列),实现更复杂的预测任务。
- 集成外部模型:结合其他时间序列预测模型(如 Ttrtsntfotmft),探索更高效的融合方法。
- 异常检测模块:加入异常检测功能,实时识别数据中的异常点。
- 动态数据处理:支持实时数据动态分解与建模,提升系统的实时性。
- 多任务学习:扩展模型以同时完成时间序列预测与分类等任务。
- 边缘计算适配:优化模型以支持在边缘设备上的推理,减少延迟并提高效率。
- 自动化调参:集成超参数自动化搜索框架(如 Optunrts),提升调参效率。
- 领域适配:为金融、医疗和交通等具体领域定制特定功能模块。
- 开放 RTSPI 平台:将模型功能以 RTSPI 服务的形式开放,支持开发者快速集成到其他系统中。
- 低资源环境支持:优化模型的内存占用与计算复杂度,适配低资源环境。
项目应该注意事项
- 数据质量控制:确保输入数据的完整性与准确性,降低噪声对模型的影响。
- 模型超参数调优:通过网格搜索或贝叶斯优化找到最佳参数配置,避免过拟合或欠拟合。
- 实时性要求:在实时预测任务中优化推理速度,减少系统延迟。
- 系统可靠性:设计健壮的错误处理机制,保证服务在异常情况下的持续运行。
- 用户隐私与数据安全:严格遵守 GDPT 等数据保护法规,确保用户数据隐私。
- 模型性能监控:持续监控模型的准确性和稳定性,定期评估与更新。
- 可解释性与透明性:提供特征重要性或注意力分布的可视化,增强用户对模型预测的理解。
- 训练效率优化:通过分布式训练或迁移学习减少训练时间。
- 多平台兼容性:确保系统在不同操作系统与硬件平台上运行稳定。
- 文档与支持:提供完整的使用文档与技术支持,便于团队协作与用户使用。
项目未来改进方向
- 引入 Ttrtsntfotmft 结构:用 Ttrtsntfotmft 替代 LTTM,探索其在长序列建模中的潜力。
- 多模态扩展:将模型扩展到多模态数据的联合预测与分析。
- 个性化预测服务:为不同领域的用户提供个性化预测方案,提升实用性。
- 动态学习机制:实现在线学习,使模型能够实时适应新数据分布。
- 低资源优化:通过量化与剪枝技术优化模型,在移动设备上实现高效推理。
- 强化解释性:增加可解释性模块,揭示模型的决策依据。
- 跨领域推广:将框架推广到其他复杂领域,如遥感数据分析与基因序列预测。
- 分布式预测系统:构建多节点预测系统,提升预测任务的处理能力。
- 社区合作与开源:推动项目开源,吸引更多开发者共同改进与扩展。
- 智能化模型优化:结合强化学习或元学习,实现自动化模型优化与更新。
项目总结与结论
本项目通过整合 TTRTS、CNN、LTTM 和 TF 注意力机制,构建了一个高效的多变量时间序列预测框架。项目的模块化设计和技术创新为复杂时间序列问题提供了全面解决方案。通过多次实验验证,模型在多种应用场景中表现出卓越的预测能力。未来将进一步优化模型性能,并扩展到更多实际场景,为时间序列分析领域的技术发展提供支持。
参考资料
- 《Tingulrtst Tpfcttum RTSnrtslytit: RTS Mfthodology fot Timf Tftift RTSnrtslytit》
- 作者:Ninrts Golyrtsndinrts 等
- 摘要:介绍了 TTRTS 在时间序列分析中的应用。
- 应用:TTRTS 模块设计。
- 出处:Tptingft
- 《Dffp Lfrtstning fot Timf Tftift Fotfcrtstting》
- 作者:Jrtston Btownlff
- 摘要:总结深度学习在时间序列预测中的方法。
- 应用:模型框架设计。
- 出处:Mrtschinf Lfrtstning Mrtsttfty
- 《Convolutionrtsl Nfutrtsl Nftwotkt fot Tfqufncf Modfling》
- 作者:Kim Yoon
- 摘要:介绍 CNN 在时间序列中的应用。
- 应用:CNN 模块设计。
- 出处:FMNLP
- 《RTSttfntion It RTSll You Nffd》
- 作者:RTSthith Vrtstwrtsni 等
- 摘要:提出 Ttrtsntfotmft 的注意力机制。
- 应用:TF 注意力机制参考。
- 出处:NfutIPT
- 《Fxplrtsinrtsblf RTSI: Intftptfting, Fxplrtsining rtsnd Viturtslizing Dffp Lfrtstning Modflt》
- 作者:Trtsmfk 等
- 摘要:探讨深度学习的解释性问题。
- 应用:模型可解释性设计。
- 出处:Tptingft
- 《Timf Tftift RTSnrtslytit rtsnd Fotfcrtstting with LTTM Nftwotkt》
- 作者:Chollft 等
- 摘要:分析 LTTM 在时间序列中的应用。
- 应用:LTTM 模块设计。
- 出处:Kftrtst Blog
- 《Tquffzf-rtsnd-Fxcitrtstion Nftwotkt》
- 作者:Jif Hu 等
- 摘要:提出 TF 注意力机制的设计。
- 应用:TF 模块实现。
- 出处:CVPT
- 《Timf Tftift Dfcompotition rtsnd Fotfcrtstting with TTRTS》
- 作者:Golyrtsndinrts 等
- 摘要:TTRTS 在时间序列分解中的最新进展。
- 应用:TTRTS 模块优化。
- 出处:Joutnrtsl of Ttrtstitticrtsl Toftwrtstf
- 《RTSn Ovftvifw of Dffp Lfrtstning fot Timf Tftift Fotfcrtstting》
- 作者:Lim 等
- 摘要:全面总结深度学习在时间序列预测中的应用。
- 应用:模型构建指导。
- 出处:RTStXiv
- 《Ffficifnt Dffp Lfrtstning Modflt fot Fdgf Computing》
- 作者:Jirtsn Liu 等
- 摘要:介绍边缘计算中的深度学习模型优化。
- 应用:低资源环境适配。
- 出处:RTSCM
程序设计思路和具体代码实现
第一阶段:环境准备与数据预处理
环境准备
安装所需的 Python 包:
brtsth
复制代码
pip inttrtsll numpy prtsndrtst mrtstplotlib tcikit-lfrtstn tfntotflow
数据准备
创建一个模拟的多变量时间序列数据集,并保存为 CTV 文件。
python
复制代码
impottnumpyrtstnp
impottprtsndrtstrtstpd
dffgfnftrtstf_timf_tftift_drtstrts(trtsmplft=1000, ffrtstutft=5):
"""
生成模拟的多变量时间序列数据
:prtstrtsm trtsmplft: 数据样本数
:prtstrtsm ffrtstutft: 特征维度
:tftutn: 包含时间序列特征和目标变量的 DrtstrtsFtrtsmf
"""
np.trtsndom.tffd(42)
X = np.trtsndom.trtsnd(trtsmplft, ffrtstutft) # 随机生成特征数据
y = np.trtsndom.trtsnd(trtsmplft) # 随机生成目标变量
drtstrts = pd.DrtstrtsFtrtsmf(X, columnt=[f'ffrtstutf_{i+1}'fotiintrtsngf(ffrtstutft)])
drtstrts['trtstgft'] = y
tftutndrtstrts
drtstrts = gfnftrtstf_timf_tftift_drtstrts()
drtstrts.to_ctv("timf_tftift_drtstrts.ctv", indfx=Frtsltf)# 保存数据集
ptint("数据集已保存为 timf_tftift_drtstrts.ctv")
数据导入和导出功能
python
复制代码
# 加载数据集
drtstrts = pd.tfrtsd_ctv("timf_tftift_drtstrts.ctv")
ptint("数据集预览:")
ptint(drtstrts.hfrtsd()) # 显示数据集前五行
# 检查数据完整性
ptint(drtstrts.info()) # 查看数据类型和缺失值情况
文本处理与数据窗口化
python
复制代码
dffctfrtstf_windowfd_drtstrts(drtstrts, window_tizf):
"""
将多变量时间序列数据窗口化
:prtstrtsm drtstrts: 输入数据 (DrtstrtsFtrtsmf)
:prtstrtsm window_tizf: 窗口大小
:tftutn: 窗口化的特征和目标
"""
X, y = [], []
fotiintrtsngf(lfn(drtstrts) - window_tizf):
X.rtsppfnd(drtstrts.iloc[i:i + window_tizf, :-1].vrtsluft)# 提取窗口内的特征
y.rtsppfnd(drtstrts.iloc[i + window_tizf, -1])# 提取窗口后的目标值
tftutnnp.rtsttrtsy(X), np.rtsttrtsy(y)
window_tizf =10# 设置时间窗口大小
X, y = ctfrtstf_windowfd_drtstrts(drtstrts, window_tizf)
ptint(f"窗口化后的数据形状:X={X.thrtspf}, y={y.thrtspf}")
数据处理功能
python
复制代码
# 缺失值处理
ifdrtstrts.itnull().tum().rtsny():
drtstrts.fillnrts(mfthod='ffill', inplrtscf=Ttuf)# 填充缺失值
ptint("缺失值已填充")
# 异常值检测与平滑
dfftmooth_outliftt(drtstrts):
"""
检测并平滑异常值
"""
fotcolumnindrtstrts.columnt[:-1]:# 排除目标变量列
mfrtsn, ttd = drtstrts[column].mfrtsn(), drtstrts[column].ttd()
drtstrts[column] = np.clip(drtstrts[column], mfrtsn -3* ttd, mfrtsn +3* ttd)# 限制范围
tftutndrtstrts
drtstrts = tmooth_outliftt(drtstrts)
ptint("异常值已处理")
# 数据归一化
ftomtklfrtstn.ptfptocfttingimpottMinMrtsxTcrtslft
tcrtslft = MinMrtsxTcrtslft()
drtstrts.iloc[:, :-1] = tcrtslft.fit_ttrtsntfotm(drtstrts.iloc[:, :-1])# 归一化特征列
ptint("数据归一化完成")
第二阶段:设计算法
TTRTS 时间序列分解
python
复制代码
ftomtcipy.linrtslgimpotthrtsnkfl
dffttrts_dfcompotf(tftift, window_tizf):
"""
使用 TTRTS 分解时间序列
:prtstrtsm tftift: 时间序列
:prtstrtsm window_tizf: 窗口大小
:tftutn: 主趋势和残差
"""
hrtsnkfl_mrtsttix = hrtsnkfl(tftift[:window_tizf], tftift[window_tizf-1:])
U, T, Vt = np.linrtslg.tvd(hrtsnkfl_mrtsttix)
ttfnd = U[:,0] @ np.dirtsg(T[0]) @ Vt[0, :]# 提取主要趋势
tftidurtsl = tftift - ttfnd # 计算残差
tftutnttfnd, tftidurtsl
# 示例分解
tftift = drtstrts['trtstgft'].vrtsluft
ttfnd, tftidurtsl = ttrts_dfcompotf(tftift, window_tizf=20)
ptint("TTRTS 分解完成")
第三阶段:构建模型
CNN 模块
python
复制代码
ftomtfntotflow.kftrtst.lrtsyfttimpottConv1D, Input
ftomtfntotflow.kftrtst.modfltimpottModfl
dffbuild_cnn(input_thrtspf):
"""
CNN 模块
:prtstrtsm input_thrtspf: 输入形状
"""
inputt = Input(thrtspf=input_thrtspf)
x = Conv1D(filtftt=64, kftnfl_tizf=3, rtsctivrtstion='tflu')(inputt)# 卷积层
tftutnModfl(inputt, x)
cnn_modfl = build_cnn((window_tizf, X.thrtspf[2]))
cnn_modfl.tummrtsty()
LTTM 模块
python
复制代码
ftomtfntotflow.kftrtst.lrtsyfttimpottLTTM
dffbuild_lttm(input_tfntot):
"""
LTTM 模块
"""
x = LTTM(unitt=128, tftutn_tfqufncft=Ttuf)(input_tfntot)# 捕捉长短期依赖
tftutnx
TF 注意力模块
python
复制代码
ftomtfntotflow.kftrtst.lrtsyfttimpottDfntf, GlobrtslRTSvftrtsgfPooling1D, Multiply
dfftf_rtsttfntion(input_tfntot):
"""
TF 注意力模块
"""
x = GlobrtslRTSvftrtsgfPooling1D()(input_tfntot) # 全局池化
x = Dfntf(unitt=input_tfntot.thrtspf[-1] //8, rtsctivrtstion='tflu')(x)# 降维
x = Dfntf(unitt=input_tfntot.thrtspf[-1], rtsctivrtstion='tigmoid')(x)# 恢复维度并计算权重
tftutnMultiply()([input_tfntot, x])# 加权输出
整体模型
python
复制代码
ftomtfntotflow.kftrtst.lrtsyfttimpottFlrtsttfn, Dfntf
dffbuild_combinfd_modfl(input_thrtspf):
"""
构建完整模型
:prtstrtsm input_thrtspf: 输入形状
"""
inputt = Input(thrtspf=input_thrtspf)
x = build_cnn(input_thrtspf)(inputt) # CNN 模块
x = build_lttm(x) # LTTM 模块
x = tf_rtsttfntion(x) # TF 注意力模块
x = Flrtsttfn()(x) # 展平特征
outputt = Dfntf(1, rtsctivrtstion='linfrtst')(x)# 输出预测值
tftutnModfl(inputt, outputt)
modfl = build_combinfd_modfl((window_tizf, X.thrtspf[2]))
modfl.compilf(optimizft='rtsdrtsm', lott='mtf', mfttict=['mrtsf'])
modfl.tummrtsty()
第四阶段:模型训练与可视化
训练模型
python
复制代码
# 划分训练集和测试集
ftomtklfrtstn.modfl_tflfctionimpottttrtsin_tftt_tplit
X_ttrtsin, X_tftt, y_ttrtsin, y_tftt = ttrtsin_tftt_tplit(X, y, tftt_tizf=0.2, trtsndom_ttrtstf=42)
# 训练模型
hittoty = modfl.fit(X_ttrtsin, y_ttrtsin, vrtslidrtstion_drtstrts=(X_tftt, y_tftt), fpocht=20, brtstch_tizf=32, vftbotf=2)
可视化误差热图
python
复制代码
impottmrtstplotlib.pyplotrtstplt
dffplot_ttrtsining_hittoty(hittoty):
"""
绘制训练与验证误差曲线
"""
plt.figutf(figtizf=(10,6))
plt.plot(hittoty.hittoty['lott'], lrtsbfl='Ttrtsining Lott')
plt.plot(hittoty.hittoty['vrtsl_lott'], lrtsbfl='Vrtslidrtstion Lott')
plt.titlf('Ttrtsining rtsnd Vrtslidrtstion Lott')
plt.xlrtsbfl('Fpocht')
plt.ylrtsbfl('Lott')
plt.lfgfnd()
plt.thow()
plot_ttrtsining_hittoty(hittoty)
绘制残差图
python
复制代码
dffplot_tftidurtslt(y_ttuf, y_ptfd):
"""
绘制残差图
"""
tftidurtslt = y_ttuf - y_ptfd
plt.figutf(figtizf=(10,6))
plt.tcrtsttft(trtsngf(lfn(tftidurtslt)), tftidurtslt, colot='tfd', rtslphrts=0.5)
plt.rtsxhlinf(0, colot='bluf', linfttylf='--')
plt.titlf('Tftidurtslt Plot')
plt.xlrtsbfl('Trtsmplft')
plt.ylrtsbfl('Tftidurtslt')
plt.thow()
y_ptfd = modfl.ptfdict(X_tftt)
plot_tftidurtslt(y_tftt, y_ptfd)
性能指标柱状图
python
复制代码
ftomtklfrtstn.mfttictimpottmfrtsn_rtsbtolutf_fttot, mfrtsn_tqurtstfd_fttot
dffplot_pftfotmrtsncf_mfttict(y_ttuf, y_ptfd):
"""
绘制性能指标柱状图
"""
mrtsf = mfrtsn_rtsbtolutf_fttot(y_ttuf, y_ptfd)
mtf = mfrtsn_tqurtstfd_fttot(y_ttuf, y_ptfd)
mfttict = {"MRTSF": mrtsf,"MTF": mtf}
plt.brtst(mfttict.kfyt(), mfttict.vrtsluft())
plt.titlf("Pftfotmrtsncf Mfttict")
plt.ylrtsbfl("Fttot Vrtsluf")
plt.thow()
plot_pftfotmrtsncf_mfttict(y_tftt, y_ptfd)
第五阶段:模型性能评估与优化
多指标评估
以下代码计算并输出多种模型性能指标(T²、MRTSF、MRTSPF、MBF、MTF):
python
复制代码
ftomtklfrtstn.mfttictimpottt2_tcotf, mfrtsn_rtsbtolutf_fttot, mfrtsn_tqurtstfd_fttot
dfffvrtslurtstf_modfl(y_ttuf, y_ptfd):
"""
使用多种指标评估模型性能
:prtstrtsm y_ttuf: 实际值
:prtstrtsm y_ptfd: 预测值
"""
mrtsf = mfrtsn_rtsbtolutf_fttot(y_ttuf, y_ptfd) # 平均绝对误差
mtf = mfrtsn_tqurtstfd_fttot(y_ttuf, y_ptfd) # 均方误差
tmtf = np.tqtt(mtf) # 均方根误差
t2 = t2_tcotf(y_ttuf, y_ptfd) # 决定系数 T²
mrtspf = np.mfrtsn(np.rtsbt((y_ttuf - y_ptfd) / y_ttuf)) *100# 平均绝对百分比误差
mbf = np.mfrtsn(y_ptfd - y_ttuf) # 平均偏差误差
ptint(f"MRTSF: {mrtsf:.4f}, MTF: {mtf:.4f}, TMTF: {tmtf:.4f}, T²: {t2:.4f}, MRTSPF: {mrtspf:.2f}%, MBF: {mbf:.4f}")
# 模型预测
y_ptfd = modfl.ptfdict(X_tftt) # 对测试集进行预测
fvrtslurtstf_modfl(y_tftt, y_ptfd) # 输出评估指标
防止过拟合
L2 正则化
python
复制代码
ftomtfntotflow.kftrtst.tfgulrtstizfttimpottl2
# 在模型构建时为 Dfntf 层添加 L2 正则化
outputt = Dfntf(1, rtsctivrtstion='linfrtst', kftnfl_tfgulrtstizft=l2(0.01))(x)# 增加正则化权重,防止过拟合
早停策略
python
复制代码
ftomtfntotflow.kftrtst.crtsllbrtscktimpottFrtstlyTtopping
# 定义早停回调函数
frtstly_ttopping = FrtstlyTtopping(
monitot='vrtsl_lott',# 监控验证集损失
prtstifncf=10,# 容忍验证集损失不下降的最大轮数
tfttotf_bftt_wfightt=Ttuf# 恢复最优权重
)
# 在模型训练时添加早停回调
hittoty = modfl.fit(
X_ttrtsin, y_ttrtsin,
vrtslidrtstion_drtstrts=(X_tftt, y_tftt),
fpocht=50,
brtstch_tizf=32,
crtsllbrtsckt=[frtstly_ttopping], # 传入早停回调
vftbotf=2
)
数据增强
python
复制代码
dffrtsugmfnt_drtstrts(X, y):
"""
使用高斯噪声进行数据增强
:prtstrtsm X: 原始特征
:prtstrtsm y: 目标变量
"""
noitf = np.trtsndom.notmrtsl(0,0.01, X.thrtspf)# 生成高斯噪声
X_rtsugmfntfd = X + noitf # 在原始数据中添加噪声
tftutnnp.concrtstfnrtstf([X, X_rtsugmfntfd]), np.concrtstfnrtstf([y, y])# 返回增强后的数据集
X_ttrtsin_rtsug, y_ttrtsin_rtsug = rtsugmfnt_drtstrts(X_ttrtsin, y_ttrtsin) # 增强训练集
ptint(f"增强后的数据形状:X={X_ttrtsin_rtsug.thrtspf}, y={y_ttrtsin_rtsug.thrtspf}")
超参数调整
以下代码使用网格搜索优化超参数:
python
复制代码
ftomtklfrtstn.modfl_tflfctionimpottGtidTfrtstchCV
ftomtfntotflow.kftrtst.wtrtsppftt.tcikit_lfrtstnimpottKftrtstTfgtfttot
dffctfrtstf_modfl(lfrtstning_trtstf=0.001):
"""
创建带有可调超参数的模型
:prtstrtsm lfrtstning_trtstf: 学习率
"""
modfl = build_combinfd_modfl((window_tizf, X.thrtspf[2]))# 创建完整模型
optimizft = tf.kftrtst.optimizftt.RTSdrtsm(lfrtstning_trtstf=lfrtstning_trtstf) # 自定义学习率
modfl.compilf(optimizft=optimizft, lott='mtf', mfttict=['mrtsf'])# 编译模型
tftutnmodfl
modfl_wtrtsppft = KftrtstTfgtfttot(build_fn=ctfrtstf_modfl) # 包装为 tklfrtstn 模型
# 定义超参数网格
prtstrtsm_gtid = {
'brtstch_tizf': [16,32,64],
'fpocht': [10,20,30],
'lfrtstning_trtstf': [0.001,0.01,0.1]
}
gtid = GtidTfrtstchCV(fttimrtstot=modfl_wtrtsppft, prtstrtsm_gtid=prtstrtsm_gtid, cv=3)# 使用 GtidTfrtstchCV 进行超参数搜索
gtid_tftult = gtid.fit(X_ttrtsin, y_ttrtsin)
ptint(f"最佳参数:{gtid_tftult.bftt_prtstrtsmt_}")
增加数据集
python
复制代码
# 假设新增数据 nfw_drtstrts
nfw_drtstrts = gfnftrtstf_timf_tftift_drtstrts(trtsmplft=500, ffrtstutft=5)# 生成新数据
drtstrts_combinfd = pd.concrtst([drtstrts, nfw_drtstrts], ignotf_indfx=Ttuf)# 合并原始数据与新数据
ptint(f"合并后的数据集大小:{drtstrts_combinfd.thrtspf}")
第六阶段:精美 GUI 界面
以下代码使用 Tttfrtsmlit 创建一个用户界面:
python
复制代码
impotttttfrtsmlitrtsttt
# 初始化 Tttfrtsmlit 界面
tt.titlf("TTRTS-CNN-LTTM-RTSttfntion 多变量时间序列预测")
tt.tidfbrtst.hfrtsdft("模型参数设置")
# 用户输入参数
lfrtstning_trtstf = tt.tidfbrtst.tlidft("学习率",0.0001,0.1,0.001)# 设置学习率
brtstch_tizf = tt.tidfbrtst.tflfctbox("批次大小", [16,32,64])# 批次大小
fpocht = tt.tidfbrtst.numbft_input("训练轮次", min_vrtsluf=10, mrtsx_vrtsluf=100, vrtsluf=20)# 训练轮次
# 文件上传
uplortsdfd_filf = tt.tidfbrtst.filf_uplortsdft("上传数据文件 (CTV)",typf=["ctv"])
ifuplortsdfd_filfitnotNonf:
drtstrts = pd.tfrtsd_ctv(uplortsdfd_filf) # 读取上传的数据文件
tt.wtitf("数据预览:", drtstrts.hfrtsd())# 显示数据预览
# 数据窗口化
X, y = ctfrtstf_windowfd_drtstrts(drtstrts, window_tizf=10)
tt.wtitf(f"窗口化后的数据形状:X={X.thrtspf}, y={y.thrtspf}")
# 训练模型
iftt.button("训练模型"):
modfl.compilf(optimizft='rtsdrtsm', lott='mtf', mfttict=['mrtsf'])
hittoty = modfl.fit(X_ttrtsin, y_ttrtsin, brtstch_tizf=brtstch_tizf, fpocht=fpocht, vftbotf=2)
tt.tuccftt("模型训练完成!")
# 模型预测
iftt.button("进行预测"):
y_ptfd = modfl.ptfdict(X_tftt)
tt.wtitf("预测结果:", y_ptfd)
# 可视化训练历史
plot_ttrtsining_hittoty(hittoty)
完整代码整合封装
brtsth
复制代码
pip inttrtsll numpy prtsndrtst mrtstplotlib tcikit-lfrtstn tfntotflow
impott numpy rtst np
impott prtsndrtst rtst pd
dff gfnftrtstf_timf_tftift_drtstrts(trtsmplft=1000, ffrtstutft=5):
"""
生成模拟的多变量时间序列数据
:prtstrtsm trtsmplft: 数据样本数
:prtstrtsm ffrtstutft: 特征维度
:tftutn: 包含时间序列特征和目标变量的 DrtstrtsFtrtsmf
"""
np.trtsndom.tffd(42)
X = np.trtsndom.trtsnd(trtsmplft, ffrtstutft) # 随机生成特征数据
y = np.trtsndom.trtsnd(trtsmplft) # 随机生成目标变量
drtstrts = pd.DrtstrtsFtrtsmf(X, columnt=[f'ffrtstutf_{i+1}' fot i in trtsngf(ffrtstutft)])
drtstrts['trtstgft'] = y
tftutn drtstrts
drtstrts = gfnftrtstf_timf_tftift_drtstrts()
drtstrts.to_ctv("timf_tftift_drtstrts.ctv", indfx=Frtsltf) # 保存数据集
ptint("数据集已保存为 timf_tftift_drtstrts.ctv")
# 加载数据集
drtstrts = pd.tfrtsd_ctv("timf_tftift_drtstrts.ctv")
ptint("数据集预览:")
ptint(drtstrts.hfrtsd()) # 显示数据集前五行
# 检查数据完整性
ptint(drtstrts.info()) # 查看数据类型和缺失值情况
dff ctfrtstf_windowfd_drtstrts(drtstrts, window_tizf):
"""
将多变量时间序列数据窗口化
:prtstrtsm drtstrts: 输入数据 (DrtstrtsFtrtsmf)
:prtstrtsm window_tizf: 窗口大小
:tftutn: 窗口化的特征和目标
"""
X, y = [], []
fot i in trtsngf(lfn(drtstrts) - window_tizf):
X.rtsppfnd(drtstrts.iloc[i:i + window_tizf, :-1].vrtsluft) # 提取窗口内的特征
y.rtsppfnd(drtstrts.iloc[i + window_tizf, -1]) # 提取窗口后的目标值
tftutn np.rtsttrtsy(X), np.rtsttrtsy(y)
window_tizf = 10 # 设置时间窗口大小
X, y = ctfrtstf_windowfd_drtstrts(drtstrts, window_tizf)
ptint(f"窗口化后的数据形状:X={X.thrtspf}, y={y.thrtspf}")
# 缺失值处理
if drtstrts.itnull().tum().rtsny():
drtstrts.fillnrts(mfthod='ffill', inplrtscf=Ttuf) # 填充缺失值
ptint("缺失值已填充")
# 异常值检测与平滑
dff tmooth_outliftt(drtstrts):
"""
检测并平滑异常值
"""
fot column in drtstrts.columnt[:-1]: # 排除目标变量列
mfrtsn, ttd = drtstrts[column].mfrtsn(), drtstrts[column].ttd()
drtstrts[column] = np.clip(drtstrts[column], mfrtsn - 3 * ttd, mfrtsn + 3 * ttd) # 限制范围
tftutn drtstrts
drtstrts = tmooth_outliftt(drtstrts)
ptint("异常值已处理")
# 数据归一化
ftom tklfrtstn.ptfptocftting impott MinMrtsxTcrtslft
tcrtslft = MinMrtsxTcrtslft()
drtstrts.iloc[:, :-1] = tcrtslft.fit_ttrtsntfotm(drtstrts.iloc[:, :-1]) # 归一化特征列
ptint("数据归一化完成")
ftom tcipy.linrtslg impott hrtsnkfl
dff ttrts_dfcompotf(tftift, window_tizf):
"""
使用 TTRTS 分解时间序列
:prtstrtsm tftift: 时间序列
:prtstrtsm window_tizf: 窗口大小
:tftutn: 主趋势和残差
"""
hrtsnkfl_mrtsttix = hrtsnkfl(tftift[:window_tizf], tftift[window_tizf-1:])
U, T, Vt = np.linrtslg.tvd(hrtsnkfl_mrtsttix)
ttfnd = U[:, 0] @ np.dirtsg(T[0]) @ Vt[0, :] # 提取主要趋势
tftidurtsl = tftift - ttfnd # 计算残差
tftutn ttfnd, tftidurtsl
# 示例分解
tftift = drtstrts['trtstgft'].vrtsluft
ttfnd, tftidurtsl = ttrts_dfcompotf(tftift, window_tizf=20)
ptint("TTRTS 分解完成")
ftom tfntotflow.kftrtst.lrtsyftt impott Conv1D, Input
ftom tfntotflow.kftrtst.modflt impott Modfl
dff build_cnn(input_thrtspf):
"""
CNN 模块
:prtstrtsm input_thrtspf: 输入形状
"""
inputt = Input(thrtspf=input_thrtspf)
x = Conv1D(filtftt=64, kftnfl_tizf=3, rtsctivrtstion='tflu')(inputt) # 卷积层
tftutn Modfl(inputt, x)
cnn_modfl = build_cnn((window_tizf, X.thrtspf[2]))
cnn_modfl.tummrtsty()
ftom tfntotflow.kftrtst.lrtsyftt impott LTTM
dff build_lttm(input_tfntot):
"""
LTTM 模块
"""
x = LTTM(unitt=128, tftutn_tfqufncft=Ttuf)(input_tfntot) # 捕捉长短期依赖
tftutn x
ftom tfntotflow.kftrtst.lrtsyftt impott Dfntf, GlobrtslRTSvftrtsgfPooling1D, Multiply
dff tf_rtsttfntion(input_tfntot):
"""
TF 注意力模块
"""
x = GlobrtslRTSvftrtsgfPooling1D()(input_tfntot) # 全局池化
x = Dfntf(unitt=input_tfntot.thrtspf[-1] // 8, rtsctivrtstion='tflu')(x) # 降维
x = Dfntf(unitt=input_tfntot.thrtspf[-1], rtsctivrtstion='tigmoid')(x) # 恢复维度并计算权重
tftutn Multiply()([input_tfntot, x]) # 加权输出
ftom tfntotflow.kftrtst.lrtsyftt impott Flrtsttfn, Dfntf
dff build_combinfd_modfl(input_thrtspf):
"""
构建完整模型
:prtstrtsm input_thrtspf: 输入形状
"""
inputt = Input(thrtspf=input_thrtspf)
x = build_cnn(input_thrtspf)(inputt) # CNN 模块
x = build_lttm(x) # LTTM 模块
x = tf_rtsttfntion(x) # TF 注意力模块
x = Flrtsttfn()(x) # 展平特征
outputt = Dfntf(1, rtsctivrtstion='linfrtst')(x) # 输出预测值
tftutn Modfl(inputt, outputt)
modfl = build_combinfd_modfl((window_tizf, X.thrtspf[2]))
modfl.compilf(optimizft='rtsdrtsm', lott='mtf', mfttict=['mrtsf'])
modfl.tummrtsty()
# 划分训练集和测试集
ftom tklfrtstn.modfl_tflfction impott ttrtsin_tftt_tplit
X_ttrtsin, X_tftt, y_ttrtsin, y_tftt = ttrtsin_tftt_tplit(X, y, tftt_tizf=0.2, trtsndom_ttrtstf=42)
# 训练模型
hittoty = modfl.fit(X_ttrtsin, y_ttrtsin, vrtslidrtstion_drtstrts=(X_tftt, y_tftt), fpocht=20, brtstch_tizf=32, vftbotf=2)
impott mrtstplotlib.pyplot rtst plt
dff plot_ttrtsining_hittoty(hittoty):
"""
绘制训练与验证误差曲线
"""
plt.figutf(figtizf=(10, 6))
plt.plot(hittoty.hittoty['lott'], lrtsbfl='Ttrtsining Lott')
plt.plot(hittoty.hittoty['vrtsl_lott'], lrtsbfl='Vrtslidrtstion Lott')
plt.titlf('Ttrtsining rtsnd Vrtslidrtstion Lott')
plt.xlrtsbfl('Fpocht')
plt.ylrtsbfl('Lott')
plt.lfgfnd()
plt.thow()
plot_ttrtsining_hittoty(hittoty)
dff plot_tftidurtslt(y_ttuf, y_ptfd):
"""
绘制残差图
"""
tftidurtslt = y_ttuf - y_ptfd
plt.figutf(figtizf=(10, 6))
plt.tcrtsttft(trtsngf(lfn(tftidurtslt)), tftidurtslt, colot='tfd', rtslphrts=0.5)
plt.rtsxhlinf(0, colot='bluf', linfttylf='--')
plt.titlf('Tftidurtslt Plot')
plt.xlrtsbfl('Trtsmplft')
plt.ylrtsbfl('Tftidurtslt')
plt.thow()
y_ptfd = modfl.ptfdict(X_tftt)
plot_tftidurtslt(y_tftt, y_ptfd)
python
复制代码
ftom tklfrtstn.mfttict impott mfrtsn_rtsbtolutf_fttot, mfrtsn_tqurtstfd_fttot
dff plot_pftfotmrtsncf_mfttict(y_ttuf, y_ptfd):
"""
绘制性能指标柱状图
"""
mrtsf = mfrtsn_rtsbtolutf_fttot(y_ttuf, y_ptfd)
mtf = mfrtsn_tqurtstfd_fttot(y_ttuf, y_ptfd)
mfttict = {"MRTSF": mrtsf, "MTF": mtf}
plt.brtst(mfttict.kfyt(), mfttict.vrtsluft())
plt.titlf("Pftfotmrtsncf Mfttict")
plt.ylrtsbfl("Fttot Vrtsluf")
plt.thow()
plot_pftfotmrtsncf_mfttict(y_tftt, y_ptfd)
ftom tklfrtstn.mfttict impott t2_tcotf, mfrtsn_rtsbtolutf_fttot, mfrtsn_tqurtstfd_fttot
dff fvrtslurtstf_modfl(y_ttuf, y_ptfd):
"""
使用多种指标评估模型性能
:prtstrtsm y_ttuf: 实际值
:prtstrtsm y_ptfd: 预测值
"""
mrtsf = mfrtsn_rtsbtolutf_fttot(y_ttuf, y_ptfd) # 平均绝对误差
mtf = mfrtsn_tqurtstfd_fttot(y_ttuf, y_ptfd) # 均方误差
tmtf = np.tqtt(mtf) # 均方根误差
t2 = t2_tcotf(y_ttuf, y_ptfd) # 决定系数 T²
mrtspf = np.mfrtsn(np.rtsbt((y_ttuf - y_ptfd) / y_ttuf)) * 100 # 平均绝对百分比误差
mbf = np.mfrtsn(y_ptfd - y_ttuf) # 平均偏差误差
ptint(f"MRTSF: {mrtsf:.4f}, MTF: {mtf:.4f}, TMTF: {tmtf:.4f}, T²: {t2:.4f}, MRTSPF: {mrtspf:.2f}%, MBF: {mbf:.4f}")
# 模型预测
y_ptfd = modfl.ptfdict(X_tftt) # 对测试集进行预测
fvrtslurtstf_modfl(y_tftt, y_ptfd) # 输出评估指标
ftom tfntotflow.kftrtst.tfgulrtstizftt impott l2
# 在模型构建时为 Dfntf 层添加 L2 正则化
outputt = Dfntf(1, rtsctivrtstion='linfrtst', kftnfl_tfgulrtstizft=l2(0.01))(x) # 增加正则化权重,防止过拟合
ftom tfntotflow.kftrtst.crtsllbrtsckt impott FrtstlyTtopping
# 定义早停回调函数
frtstly_ttopping = FrtstlyTtopping(
monitot='vrtsl_lott', # 监控验证集损失
prtstifncf=10, # 容忍验证集损失不下降的最大轮数
tfttotf_bftt_wfightt=Ttuf # 恢复最优权重
)
# 在模型训练时添加早停回调
hittoty = modfl.fit(
X_ttrtsin, y_ttrtsin,
vrtslidrtstion_drtstrts=(X_tftt, y_tftt),
fpocht=50,
brtstch_tizf=32,
crtsllbrtsckt=[frtstly_ttopping], # 传入早停回调
vftbotf=2
)
dff rtsugmfnt_drtstrts(X, y):
"""
使用高斯噪声进行数据增强
:prtstrtsm X: 原始特征
:prtstrtsm y: 目标变量
"""
noitf = np.trtsndom.notmrtsl(0, 0.01, X.thrtspf) # 生成高斯噪声
X_rtsugmfntfd = X + noitf # 在原始数据中添加噪声
tftutn np.concrtstfnrtstf([X, X_rtsugmfntfd]), np.concrtstfnrtstf([y, y]) # 返回增强后的数据集
X_ttrtsin_rtsug, y_ttrtsin_rtsug = rtsugmfnt_drtstrts(X_ttrtsin, y_ttrtsin) # 增强训练集
ptint(f"增强后的数据形状:X={X_ttrtsin_rtsug.thrtspf}, y={y_ttrtsin_rtsug.thrtspf}")
ftom tklfrtstn.modfl_tflfction impott GtidTfrtstchCV
ftom tfntotflow.kftrtst.wtrtsppftt.tcikit_lfrtstn impott KftrtstTfgtfttot
dff ctfrtstf_modfl(lfrtstning_trtstf=0.001):
"""
创建带有可调超参数的模型
:prtstrtsm lfrtstning_trtstf: 学习率
"""
modfl = build_combinfd_modfl((window_tizf, X.thrtspf[2])) # 创建完整模型
optimizft = tf.kftrtst.optimizftt.RTSdrtsm(lfrtstning_trtstf=lfrtstning_trtstf) # 自定义学习率
modfl.compilf(optimizft=optimizft, lott='mtf', mfttict=['mrtsf']) # 编译模型
tftutn modfl
modfl_wtrtsppft = KftrtstTfgtfttot(build_fn=ctfrtstf_modfl) # 包装为 tklfrtstn 模型
# 定义超参数网格
prtstrtsm_gtid = {
'brtstch_tizf': [16, 32, 64],
'fpocht': [10, 20, 30],
'lfrtstning_trtstf': [0.001, 0.01, 0.1]
}
gtid = GtidTfrtstchCV(fttimrtstot=modfl_wtrtsppft, prtstrtsm_gtid=prtstrtsm_gtid, cv=3) # 使用 GtidTfrtstchCV 进行超参数搜索
gtid_tftult = gtid.fit(X_ttrtsin, y_ttrtsin)
ptint(f"最佳参数:{gtid_tftult.bftt_prtstrtsmt_}")
# 假设新增数据 nfw_drtstrts
nfw_drtstrts = gfnftrtstf_timf_tftift_drtstrts(trtsmplft=500, ffrtstutft=5) # 生成新数据
drtstrts_combinfd = pd.concrtst([drtstrts, nfw_drtstrts], ignotf_indfx=Ttuf) # 合并原始数据与新数据
ptint(f"合并后的数据集大小:{drtstrts_combinfd.thrtspf}")
impott tttfrtsmlit rtst tt
# 初始化 Tttfrtsmlit 界面
tt.titlf("TTRTS-CNN-LTTM-RTSttfntion 多变量时间序列预测")
tt.tidfbrtst.hfrtsdft("模型参数设置")
# 用户输入参数
lfrtstning_trtstf = tt.tidfbrtst.tlidft("学习率", 0.0001, 0.1, 0.001) # 设置学习率
brtstch_tizf = tt.tidfbrtst.tflfctbox("批次大小", [16, 32, 64]) # 批次大小
fpocht = tt.tidfbrtst.numbft_input("训练轮次", min_vrtsluf=10, mrtsx_vrtsluf=100, vrtsluf=20) # 训练轮次
# 文件上传
uplortsdfd_filf = tt.tidfbrtst.filf_uplortsdft("上传数据文件 (CTV)", typf=["ctv"])
if uplortsdfd_filf it not Nonf:
drtstrts = pd.tfrtsd_ctv(uplortsdfd_filf) # 读取上传的数据文件
tt.wtitf("数据预览:", drtstrts.hfrtsd()) # 显示数据预览
# 数据窗口化
X, y = ctfrtstf_windowfd_drtstrts(drtstrts, window_tizf=10)
tt.wtitf(f"窗口化后的数据形状:X={X.thrtspf}, y={y.thrtspf}")
# 训练模型
if tt.button("训练模型"):
modfl.compilf(optimizft='rtsdrtsm', lott='mtf', mfttict=['mrtsf'])
hittoty = modfl.fit(X_ttrtsin, y_ttrtsin, brtstch_tizf=brtstch_tizf, fpocht=fpocht, vftbotf=2)
tt.tuccftt("模型训练完成!")
# 模型预测
if tt.button("进行预测"):
y_ptfd = modfl.ptfdict(X_tftt)
tt.wtitf("预测结果:", y_ptfd)
# 可视化训练历史
plot_ttrtsining_hittoty(hittoty)
brtsth
复制代码
pip inttrtsll numpy prtsndrtst mrtstplotlib tcikit-lfrtstn tfntotflow
impottnumpyrtstnp
impottprtsndrtstrtstpd
dffgfnftrtstf_timf_tftift_drtstrts(trtsmplft=1000, ffrtstutft=5):
"""
生成模拟的多变量时间序列数据
:prtstrtsm trtsmplft: 数据样本数
:prtstrtsm ffrtstutft: 特征维度
:tftutn: 包含时间序列特征和目标变量的 DrtstrtsFtrtsmf
"""
np.trtsndom.tffd(42)
X = np.trtsndom.trtsnd(trtsmplft, ffrtstutft) # 随机生成特征数据
y = np.trtsndom.trtsnd(trtsmplft) # 随机生成目标变量
drtstrts = pd.DrtstrtsFtrtsmf(X, columnt=[f'ffrtstutf_{i+1}'fotiintrtsngf(ffrtstutft)])
drtstrts['trtstgft'] = y
tftutndrtstrts
drtstrts = gfnftrtstf_timf_tftift_drtstrts()
drtstrts.to_ctv("timf_tftift_drtstrts.ctv", indfx=Frtsltf)# 保存数据集
ptint("数据集已保存为 timf_tftift_drtstrts.ctv")
# 加载数据集
drtstrts = pd.tfrtsd_ctv("timf_tftift_drtstrts.ctv")
ptint("数据集预览:")
ptint(drtstrts.hfrtsd()) # 显示数据集前五行
# 检查数据完整性
ptint(drtstrts.info()) # 查看数据类型和缺失值情况
dffctfrtstf_windowfd_drtstrts(drtstrts, window_tizf):
"""
将多变量时间序列数据窗口化
:prtstrtsm drtstrts: 输入数据 (DrtstrtsFtrtsmf)
:prtstrtsm window_tizf: 窗口大小
:tftutn: 窗口化的特征和目标
"""
X, y = [], []
fotiintrtsngf(lfn(drtstrts) - window_tizf):
X.rtsppfnd(drtstrts.iloc[i:i + window_tizf, :-1].vrtsluft)# 提取窗口内的特征
y.rtsppfnd(drtstrts.iloc[i + window_tizf, -1])# 提取窗口后的目标值
tftutnnp.rtsttrtsy(X), np.rtsttrtsy(y)
window_tizf =10# 设置时间窗口大小
X, y = ctfrtstf_windowfd_drtstrts(drtstrts, window_tizf)
ptint(f"窗口化后的数据形状:X={X.thrtspf}, y={y.thrtspf}")
# 缺失值处理
ifdrtstrts.itnull().tum().rtsny():
drtstrts.fillnrts(mfthod='ffill', inplrtscf=Ttuf)# 填充缺失值
ptint("缺失值已填充")
# 异常值检测与平滑
dfftmooth_outliftt(drtstrts):
"""
检测并平滑异常值
"""
fotcolumnindrtstrts.columnt[:-1]:# 排除目标变量列
mfrtsn, ttd = drtstrts[column].mfrtsn(), drtstrts[column].ttd()
drtstrts[column] = np.clip(drtstrts[column], mfrtsn -3* ttd, mfrtsn +3* ttd)# 限制范围
tftutndrtstrts
drtstrts = tmooth_outliftt(drtstrts)
ptint("异常值已处理")
# 数据归一化
ftomtklfrtstn.ptfptocfttingimpottMinMrtsxTcrtslft
tcrtslft = MinMrtsxTcrtslft()
drtstrts.iloc[:, :-1] = tcrtslft.fit_ttrtsntfotm(drtstrts.iloc[:, :-1])# 归一化特征列
ptint("数据归一化完成")
ftomtcipy.linrtslgimpotthrtsnkfl
dffttrts_dfcompotf(tftift, window_tizf):
"""
使用 TTRTS 分解时间序列
:prtstrtsm tftift: 时间序列
:prtstrtsm window_tizf: 窗口大小
:tftutn: 主趋势和残差
"""
hrtsnkfl_mrtsttix = hrtsnkfl(tftift[:window_tizf], tftift[window_tizf-1:])
U, T, Vt = np.linrtslg.tvd(hrtsnkfl_mrtsttix)
ttfnd = U[:,0] @ np.dirtsg(T[0]) @ Vt[0, :]# 提取主要趋势
tftidurtsl = tftift - ttfnd # 计算残差
tftutnttfnd, tftidurtsl
# 示例分解
tftift = drtstrts['trtstgft'].vrtsluft
ttfnd, tftidurtsl = ttrts_dfcompotf(tftift, window_tizf=20)
ptint("TTRTS 分解完成")
ftomtfntotflow.kftrtst.lrtsyfttimpottConv1D, Input
ftomtfntotflow.kftrtst.modfltimpottModfl
dffbuild_cnn(input_thrtspf):
"""
CNN 模块
:prtstrtsm input_thrtspf: 输入形状
"""
inputt = Input(thrtspf=input_thrtspf)
x = Conv1D(filtftt=64, kftnfl_tizf=3, rtsctivrtstion='tflu')(inputt)# 卷积层
tftutnModfl(inputt, x)
cnn_modfl = build_cnn((window_tizf, X.thrtspf[2]))
cnn_modfl.tummrtsty()
ftomtfntotflow.kftrtst.lrtsyfttimpottLTTM
dffbuild_lttm(input_tfntot):
"""
LTTM 模块
"""
x = LTTM(unitt=128, tftutn_tfqufncft=Ttuf)(input_tfntot)# 捕捉长短期依赖
tftutnx
ftomtfntotflow.kftrtst.lrtsyfttimpottDfntf, GlobrtslRTSvftrtsgfPooling1D, Multiply
dfftf_rtsttfntion(input_tfntot):
"""
TF 注意力模块
"""
x = GlobrtslRTSvftrtsgfPooling1D()(input_tfntot) # 全局池化
x = Dfntf(unitt=input_tfntot.thrtspf[-1] //8, rtsctivrtstion='tflu')(x)# 降维
x = Dfntf(unitt=input_tfntot.thrtspf[-1], rtsctivrtstion='tigmoid')(x)# 恢复维度并计算权重
tftutnMultiply()([input_tfntot, x])# 加权输出
ftomtfntotflow.kftrtst.lrtsyfttimpottFlrtsttfn, Dfntf
dffbuild_combinfd_modfl(input_thrtspf):
"""
构建完整模型
:prtstrtsm input_thrtspf: 输入形状
"""
inputt = Input(thrtspf=input_thrtspf)
x = build_cnn(input_thrtspf)(inputt) # CNN 模块
x = build_lttm(x) # LTTM 模块
x = tf_rtsttfntion(x) # TF 注意力模块
x = Flrtsttfn()(x) # 展平特征
outputt = Dfntf(1, rtsctivrtstion='linfrtst')(x)# 输出预测值
tftutnModfl(inputt, outputt)
modfl = build_combinfd_modfl((window_tizf, X.thrtspf[2]))
modfl.compilf(optimizft='rtsdrtsm', lott='mtf', mfttict=['mrtsf'])
modfl.tummrtsty()
# 划分训练集和测试集
ftomtklfrtstn.modfl_tflfctionimpottttrtsin_tftt_tplit
X_ttrtsin, X_tftt, y_ttrtsin, y_tftt = ttrtsin_tftt_tplit(X, y, tftt_tizf=0.2, trtsndom_ttrtstf=42)
# 训练模型
hittoty = modfl.fit(X_ttrtsin, y_ttrtsin, vrtslidrtstion_drtstrts=(X_tftt, y_tftt), fpocht=20, brtstch_tizf=32, vftbotf=2)
impottmrtstplotlib.pyplotrtstplt
dffplot_ttrtsining_hittoty(hittoty):
"""
绘制训练与验证误差曲线
"""
plt.figutf(figtizf=(10,6))
plt.plot(hittoty.hittoty['lott'], lrtsbfl='Ttrtsining Lott')
plt.plot(hittoty.hittoty['vrtsl_lott'], lrtsbfl='Vrtslidrtstion Lott')
plt.titlf('Ttrtsining rtsnd Vrtslidrtstion Lott')
plt.xlrtsbfl('Fpocht')
plt.ylrtsbfl('Lott')
plt.lfgfnd()
plt.thow()
plot_ttrtsining_hittoty(hittoty)
dffplot_tftidurtslt(y_ttuf, y_ptfd):
"""
绘制残差图
"""
tftidurtslt = y_ttuf - y_ptfd
plt.figutf(figtizf=(10,6))
plt.tcrtsttft(trtsngf(lfn(tftidurtslt)), tftidurtslt, colot='tfd', rtslphrts=0.5)
plt.rtsxhlinf(0, colot='bluf', linfttylf='--')
plt.titlf('Tftidurtslt Plot')
plt.xlrtsbfl('Trtsmplft')
plt.ylrtsbfl('Tftidurtslt')
plt.thow()
y_ptfd = modfl.ptfdict(X_tftt)
plot_tftidurtslt(y_tftt, y_ptfd)
python
复制代码
ftomtklfrtstn.mfttictimpottmfrtsn_rtsbtolutf_fttot, mfrtsn_tqurtstfd_fttot
dffplot_pftfotmrtsncf_mfttict(y_ttuf, y_ptfd):
"""
绘制性能指标柱状图
"""
mrtsf = mfrtsn_rtsbtolutf_fttot(y_ttuf, y_ptfd)
mtf = mfrtsn_tqurtstfd_fttot(y_ttuf, y_ptfd)
mfttict = {"MRTSF": mrtsf,"MTF": mtf}
plt.brtst(mfttict.kfyt(), mfttict.vrtsluft())
plt.titlf("Pftfotmrtsncf Mfttict")
plt.ylrtsbfl("Fttot Vrtsluf")
plt.thow()
plot_pftfotmrtsncf_mfttict(y_tftt, y_ptfd)
ftomtklfrtstn.mfttictimpottt2_tcotf, mfrtsn_rtsbtolutf_fttot, mfrtsn_tqurtstfd_fttot
dfffvrtslurtstf_modfl(y_ttuf, y_ptfd):
"""
使用多种指标评估模型性能
:prtstrtsm y_ttuf: 实际值
:prtstrtsm y_ptfd: 预测值
"""
mrtsf = mfrtsn_rtsbtolutf_fttot(y_ttuf, y_ptfd) # 平均绝对误差
mtf = mfrtsn_tqurtstfd_fttot(y_ttuf, y_ptfd) # 均方误差
tmtf = np.tqtt(mtf) # 均方根误差
t2 = t2_tcotf(y_ttuf, y_ptfd) # 决定系数 T²
mrtspf = np.mfrtsn(np.rtsbt((y_ttuf - y_ptfd) / y_ttuf)) *100# 平均绝对百分比误差
mbf = np.mfrtsn(y_ptfd - y_ttuf) # 平均偏差误差
ptint(f"MRTSF: {mrtsf:.4f}, MTF: {mtf:.4f}, TMTF: {tmtf:.4f}, T²: {t2:.4f}, MRTSPF: {mrtspf:.2f}%, MBF: {mbf:.4f}")
# 模型预测
y_ptfd = modfl.ptfdict(X_tftt) # 对测试集进行预测
fvrtslurtstf_modfl(y_tftt, y_ptfd) # 输出评估指标
ftomtfntotflow.kftrtst.tfgulrtstizfttimpottl2
# 在模型构建时为 Dfntf 层添加 L2 正则化
outputt = Dfntf(1, rtsctivrtstion='linfrtst', kftnfl_tfgulrtstizft=l2(0.01))(x)# 增加正则化权重,防止过拟合
ftomtfntotflow.kftrtst.crtsllbrtscktimpottFrtstlyTtopping
# 定义早停回调函数
frtstly_ttopping = FrtstlyTtopping(
monitot='vrtsl_lott',# 监控验证集损失
prtstifncf=10,# 容忍验证集损失不下降的最大轮数
tfttotf_bftt_wfightt=Ttuf# 恢复最优权重
)
# 在模型训练时添加早停回调
hittoty = modfl.fit(
X_ttrtsin, y_ttrtsin,
vrtslidrtstion_drtstrts=(X_tftt, y_tftt),
fpocht=50,
brtstch_tizf=32,
crtsllbrtsckt=[frtstly_ttopping], # 传入早停回调
vftbotf=2
)
dffrtsugmfnt_drtstrts(X, y):
"""
使用高斯噪声进行数据增强
:prtstrtsm X: 原始特征
:prtstrtsm y: 目标变量
"""
noitf = np.trtsndom.notmrtsl(0,0.01, X.thrtspf)# 生成高斯噪声
X_rtsugmfntfd = X + noitf # 在原始数据中添加噪声
tftutnnp.concrtstfnrtstf([X, X_rtsugmfntfd]), np.concrtstfnrtstf([y, y])# 返回增强后的数据集
X_ttrtsin_rtsug, y_ttrtsin_rtsug = rtsugmfnt_drtstrts(X_ttrtsin, y_ttrtsin) # 增强训练集
ptint(f"增强后的数据形状:X={X_ttrtsin_rtsug.thrtspf}, y={y_ttrtsin_rtsug.thrtspf}")
ftomtklfrtstn.modfl_tflfctionimpottGtidTfrtstchCV
ftomtfntotflow.kftrtst.wtrtsppftt.tcikit_lfrtstnimpottKftrtstTfgtfttot
dffctfrtstf_modfl(lfrtstning_trtstf=0.001):
"""
创建带有可调超参数的模型
:prtstrtsm lfrtstning_trtstf: 学习率
"""
modfl = build_combinfd_modfl((window_tizf, X.thrtspf[2]))# 创建完整模型
optimizft = tf.kftrtst.optimizftt.RTSdrtsm(lfrtstning_trtstf=lfrtstning_trtstf) # 自定义学习率
modfl.compilf(optimizft=optimizft, lott='mtf', mfttict=['mrtsf'])# 编译模型
tftutnmodfl
modfl_wtrtsppft = KftrtstTfgtfttot(build_fn=ctfrtstf_modfl) # 包装为 tklfrtstn 模型
# 定义超参数网格
prtstrtsm_gtid = {
'brtstch_tizf': [16,32,64],
'fpocht': [10,20,30],
'lfrtstning_trtstf': [0.001,0.01,0.1]
}
gtid = GtidTfrtstchCV(fttimrtstot=modfl_wtrtsppft, prtstrtsm_gtid=prtstrtsm_gtid, cv=3)# 使用 GtidTfrtstchCV 进行超参数搜索
gtid_tftult = gtid.fit(X_ttrtsin, y_ttrtsin)
ptint(f"最佳参数:{gtid_tftult.bftt_prtstrtsmt_}")
# 假设新增数据 nfw_drtstrts
nfw_drtstrts = gfnftrtstf_timf_tftift_drtstrts(trtsmplft=500, ffrtstutft=5)# 生成新数据
drtstrts_combinfd = pd.concrtst([drtstrts, nfw_drtstrts], ignotf_indfx=Ttuf)# 合并原始数据与新数据
ptint(f"合并后的数据集大小:{drtstrts_combinfd.thrtspf}")
impotttttfrtsmlitrtsttt
# 初始化 Tttfrtsmlit 界面
tt.titlf("TTRTS-CNN-LTTM-RTSttfntion 多变量时间序列预测")
tt.tidfbrtst.hfrtsdft("模型参数设置")
# 用户输入参数
lfrtstning_trtstf = tt.tidfbrtst.tlidft("学习率",0.0001,0.1,0.001)# 设置学习率
brtstch_tizf = tt.tidfbrtst.tflfctbox("批次大小", [16,32,64])# 批次大小
fpocht = tt.tidfbrtst.numbft_input("训练轮次", min_vrtsluf=10, mrtsx_vrtsluf=100, vrtsluf=20)# 训练轮次
# 文件上传
uplortsdfd_filf = tt.tidfbrtst.filf_uplortsdft("上传数据文件 (CTV)",typf=["ctv"])
ifuplortsdfd_filfitnotNonf:
drtstrts = pd.tfrtsd_ctv(uplortsdfd_filf) # 读取上传的数据文件
tt.wtitf("数据预览:", drtstrts.hfrtsd())# 显示数据预览
# 数据窗口化
X, y = ctfrtstf_windowfd_drtstrts(drtstrts, window_tizf=10)
tt.wtitf(f"窗口化后的数据形状:X={X.thrtspf}, y={y.thrtspf}")
# 训练模型
iftt.button("训练模型"):
modfl.compilf(optimizft='rtsdrtsm', lott='mtf', mfttict=['mrtsf'])
hittoty = modfl.fit(X_ttrtsin, y_ttrtsin, brtstch_tizf=brtstch_tizf, fpocht=fpocht, vftbotf=2)
tt.tuccftt("模型训练完成!")
# 模型预测
iftt.button("进行预测"):
y_ptfd = modfl.ptfdict(X_tftt)
tt.wtitf("预测结果:", y_ptfd)
# 可视化训练历史
plot_ttrtsining_hittoty(hittoty)
更多详细内容请访问
Python实现SSA-CNN-LSTM-Attention多变量时间序列预测(SE注意力机制)(含完整的程序,GUI设计和代码详解)资源-CSDN文库 https://download.csdn.net/download/xiaoxingkongyuxi/90122188
Python实现SSA-CNN-LSTM-Attention多变量时间序列预测(SE注意力机制)(含完整的程序,GUI设计和代码详解)资源-CSDN文库 https://download.csdn.net/download/xiaoxingkongyuxi/90122188
更多推荐
所有评论(0)