如何在PyTorch中计算幂函数的幂梯度?

时间:2019-06-21 21:30:39

标签: pytorch autograd

我正在尝试计算

的梯度
out = x.sign()*torch.pow(x.abs(), alpha)

关于字母。

到目前为止,我尝试了以下操作:

class Power(nn.Module):
  def __init__(self, alpha=2.):
    super(Power, self).__init__()
    self.alpha = nn.Parameter(torch.tensor(alpha))

  def forward(self, x):
    return x.sign()*torch.abs(x)**self.alpha

但该课程不断给我nan训练我的网络。我希望看到类似grad=out*torch.log(x)的内容,但无法实现。例如,此代码不返回任何内容:

alpha_rooting = Power()
x = torch.randn((1), device='cpu', dtype=torch.float)
out = (alpha_rooting(x)).sum()
out.backward()
print(out.grad)

为此,我也尝试使用autograd来运气。我应该如何解决这个问题?谢谢。

1 个答案:

答案 0 :(得分:0)

您编写的Power()类可以正常工作。实际使用方式存在问题。渐变存储在该变量的.grad中,而不是上面使用的out变量中。您可以按以下方式更改代码。

alpha_rooting = Power()
x = torch.randn((1), device='cpu', dtype=torch.float)
out = (alpha_rooting(x)).sum()

# compute gradients of all parameters with respect to out (dout/dparam)
out.backward()
# print gradient of alpha
# Note that gradients are store in .grad of parameter not out variable
print(alpha_rooting.alpha.grad)

# compare if it is approximately correct to exact grads
err = (alpha_rooting.alpha.grad - out*torch.log(x))**2 
if (err <1e-8):
    print("Gradients are correct")
相关问题