PyTorch报错module 'torch' has no attribute 'gradient'如何解决?
PyTorch
torch.gradient AttributeError 解决方案 核心原因说明
torch.gradient 是PyTorch 1.8.0及以上版本才正式加入的官方API,低于该版本的PyTorch本身无该接口,调用必然报错。你当前环境conda list显示正在使用PyTorch 1.7.1,属于版本不匹配问题。你测试高版本仍报错,本质是安装的高版本PyTorch和你实际运行代码的环境不一致,属于多Python环境冲突。
分步解决步骤
- 第一步:验证当前运行环境的真实PyTorch版本
在你运行报错代码的同一终端/开发环境执行以下命令,确认真实版本:
如果输出低于1.8.0,说明高版本没有安装到你当前使用的环境中。python -c "import torch; print(torch.__version__)" - 第二步:卸载残留PyTorch相关包
先清空当前环境所有PyTorch相关安装包,避免多版本残留冲突:conda uninstall pytorch torchvision torchaudio pytorch-mutex -y pip uninstall torch torchvision torchaudio -y - 第三步:安装兼容的稳定版本
你提到1.9.0存在torch.gradient edge order相关bug,推荐安装无该问题且支持torch.gradient的1.8.1 CPU版本:
conda安装命令:
pip安装命令:conda install pytorch==1.8.1 torchvision==0.9.1 torchaudio==0.8.1 cpuonly -c pytorchpip install torch==1.8.1+cpu torchvision==0.9.1+cpu torchaudio==0.8.1 -f https://download.pytorch.org/whl/torch_stable.html - 第四步:功能验证
安装完成后执行以下代码验证功能正常:
正常输出为import torch test_tensor = torch.tensor([1.0, 3.0, 6.0, 10.0]) print(torch.gradient(test_tensor))(tensor([2., 2.5, 3.5, 4.]),)即代表问题解决。
内容的提问来源于stack exchange,提问作者Uwe.Schneider
相关产品推荐
相关产品推荐

