PyTorch训练报错RuntimeError:梯度计算变量被原地操作修改
问题原因及解决办法
- 你遇到的
RuntimeError是因为image -= image_mean这行代码本质上是原地操作——它等价于调用image.sub_(image_mean)(带下划线的原地方法),直接修改了输入张量image的内容。而PyTorch在反向传播时需要用到输入张量的原始值来计算梯度,一旦原始张量被原地修改,梯度计算就会失败。 - 解决方法很简单,不要直接修改输入张量,而是生成一个新的张量:
class model(nn.Module): def forward(self, image): image_mean = torch.mean(image, dim=(-3, -2, -1)) # 替换原地操作,创建新张量 image = image - image_mean return image # 别忘了返回处理后的张量
- 补充:如果计算后的
image_mean维度和image不匹配(比如取均值后是标量或低维张量),可能需要先做维度扩展避免广播问题,示例如下:
class model(nn.Module): def forward(self, image): image_mean = torch.mean(image, dim=(-3, -2, -1)) # 根据输入image的维度调整view参数,保证维度匹配 image_mean = image_mean.view(-1, 1, 1, 1) image = image - image_mean return image
内容的提问来源于stack exchange,提问作者Yaoshiang
相关产品推荐
相关产品推荐

