Pytorch 雷卢导数

Pytorch 雷卢导数,pytorch,Pytorch,我在学火把。这是官方教程中的第一个示例。我有两个问题,如下图所示 我知道当x0时,ReLU函数的导数为1。是这样吗?但是代码似乎保持x>0部分不变,并将x

我在学火把。这是官方教程中的第一个示例。我有两个问题,如下图所示

我知道当x<0时,ReLU函数的导数为0,当x>0时,ReLU函数的导数为1。是这样吗?但是代码似乎保持x>0部分不变,并将x<0部分设置为0。为什么呢

b为什么要转置,即x.T.mmgrad_h?我似乎不需要换位。我只是糊涂了。谢谢

# -*- coding: utf-8 -*-

import torch


dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on GPU

# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10

# Create random input and output data
x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)

# Randomly initialize weights
w1 = torch.randn(D_in, H, device=device, dtype=dtype)
w2 = torch.randn(H, D_out, device=device, dtype=dtype)

learning_rate = 1e-6
for t in range(500):
    # Forward pass: compute predicted y
    h = x.mm(w1)
    h_relu = h.clamp(min=0)
    y_pred = h_relu.mm(w2)

    # Compute and print loss
    loss = (y_pred - y).pow(2).sum().item()
    print(t, loss)

    # Backprop to compute gradients of w1 and w2 with respect to loss
    grad_y_pred = 2.0 * (y_pred - y)
    grad_w2 = h_relu.t().mm(grad_y_pred)
    grad_h_relu = grad_y_pred.mm(w2.t())

1-当x<0时,ReLU函数的导数为0,当x>0时,ReLU函数的导数为1,这是事实。但请注意,梯度是从函数的输出一直流到h。当您返回计算梯度时,它的计算公式为:

grad_h = derivative of ReLu(x) * incoming gradient
正如你们所说的,ReLu函数的导数是1,所以grad_h正好等于引入的梯度


2-x矩阵的大小为64x1000,渐变h矩阵的大小为64x100。很明显,你不能直接将x乘以grad_h,你需要对x进行转置,以获得适当的维数。

我投票将这个问题作为离题题题来结束,因为它与编程无关,与数学有关,事实上,有一些代码是次要的,正如投票结果显示的那样。
    # Update weights using gradient descent
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2
grad_h = derivative of ReLu(x) * incoming gradient