首页 > 解决方案 > 不要在 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 等)。

最后,我的目标是使用高斯模块进行计算,但计算不应该包含在梯度计算中。

我尝试执行以下操作:

  1. 使用了高斯前向方法上面的@torch.no_grad

  2. 在高斯模块中的每次操作后使用分离:

    x[1: _number] = x[1: _number] + (self.n * _d[1: _number]).detach()和类似的其他操作

  3. 在 forward 方法中使用 y = x.detach()。对 y 执行操作,然后 x.data = y

以上方法正确吗?

PS:问题已编辑

标签: pytorchautograd

解决方案


当有参数需要优化时,梯度计算是有意义的。

如果您的模块没有任何参数,则不会存储梯度,因为没有参数可以关联它。


推荐阅读