导入torchvision时出现AttributeError: module 'torch' has no attribute 'version'错误
解决导入torchvision时的
AttributeError: module 'torch' has no attribute 'version'问题 这个错误的核心原因是torch与torchvision版本不兼容——你安装的torchvision版本依赖torch.version模块,但当前torch版本过旧,没有这个属性。以下是具体解决步骤:
1. 确认当前torch版本
先运行以下代码查看你当前的torch版本:
import torch print(torch.__version__)
老版本的torch(比如1.11及更早)没有torch.version模块,无法适配新的torchvision版本。
2. 安装兼容的torch与torchvision版本
首先卸载现有版本:
pip uninstall torch torchvision -y
然后根据你的环境选择对应的安装命令:
- CPU环境:
pip install torch==2.0.0 torchvision==0.15.0 --index-url https://download.pytorch.org/whl/cpu - CUDA 11.7环境:
pip install torch==2.0.0 torchvision==0.15.0 --index-url https://download.pytorch.org/whl/cu117 - CUDA 11.8环境:
pip install torch==2.1.0 torchvision==0.16.0 --index-url https://download.pytorch.org/whl/cu118
注意:务必确保在你报错的虚拟环境(
d:\Python\CNN PyTorch\venv)中执行上述命令,避免安装到全局Python环境。
3. 验证修复结果
重新运行你的导入代码:
import torch import torch.nn as nn import torch.optim as optim import torchvision
如果没有报错,再打印版本确认兼容性:
print(f"Torch版本: {torch.__version__}") print(f"Torchvision版本: {torchvision.__version__}")
内容的提问来源于stack exchange,提问作者Mujahid Hussain
相关产品推荐
相关产品推荐

