pytorch - 为什么我们在定义 ReLU autograd 函数时需要克隆 grad_output 并将其分配给 grad_input?

标签 pytorch backpropagation autograd

我正在浏览 pytorch 教程的 autograd 部分。我有两个问题:

  1. 为什么我们需要克隆 grad_output并将其分配给 grad_input除了反向传播期间的简单赋值之外?
  2. grad_input[input < 0] = 0 的目的是什么? ?这是否意味着当输入小于零时我们不更新梯度?

代码如下:

class MyReLU(torch.autograd.Function):
    @staticmethod
    def forward(ctx, input):
        """
        In the forward pass we receive a Tensor containing the input and return
        a Tensor containing the output. ctx is a context object that can be used
        to stash information for backward computation. You can cache arbitrary
        objects for use in the backward pass using the ctx.save_for_backward method.
        """
        ctx.save_for_backward(input)
        return input.clamp(min=0)

    @staticmethod
    def backward(ctx, grad_output):
        """
        In the backward pass we receive a Tensor containing the gradient of the loss
        with respect to the output, and we need to compute the gradient of the loss
        with respect to the input.
        """
        input, = ctx.saved_tensors
        grad_input = grad_output.clone()
        grad_input[input < 0] = 0
        return grad_input

链接在这里: https://pytorch.org/tutorials/beginner/pytorch_with_examples.html#pytorch-defining-new-autograd-functions

非常感谢。

最佳答案

Why do we need clone the grad_output and assign it to grad_input other than simple assignment during backpropagation?

tensor.clone()创建模仿原始张量 requires_grad 的张量副本 field 。 clone是一种复制张量的方法,同时仍将副本保留为它来自的计算图的一部分。

所以,grad_input是与 grad_output 相同的计算图的一部分如果我们计算 grad_output 的梯度, 然后对 grad_input 做同样的事情.

由于我们在 grad_input 中进行了更改,我们先克隆它。

What's the purpose of 'grad_input[input < 0] = 0'? Does it mean we don't update the gradient when input less than zero?

这是根据 ReLU 函数的定义完成的。 ReLU 函数是 f(x)=max(0,x) .这意味着如果 x<=0然后 f(x)=0 , 否则 f(x)=x .在第一种情况下,当 x<0 , f(x) 的导数关于 xf'(x)=0 .所以,我们执行 grad_input[input < 0] = 0 .在第二种情况下,它是 f'(x)=1 , 所以我们简单地传递 grad_outputgrad_input (就像打开的门一样工作)。

关于pytorch - 为什么我们在定义 ReLU autograd 函数时需要克隆 grad_output 并将其分配给 grad_input?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60909934/

相关文章:

python - PyTorch 中 "*"运算符在张量大小之前做什么?

deep-learning - keras 如何处理多重损失?

machine-learning - 当我需要更新多层感知器中的权重时?

python - 评估pytorch模型: `with torch.no_grad` vs `model.eval()`

pytorch - 找不到就地操作导致 "RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation:"

python-3.x - 在 pytorch 中学习之前对图像进行标准化

image - 在同一图像张量上两次使用 torchvision.utils.save_image 会使第二次保存无效。这是怎么回事?

python - 模块未找到错误 : No module named 'tools.nnwrap'

machine-learning - 输出神经元误差