You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

运行pytorch_forecasting导入报错,pytorch_lightning.metrics已迁移至torchmetrics

解决pytorch_forecasting导入错误(依赖torchmetrics替代pytorch_lightning.metrics)

问题说明

运行以下导入代码时,from pytorch_forecasting.metrics import MAE, SMAPE, PoissonLoss, QuantileLoss 语句报错,原因是pytorch_forecasting内部引用了已废弃的from pytorch_lightning.metrics import Metric as LightningMetric,而pytorch_lightning.metrics已迁移至torchmetrics,且无法直接编辑pytorch_forecasting模块,安装旧版本包也引发更多问题。

导入代码:

from pytorch_forecasting import Baseline, TemporalFusionTransformer, TimeSeriesDataSet
from pytorch_forecasting.data import GroupNormalizer
from pytorch_forecasting.metrics import MAE, SMAPE, PoissonLoss, QuantileLoss
from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters

解决方案

  • 方法1:临时映射模块(无需修改原代码)
    在你的代码最开头添加以下内容,将pytorch_lightning.metrics的引用定向到torchmetrics:
import sys
from types import ModuleType

# 创建模拟pytorch_lightning.metrics的模块
pl_metrics = ModuleType("pytorch_lightning.metrics")
sys.modules["pytorch_lightning.metrics"] = pl_metrics

# 从torchmetrics导入Metric并赋值给模拟模块
from torchmetrics import Metric
pl_metrics.Metric = Metric

# 后续正常执行原导入语句
from pytorch_forecasting import Baseline, TemporalFusionTransformer, TimeSeriesDataSet
from pytorch_forecasting.data import GroupNormalizer
from pytorch_forecasting.metrics import MAE, SMAPE, PoissonLoss, QuantileLoss
from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters
  • 方法2:安装兼容版本组合
    安装已验证可解决此依赖问题的版本组合(可根据自身torch版本微调):
pip install pytorch-forecasting==0.10.3 torchmetrics==0.11.4
  • 方法3:动态patch模块引用
    使用unittest.mock临时替换模块路径:
from unittest.mock import patch

# 在导入pytorch_forecasting前patch依赖
with patch("pytorch_forecasting.metrics.base.pytorch_lightning.metrics", __import__("torchmetrics")):
    from pytorch_forecasting import Baseline, TemporalFusionTransformer, TimeSeriesDataSet
    from pytorch_forecasting.data import GroupNormalizer
    from pytorch_forecasting.metrics import MAE, SMAPE, PoissonLoss, QuantileLoss
    from pytorch_forecasting.models.temporal_fusion_transformer.tuning import optimize_hyperparameters

内容的提问来源于stack exchange,提问作者Jasper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 21:52:44