Skip to main content
 首页 » 编程设计

python之Pytorch:定义自定义函数

2024年10月01日7JustinYoung

我想自己写激活函数,但是遇到了问题。说矩阵乘法将调用.data。我进行了搜索,但几乎没有得到有用的信息。任何帮助将不胜感激。错误信息为

 Traceback (most recent call last): 
      File "defineAutogradFuncion.py", line 126, in <module> 
        test = gradcheck(argmin, input, eps=1e-6, atol=1e-4) 
      File "/home/zhaosl/.local/lib/python2.7/site-packages/torch/autograd/gradcheck.py", line 154, in gradcheck 
        output = func(*inputs) 
      File "defineAutogradFuncion.py", line 86, in forward 
        output = output.mm(dismap).squeeze(-1) 
      File "/home/zhaosl/.local/lib/python2.7/site-packages/torch/autograd/variable.py", line 578, in mm 
        output = Variable(self.data.new(self.data.size(0), matrix.data.size(1))) 
      File "/home/zhaosl/.local/lib/python2.7/site-packages/torch/tensor.py", line 374, in data 
        raise RuntimeError('cannot call .data on a torch.Tensor: did you intend to use autograd.Variable?') 
    RuntimeError: cannot call .data on a torch.Tensor: did you intend to use autograd.Variable? 
    class Softargmin(torch.autograd.Function): 
    """ 
    We can implement our own custom autograd Functions by subclassing 
    torch.autograd.Function and implementing the forward and backward passes 
    which operate on Tensors. 
    """ 
    @staticmethod 
    def forward(self, input): 
        """ 
        In the forward pass we receive a Tensor containing the input and return a 
        Tensor containing the output. You can cache arbitrary Tensors for use in the 
        backward pass using the save_for_backward method. 
        """ 
        #P = Fun.softmax(-input) 
        inputSqueeze = input.squeeze(-1) 
        P = Fun.softmax(-inputSqueeze) 
        self.save_for_backward(P) 
 
        output = P.permute(0,2,3,1) 
        dismap = torch.arange(0,output.size(-1)+1).unsqueeze(1) 
        output = output.mm(dismap).squeeze(-1) 
       return output 
    @staticmethod 
    def backward(self, grad_output): 
        """ 
        In the backward pass we receive a Tensor containing the gradient of the loss 
        with respect to the output, and we need to compute the gradient of the loss 
        with respect to the input. 
        """ 
        P, = self.saved_tensors 
        P = P.unsqueeze(-1) 
        Pk = torch.squeeze(P,-1).permute(0,2,3,1) 
        k = torch.arange(0,Pk.size(-1)+1).unsqueeze(1) 
        sumkPk = Pk.mm(k) 
        sumkPk = sumkPk.unsqueeze(1).expand(P.size()) 
        i = torch.arange(0,Pk.size(-1)+1).view(1,-1,1,1,1).expand(P.size()) 
        grad_output_expand =grad_output.unsqueeze(-1).unsqueeze(1).expand(P.size()) 
        grad_input = grad_output_expand*P*(sumkPk-i) 
        return grad_input 

请您参考如下方法:

PyTorch 中最基本的元素是 Tensor,它等同于 numpy.ndarray,唯一的区别是 Tensor可以放在 GPU 上进行任何计算。

Variable 是 Tensor 的包装器,包含三个属性:data、grad 和 grad_fn。 data 包含原始的Tensor; grad 包含某个值相对于此 Variable 的导数/梯度; grad_fn 是指向创建此 Variable 的 Function 对象的指针。 grad_fn 属性实际上是 autograd 正常工作的关键,因为 PyTorch 使用这些指针在每次迭代时构建计算图并对所有 变量执行微分 相应地在你的图表中。这不仅仅是关于通过您正在创建的自定义 Function 对象正确区分。

因此,每当您在需要微分的计算中创建一些 Tensor 时,将其包装为 Variable。首先,这将使 Tensor 能够在您调用 backward() 后保存生成的导数/梯度值。其次,这有助于autograd 构建正确的计算图。

另一件需要注意的事情是,每当您将 Variable 发送到计算图中时,使用此 Variable 计算的任何值都将自动成为 Variable。因此,您不必在计算图中手动包装所有 Tensors。

您可能想看看 this .

回到你的错误,要找出真正导致问题的原因有点困难,因为你没有显示所有代码(比如你如何在你的代码中使用这个自定义 Function 的信息)计算图),但我怀疑最有可能发生的是当 PyTorch 在您的模型上使用数值梯度检查以查看微分是否是正确的,它假设该子图中的每个节点都是一个 Variable 因为这是通过该子图进行区分所必需的,然后它尝试调用该子图的 data 属性Variable,很可能是因为该值在微分中的某处使用,并且失败是因为该节点实际上是一个 Tensor 并且没有 data 属性。