RuntimeError: one of the variables needed for gradient computation has been modified by an inplace

本文介绍了在Pytorch中遇到的RuntimeError,该错误由于在梯度计算过程中对要求导的变量进行了inplace操作。解决方法是使用torch.clone()创建新变量进行运算,以防止对原始变量的影响。通过这一修正,可以避免程序出错并确保梯度计算的正确性。
摘要由CSDN通过智能技术生成
【Pytorch】RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [32, 1470]], which is output 0 of SigmoidBackward, is at version 196; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
  • 错误原因
    经过排查,发现是把pytorch里将要求导的变量和其他的tensor变量进行运算,导致报错。pred是模型输出的预测值,在求损失函数时候我把它和自身这个tensor进行运算,发现程序运行不了。
pred[:, x, y, 0] = (pred[:, x, y, 0] * cell_size + x * cell_size) / self.img_size
  • 解决方法
    重新定义了一个变量,利用torch.clone()函数将pred赋给新定义的变量,然后之后的运算都在这个新定义的变量上进行。然后程序就没有再报错。把要求导的tensor变量和其他的tensor变量进行运算,才出现这个报错,如果只是和普通的常数变量进行运算,程序可以正常运行。
pred_tensor=pred.clone()
pred_tensor[:,x,y,0] = (pred_tensor[:,x,y,0]*cell_size + x*cell_size)/ self.img_size
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值