首页
学习
活动
专区
圈层
工具
发布

ReLU导数
EN

Stack Overflow用户
提问于 2018-09-23 09:46:42
回答 1查看 3.2K关注 0票数 0

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

( a)我理解当x< 0时,ReLU函数的导数是0,x>0时,导数是1。是那么回事吗?但是代码似乎保持x> 0部分不变,并将x<0部分设置为0。为什么会这样呢?

( b)为什么转座子,即x.T.mm(grad_h)?转位在我看来并不是必要的。我只是有点困惑。谢谢,

代码语言:javascript
复制
# -*- 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)

代码语言:javascript
复制
    # Update weights using gradient descent
    w1 -= learning_rate * grad_w1
    w2 -= learning_rate * grad_w2
EN

回答 1

Stack Overflow用户

发布于 2018-09-23 18:53:07

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

代码语言:javascript
复制
grad_h = derivative of ReLu(x) * incoming gradient

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

X矩阵的大小为64x1000,grad_h矩阵为64x100。很明显,你不能直接乘以x与grad_h,你需要采取转置x得到适当的尺寸。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52464922

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档