Deep learning Pytork中是否有NO.tensor.switch的类似物?

Deep learning Pytork中是否有NO.tensor.switch的类似物?,deep-learning,theano,pytorch,Deep Learning,Theano,Pytorch,我想强制将向量中低于某个阈值的所有元素归零。我想这样做,这样我仍然可以通过非零值传播梯度 例如,在theano中,我可以写: B=theano.tensor.switch(A

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

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

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


pytorch中是否有解决方案?

我不认为pytorch中默认实现了
开关。但是,您可以通过以下方式在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<0.1,0,A)

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

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

从pytorch 0.4+开始,您可以使用
torch轻松实现。其中
(请参阅)

这和西亚诺一样简单。用一个例子来看你自己:

导入火炬
从torch.autograd导入变量
x=变量(torch.arange(0,4),需要#grad=True)#x=[0 1 2 3]
零点=变量(火炬零点(*x.shape))#零点=[0]
y=x**2#y=[01 4 9]
z=火炬。其中(y<5,零,y)#z=[09]
#dz/dx=(dz/dy)(dy/dx)=(y<5)(0)+(y≥ 5) (2x)=2x(x**2≥ 5) 
z、 向后(火炬张量([1.0]))
x、 梯度#(dz/dx)=[06]