不要在 PyTorch 中包含梯度计算操作

Don't include an operation for gradient computation in PyTorch

我有一个自定义图层。让层被称为 'Gaussian'

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

以上class的使用如下:

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. 在Gaussian模块中每次操作后使用detach:

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

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

以上方法是否正确?

P.S:问题已编辑

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

如果你的模块没有任何参数,那么不会存储梯度,因为没有参数关联它。