Advertisement

Pytorch入门学习第八课——自定义层实现及异常处理

阅读量:

总说

尽管PyTorch具备自动求导的功能,但在某些情况下,部分操作并不支持求导,此时需要用户自行定义求导方式,这一过程通常被称为“扩展torch.autograd”。虽然官方文档中提供了相关示例,但内容较为基础。本文将对此进行更为详尽的阐述。

扩展 torch.autograd

复制代码
    class LinearFunction(Function):
    
    # 必须是staticmethod
    @staticmethod
    # 第一个是ctx,第二个是input,其他是可选参数。
    # ctx在这里类似self,ctx的属性可以在backward中调用。
    def forward(ctx, input, weight, bias=None):
        ctx.save_for_backward(input, weight, bias)
        output = input.mm(weight.t())
        if bias is not None:
            output += bias.unsqueeze(0).expand_as(output)
        return output
    
    
    @staticmethod
    def backwa

全部评论 (0)

还没有任何评论哟~