小编DaF*_*ooo的帖子

当使用 .clamp 而不是 torch.relu 时,Pytorch Autograd 会给出不同的渐变

我仍在努力理解 PyTorch autograd 系统。我正在努力解决的一件事是理解为什么.clamp(min=0)并且nn.functional.relu()似乎有不同的向后传球。

它特别令人困惑,因为它.clampreluPyTorch 教程中的等效用法相同,例如https://pytorch.org/tutorials/beginner/pytorch_with_examples.html#pytorch-nn

我在分析具有一个隐藏层和 relu 激活(输出层中的线性)的简单全连接网络的梯度时发现了这一点。

据我了解,以下代码的输出应该只是零。我希望有人能告诉我我缺少什么。

import torch
dtype = torch.float

x = torch.tensor([[3,2,1],
                  [1,0,2],
                  [4,1,2],
                  [0,0,1]], dtype=dtype)

y = torch.ones(4,4)

w1_a = torch.tensor([[1,2],
                     [0,1],
                     [4,0]], dtype=dtype, requires_grad=True)
w1_b = w1_a.clone().detach()
w1_b.requires_grad = True



w2_a = torch.tensor([[-1, 1],
                     [-2, 3]], dtype=dtype, requires_grad=True)
w2_b = w2_a.clone().detach()
w2_b.requires_grad = True


y_hat_a = torch.nn.functional.relu(x.mm(w1_a)).mm(w2_a)
y_a = torch.ones_like(y_hat_a)
y_hat_b = x.mm(w1_b).clamp(min=0).mm(w2_b)
y_b = torch.ones_like(y_hat_b)

loss_a = (y_hat_a - y_a).pow(2).sum()
loss_b …
Run Code Online (Sandbox Code Playgroud)

python backpropagation pytorch autograd relu

8
推荐指数
1
解决办法
1415
查看次数

标签 统计

autograd ×1

backpropagation ×1

python ×1

pytorch ×1

relu ×1