【问题标题】:Is there analog of theano.tensor.switch in pytorch?pytorch中是否有theano.tensor.switch的模拟?
【发布时间】:2018-09-30 14:06:03
【问题描述】:

我想强制将向量中低于某个阈值的所有元素归零。而且我想这样做,以便我仍然可以通过非零传播梯度。

例如,在 theano 中我可以这样写:

B = theano.tensor.switch(A < .1, 0, A)

pytorch 有解决方案吗?

【问题讨论】:

    标签: deep-learning theano pytorch


    【解决方案1】:

    从 pytorch 0.4+ 开始,您可以使用 torch.where 轻松完成此操作(请参阅 doc,Merged PR

    就像在 Theano 中一样简单。举个例子看看自己:

    import torch
    from torch.autograd import Variable
    
    x = Variable(torch.arange(0,4), requires_grad=True) # x     = [0 1 2 3]
    zeros = Variable(torch.zeros(*x.shape))             # zeros = [0 0 0 0]
    
    y = x**2                         # y = [0 1 4 9]
    z = torch.where(y < 5, zeros, y) # z = [0 0 0 9]
    
    # dz/dx = (dz/dy)(dy/dx) = (y < 5)(0) + (y ≥ 5)(2x) = 2x(x**2 ≥ 5) 
    z.backward(torch.Tensor([1.0])) 
    x.grad # (dz/dx) = [0 0 0 6]
    

    【讨论】:

      【解决方案2】:

      我不认为 switch 在 PyTorch 中默认实现。但是,您可以通过extending the torch.autograd.Function在 PyTorch 中定义自己的函数

      所以,开关函数看起来像

      class switchFunction(Function):
          @staticmethod
          def forward(ctx, flag, value, tensor):
              ctx.save_for_backward(flag)
              tensor[flag] = value
              return tensor
      
          @staticmethod
          def backward(ctx, grad_output):
              flag, = ctx.saved_variables
              grad_output[flag] = 0
              return grad_output
      switch = switchFunction.apply
      

      现在,您可以简单地将switch 称为switch(A &lt; 0.1, 0, A)

      编辑

      实际上有一个函数可以做到这一点。它被称为Threshold。你可以像这样使用它

      import torch.nn as nn
      m = nn.Threshold(0.1, 0)
      B = m(A)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多