首页 > 解决方案 > ReLU 的导数

问题描述

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

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

b) 为什么转置,iexTmm(grad_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())
    grad_h = grad_h_relu.clone()
    grad_h[h < 0] = 0
    grad_w1 = x.t().mm(grad_h)
    # Update weights using gradient descent
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2

标签: pytorch

解决方案


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

grad_h = derivative of ReLu(x) * incoming gradient

正如你所说,ReLu 函数的导数是 1,所以 grad_h 正好等于传入梯度。

2- x 矩阵的大小为 64x1000,grad_h 矩阵为 64x100。很明显,您不能直接将 x 与 grad_h 相乘,您需要对 x 进行转置以获得适当的尺寸。


推荐阅读