PyCharm虚拟环境中导入torchmetrics报错及版本问题求助
解决torchmetrics导入错误及torchvision无法更新问题
错误原因分析
从报错栈来看,问题出在lightning_utilities检测PyTorch版本时,packaging.version模块无法解析到有效的版本字符串(返回了NoneType),根源是torchmetrics版本与当前PyTorch/torchvision版本不兼容;而torchvision无法更新大概率是pip版本过低、依赖冲突或版本匹配逻辑限制导致。
解决方案
1. 降级torchmetrics到兼容版本
新版本torchmetrics对PyTorch和torchvision的版本要求较高,先卸载现有版本再安装适配的旧版本:
pip uninstall -y torchmetrics pip install torchmetrics==1.3.2
(注:该版本适配PyTorch 2.x系列,若仍有问题可尝试1.2.1等更早版本)
2. 修复torchvision无法更新的问题
- 先升级pip到最新版本,规避版本兼容问题:
python -m pip install --upgrade pip
- 强制重装指定版本的torchvision,跳过依赖检查(解决依赖冲突导致的更新失败):
pip install torchvision==0.22.1 --force-reinstall --no-deps
- 若仍失败,先完全卸载torchvision再重新安装:
pip uninstall -y torchvision pip install torchvision==0.22.1
3. 验证修复
在PyCharm的虚拟环境中运行以下代码验证:
import torch import torchvision import torchmetrics as tm print(f"PyTorch版本: {torch.__version__}") print(f"Torchvision版本: {torchvision.__version__}") print(f"Torchmetrics导入成功")
内容的提问来源于stack exchange,提问作者Gyon
相关产品推荐
相关产品推荐

