【问题标题】:Understanding pytorch autograd了解 pytorch autograd
【发布时间】:2020-05-12 10:01:00
【问题描述】:

我正在尝试了解 pytorch autograd 的工作原理。如果我有函数 y = 2x 和 z = y**2,如果我进行正态微分,我得到 x = 1 处的 dz/dx 为 8 (dz/dx = dz/dy * dy/dx = 2y*2 = 2 (2x)*2 = 8x)。或者,z = (2x)**2 = 4x^2 和 dz/dx = 8x,所以在 x = 1 时,它是 8。

如果我对 pytorch autograd 做同样的事情,我会得到 4

x = torch.ones(1,requires_grad=True)
y = 2*x
z = y**2
x.backward(z)
print(x.grad)

打印出来的

tensor([4.])

我哪里错了?

【问题讨论】:

    标签: pytorch autograd


    【解决方案1】:

    你用错了Tensor.backward。要获得您要求的结果,您应该使用

    x = torch.ones(1,requires_grad=True)
    y = 2*x
    z = y**2
    z.backward()  # <-- fixed
    print(x.grad)
    

    z.backward() 的调用会调用反向传播算法,从z 开始并返回计算图中的每个叶节点。在这种情况下,x 是唯一的叶节点。调用z.backward() 后,计算图被重置,每个叶节点的.grad 成员更新为z 相对于叶节点的梯度(在本例中为dz/dx)。

    您的原始代码中实际发生了什么?好吧,您所做的是从x 开始应用反向传播。没有参数 x.backward() 只会导致 x.grad 设置为 1,因为 dx/dx = 1。附加参数 (gradient) 实际上是应用于结果梯度的比例。在这种情况下z=4 所以你得到x.grad = z * dx/dx = 4 * 1 = 4。如果有兴趣,您可以查看this 以获取有关gradient 参数作用的更多信息。

    【讨论】:

    【解决方案2】:

    如果您对 pytorch 中的 autograd 仍有一些疑惑,请参考: 这将是基本的异或门表示

    import numpy as np
    import torch.nn.functional as F
    inputs = torch.tensor(
                    [
                        [0, 0],
                        [0, 1],
                        [1, 0],
                        [1, 1]
                    ]
                )
    outputs = torch.tensor(
                    [
                        0,
                        1,
                        1,
                        0
                    ],
            )
    weights = torch.randn(1, 2)
    weights.requires_grad = True #set it as true for gradient computation
    
    bias = torch.randn(1, requires_grad=True) #set it as true for gradient computation
    
    preds = F.linear(inputs, weights, bias) #create a basic linear model
    loss = (outputs - preds).mean()
    loss.backward()
    print(weights.grad) # this will print your weights
            
    

    【讨论】:

      猜你喜欢
      • 2018-09-06
      • 2020-05-13
      • 2018-12-05
      • 2020-01-11
      • 2017-10-27
      • 2018-05-11
      • 2020-08-25
      • 1970-01-01
      • 2019-09-17
      相关资源
      最近更新 更多