【问题标题】:What is the backward process of max operation in deep learning?深度学习中最大运算的逆向过程是什么?
【发布时间】:2019-05-01 12:51:23
【问题描述】:

我知道深度学习的反向过程遵循梯度下降算法。但是,max 操作从来没有梯度概念。

tensorflow、pytorch 等深度学习框架如何处理maxpooling 等“max”操作的倒数?

【问题讨论】:

    标签: python tensorflow deep-learning caffe pytorch


    【解决方案1】:

    您必须考虑max 运算符的实际作用?那就是:

    • 它返回或者说它传播了最大值。

    这正是它在这里所做的——它需要两个或更多张量并向前传播(仅)最大值。

    看一个简短的例子通常会有所帮助:

    t1 = torch.rand(10, requires_grad=True)
    t2 = torch.rand(10, requires_grad=True)
    
    
    s1 = torch.sum(t1)
    s2 = torch.sum(t2)
    print('sum t1:', s1, 'sum t2:', s2)
    m = torch.max(s1, s2)
    print('max:', m, 'requires_grad:', m.requires_grad)
    m.backward()
    print('t1 gradients:', t1.grad)
    print('t2 gradients:', t2.grad)
    

    这段代码创建了两个随机张量,将它们相加并将它们放入一个 max 函数中。然后在结果上调用backward()

    让我们来看看两种可能的结果:

    • 结果 1 - t1 的总和更大:

      sum t1: tensor(5.6345) sum t2: tensor(4.3965)
      max: tensor(5.6345) requires_grad: True
      t1 gradients: tensor([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
      t2 gradients: tensor([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
      
    • 结果 2 - t2 的总和更大:

      sum t1: tensor(3.3263) sum t2: tensor(4.0517)
      max: tensor(4.0517) requires_grad: True
      t1 gradients: tensor([ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.])
      t2 gradients: tensor([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
      

    正如您所期望的那样,s1 表示将针对t1 计算最大梯度。同样,当s2t2 的最大梯度时。

    • 与向前的步骤类似,反向传播是通过最大值向后传播。

    值得一提的是,不代表最大值的其他张量仍然是图的一部分。然后只有梯度设置为零。如果它们不是图形的一部分,您将得到 None 作为梯度,而不是零向量。

    您可以检查如果您使用 python-max 而不是 torch.max 会发生什么:

    t1 = torch.rand(10, requires_grad=True)
    t2 = torch.rand(10, requires_grad=True)
    
    
    s1 = torch.sum(t1)
    s2 = torch.sum(t2)
    print('sum t1:', s1, 'sum t2:', s2)
    m = max(s1, s2)
    print('max:', m, 'requires_grad:', m.requires_grad)
    m.backward()
    print('t1 gradients:', t1.grad)
    print('t2 gradients:', t2.grad)
    

    输出:

    sum t1: tensor(4.7661) sum t2: tensor(4.4166)
    max: tensor(4.7661) requires_grad: True
    t1 gradients: tensor([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])
    t2 gradients: None 
    

    【讨论】:

    • 很好的答案,特别是对于“其他不代表最大值的张量仍然是图表的一部分”。
    猜你喜欢
    • 2019-06-07
    • 2017-02-12
    • 2018-02-04
    • 2015-10-18
    • 2018-11-05
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    相关资源
    最近更新 更多