pytorch - 不要在 PyTorch 中包含梯度计算操作
问题描述
我有一个自定义图层。让层被称为“高斯”
class Gaussian(nn.Module):
def __init__():
super(Gaussian, self).__init__()
#@torch.no_grad
def forward(self, x):
_r = np.random.randint(0, x.shape[0], x.shape[0])
_sample = x[_r]
_d = (_sample - x)
_number = int(self.k * x.shape[0])
x[1: _number] = x[1: _number] + (self.n * _d[1: _number]).detach()
return x
上面的类将按如下方式使用:
cnn_model = nn.Sequential(nn.Conv2d(1, 32, 5), Gaussian(), nn.ReLU(), nn.Conv2d(32, 32, 5))
如果x
是输入,我希望梯度x
排除高斯模块中存在的操作,但包括神经网络其他层中的计算(nn.Conv2d 等)。
最后,我的目标是使用高斯模块进行计算,但计算不应该包含在梯度计算中。
我尝试执行以下操作:
使用了高斯前向方法上面的@torch.no_grad
在高斯模块中的每次操作后使用分离:
x[1: _number] = x[1: _number] + (self.n * _d[1: _number]).detach()
和类似的其他操作在 forward 方法中使用 y = x.detach()。对 y 执行操作,然后 x.data = y
以上方法正确吗?
PS:问题已编辑
解决方案
当有参数需要优化时,梯度计算是有意义的。
如果您的模块没有任何参数,则不会存储梯度,因为没有参数可以关联它。
推荐阅读
- python - VS Code 中的 Python genfromtxt 找不到 txt
- xcode - 如何修复错误读取“node_modules/react-native/ReactCommon/yoga/yoga/log.cpp”React Native
- google-chrome - Google 表单时间字段在某些移动设备上不显示 AM/PM
- java - JPA findAllById 返回 ID 顺序。我可以在没有 ID 订单的情况下获取数据吗?
- r - XML 内容似乎不是 XML:'eae-5f67afd5c3dc'
- r - 为什么 mutate_at 会产生错误的估计?
- python - 递归函数是否正确使用
- flutter - 如何仅在 TableWidget 的 colmun 中设置 backgroundColor?
- amazon-web-services - 如何使用 IAM 角色通过 AWS CLI 运行 aws-nuke
- javascript - 基于数组的对象(Javascript)