PyTorch加载预训练GoogLeNet报错:AttributeError问题求助
你遇到的这个AttributeError大概率是两个核心原因导致的:要么是torch和torchvision的版本不兼容/版本过低,要么是环境里存在多个Python环境,导致你调用的不是安装了最新torchvision的那个环境。下面给你一步步的解决办法:
第一步:检查并匹配torch和torchvision的版本
就算你装了最新的torchvision,如果PyTorch版本和它不兼容,也会出现这类模块找不到的问题。先打开终端输入以下命令,查看当前环境的版本情况:python -c "import torch; import torchvision; print('Torch version:', torch.__version__); print('Torchvision version:', torchvision.__version__)"确保你的torchvision版本至少在0.4.0以上(GoogLeNet从这个版本开始加入到torchvision.models中),并且和torch版本匹配(比如torch 2.0.x对应torchvision 0.15.x,torch 1.13.x对应torchvision 0.14.x)。如果版本不匹配,先卸载现有版本再重新安装对应组合:
pip uninstall torch torchvision -y # 示例:安装适配CUDA 11.7的torch+torchvision组合,可根据自己的CUDA版本调整 pip install torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 --index-url https://download.pytorch.org/whl/cu117第二步:确认你使用的是正确的Python环境
多虚拟环境混用很容易搞混依赖。你可以在运行代码的终端里输入which python(Linux/macOS)或者where python(Windows),看看当前使用的Python路径是不是你安装了最新torchvision的那个环境。如果不是,切换到对应的虚拟环境再运行代码。第三步:使用新版本torchvision的正确加载方式
从torchvision 0.13.0开始,pretrained=True参数已经被弃用,官方推荐用weights参数指定预训练权重。换成新写法不仅更规范,也能避免潜在的版本适配问题:from torchvision.models import googlenet, GoogLeNet_Weights # 加载带有预训练权重的GoogLeNet model = googlenet(weights=GoogLeNet_Weights.DEFAULT) # 如果不需要预训练权重,就写weights=None # model = googlenet(weights=None)第四步:确认没有拼写错误
虽然可能性不大,但还是检查下代码里的函数名是不是googlenet(全小写),别写成GoogLeNet或者其他拼写错误。
如果按上面的步骤操作后还是有问题,可以把版本检查命令的输出结果贴出来,方便进一步排查。
内容的提问来源于stack exchange,提问作者ice




