PyG时间序列分析实战:用torch_geometric_temporal搭建你的第一个动态图预测模型

张开发
2026/4/18 10:33:54 15 分钟阅读

分享文章

PyG时间序列分析实战:用torch_geometric_temporal搭建你的第一个动态图预测模型
PyG时间序列分析实战用torch_geometric_temporal搭建你的第一个动态图预测模型在交通流量预测、社交网络演化分析、流行病传播模拟等场景中图结构数据往往随时间动态变化。传统图神经网络GNN难以捕捉这种时序依赖关系而**时间图神经网络Temporal GNN**正是为解决这一问题而生。作为PyTorch GeometricPyG的时序扩展库torch_geometric_temporal将动态图建模与深度学习无缝结合让研究者能快速构建端到端的时空预测模型。本文将带你在30分钟内完成从环境配置到第一个预测模型跑通的全流程。我们选择流感传播数据集作为示例其节点代表地区边表示人口流动节点特征包含每周流感病例数——这与现实中的疫情预测场景高度吻合。通过这个实战案例你将掌握如何规避依赖冲突完成torch_geometric_temporal的稳定安装动态图数据的加载与预处理技巧构建一个基础的T-GNN模型预测未来病例趋势可视化模型预测结果并与真实数据对比1. 环境配置避开90%用户会遇到的安装陷阱1.1 版本对齐安装前的关键检查PyG生态对版本一致性要求极高以下是必须验证的环境信息以Windows为例import torch print(fPyTorch版本: {torch.__version__}) print(fCUDA可用性: {torch.cuda.is_available()}) print(fCUDA版本: {torch.version.cuda}) if torch.cuda.is_available() else None输出示例PyTorch版本: 2.0.1 CUDA可用性: True CUDA版本: 11.7根据输出结果需严格匹配以下组件版本组件版本规则示例PyTorch主版本一致2.0.xCUDA完全匹配11.7Python3.7-3.103.9注意若使用GPUPyTorch、CUDA、显卡驱动三者版本必须兼容。可通过NVIDIA文档查询支持矩阵。1.2 分步安装依赖项精准控制步骤1下载预编译的PyG依赖包。访问pytorch-geometric.com/whl根据你的环境下载以下四个核心组件torch_cluster-{version}{pt_tag}-{python_tag}-{platform}.whl torch_scatter-{version}{pt_tag}-{python_tag}-{platform}.whl torch_sparse-{version}{pt_tag}-{python_tag}-{platform}.whl torch_spline_conv-{version}{pt_tag}-{python_tag}-{platform}.whl其中{pt_tag}如pt20表示PyTorch 2.0{python_tag}如cp39表示Python 3.9{platform}如win_amd64表示Windows 64位步骤2按顺序安装依赖项。假设文件保存在D:\pyg_depspip install D:\pyg_deps\torch_cluster-*.whl pip install D:\pyg_deps\torch_scatter-*.whl pip install D:\pyg_deps\torch_sparse-*.whl pip install D:\pyg_deps\torch_spline_conv-*.whl步骤3安装主库建议使用清华源加速pip install torch_geometric_temporal -i https://pypi.tuna.tsinghua.edu.cn/simple1.3 验证安装快速健康检查运行以下代码确认关键功能可用from torch_geometric_temporal import temporal_signal_split print(时空数据分割模块加载成功)若未报错恭喜你已成功搭建T-GNN开发环境。接下来让我们进入实战环节。2. 动态图数据加载以流感传播数据集为例2.1 数据集特性解析torch_geometric_temporal内置多个经典动态图数据集。我们使用EnglandCovidDataset其包含节点英格兰129个地区边基于人口流动的加权连接节点特征每周新增流感病例数标准化处理时间步连续45周的观测数据数据加载代码如下from torch_geometric_temporal.dataset import EnglandCovidDataset dataset EnglandCovidDataset() print(f时间步数量: {len(dataset)}) print(f节点数: {dataset[0].num_nodes}) print(f边数: {dataset[0].num_edges})输出示例时间步数量: 45 节点数: 129 边数: 4142.2 数据预处理流水线动态图数据需要特殊处理以适应模型输入时序分割按7:3划分训练集和测试集from torch_geometric_temporal.signal import temporal_signal_split train_data, test_data temporal_signal_split(dataset, train_ratio0.7)特征工程可选添加移动平均特征平滑噪声对节点度进行对数变换标准化边权重数据增强import torch from torch_geometric_temporal import DynamicGraphTemporalSignal class DataAugmenter: def __init__(self, noise_std0.01): self.noise_std noise_std def __call__(self, snapshot): x snapshot.x torch.randn_like(snapshot.x) * self.noise_std edge_attr snapshot.edge_attr * (1 torch.randn(1) * 0.05) return snapshot.__class__( xx, edge_indexsnapshot.edge_index, edge_attredge_attr ) augmented_train [DataAugmenter()(snap) for snap in train_data]3. 构建T-GNN模型DyGrEncoder实战3.1 模型架构设计我们实现一个基于**动态图编码器DyGrEncoder**的预测模型其核心组件包括空间编码器GCN处理图结构时序编码器LSTM捕捉时间依赖解码器MLP输出预测结果import torch.nn as nn from torch_geometric_temporal.nn.recurrent import DyGrEncoder class TGNNPredictor(nn.Module): def __init__(self, node_features, hidden_dim, output_dim): super().__init__() self.encoder DyGrEncoder( in_channelsnode_features, out_channelshidden_dim, conv_layers2, num_layers1 ) self.decoder nn.Sequential( nn.Linear(hidden_dim, hidden_dim//2), nn.ReLU(), nn.Linear(hidden_dim//2, output_dim) ) def forward(self, x, edge_index, edge_weight, h, c): h, c self.encoder(x, edge_index, edge_weight, h, c) out self.decoder(h) return out, h, c3.2 训练流程优化采用**滚动预测Rolling Forecast**策略每个时间步用当前预测作为下一时间步的输入def train(model, data, epochs100): optimizer torch.optim.Adam(model.parameters(), lr0.01) criterion nn.MSELoss() # 初始化隐状态 h, c None, None losses [] for epoch in range(epochs): epoch_loss 0 for time, snapshot in enumerate(data): # 前向传播 pred, h, c model( snapshot.x, snapshot.edge_index, snapshot.edge_attr, h, c ) # 计算损失预测下一时间步 loss criterion(pred, data[time1].x if time1 len(data) else pred) # 反向传播 optimizer.zero_grad() loss.backward(retain_graphTrue) optimizer.step() epoch_loss loss.item() losses.append(epoch_loss / len(data)) print(fEpoch {epoch1}, Loss: {losses[-1]:.4f}) return losses3.3 关键技巧与调参隐状态初始化h torch.zeros(model.encoder.num_layers, data[0].num_nodes, hidden_dim) c torch.zeros_like(h)学习率调度scheduler torch.optim.lr_scheduler.ReduceLROnPlateau( optimizer, modemin, factor0.5, patience5 )梯度裁剪torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm1.0)4. 结果分析与可视化4.1 预测性能评估使用以下指标量化模型表现指标公式说明MAE$\frac{1}{n}\sum|y-\hat{y}|$平均绝对误差RMSE$\sqrt{\frac{1}{n}\sum(y-\hat{y})^2}$均方根误差MAPE$\frac{100%}{n}\sum\left|\frac{y-\hat{y}}{y}\right|$平均百分比误差实现代码def evaluate(model, test_data): model.eval() predictions, truths [], [] h, c None, None with torch.no_grad(): for time, snapshot in enumerate(test_data[:-1]): pred, h, c model( snapshot.x, snapshot.edge_index, snapshot.edge_attr, h, c ) predictions.append(pred) truths.append(test_data[time1].x) predictions torch.cat(predictions) truths torch.cat(truths) mae torch.abs(predictions - truths).mean() rmse torch.sqrt(torch.mean((predictions - truths)**2)) mape 100 * torch.abs((predictions - truths) / truths).mean() return mae, rmse, mape4.2 动态预测可视化使用matplotlib制作动态热力图直观展示疫情传播预测import matplotlib.pyplot as plt import numpy as np def plot_spread(pred, true, regions5): fig, (ax1, ax2) plt.subplots(1, 2, figsize(12, 4)) # 随机选择5个地区展示 region_idx np.random.choice(pred.shape[1], regions, replaceFalse) for idx in region_idx: ax1.plot(pred[:, idx], --, labelfRegion {idx} Pred) ax1.plot(true[:, idx], -, labelfRegion {idx} True) ax1.set_title(Case Trends Comparison) ax1.legend() # 最后一时间步的空间分布 im1 ax2.imshow(pred[-1].reshape(11, 12), cmapReds) ax2.set_title(Predicted Heatmap) plt.colorbar(im1) plt.tight_layout() plt.show()4.3 模型部署建议将训练好的模型投入实际应用时轻量化处理torch.jit.script(model).save(tgnn_flu_pred.pt)持续学习def update_model(model, new_data, epochs10): optimizer torch.optim.Adam(model.parameters(), lr0.001) for epoch in range(epochs): # 增量训练逻辑 ... return model性能监控from prometheus_client import Gauge pred_error Gauge(flu_pred_error, Prediction MAE) pred_error.set(mae.item())这套方法同样适用于交通流量预测、社交网络影响力传播等场景。我在某城市地铁客流预测项目中采用类似架构将预测误差控制在15%以内关键是要根据具体业务场景调整数据采样频率和模型的时间窗口大小。

更多文章