Pytorch自定义求导:Extending torch.autograd

PyTorch通常能自动完成梯度计算,即autograd。但在涉及复杂操作的自定义损失函数中,autograd可能无法工作。为此,需要为每个操作创建一个新的Function子类以加入autograd。这包括:1) __init__(如果操作有非Variable参数,用于传递这些参数);2) forward() - 定义前向计算过程,返回Tensor;3) backward() - 计算梯度,根据forward的输出和输入数量定义相应参数。在实际应用中,可以参考相关博客文章进行实现。
摘要由CSDN通过智能技术生成

Normally, pytorch can automatically achieve the gradient computation, i.e., autograd.

However, if we define a loss function including some complex operations, the autograd mechanics don't work.

Thus, adding these operations to autograd requires implementing a new Function subclass for each operation. Recall that Function s are what autograd uses to compute the results and gradients, and encode the operation history.

It can be achieved by using “Extending torch.autograd ”:

(1)__init__ (optional) - 如果你的operation包含非Variable参数,那么就将其作为__init__的参数传入到operation中。例如:AddConstant Function加一个常数,Transpose Function需要指定哪两个维度需要交换。如果你的operation不需要额外的参数,你可以忽略__init__。

(2)forward() - 计算 op 的前向过程

  • 在执行 forward 之前,Variable 参数已经被转换成了 Tensor
  • forward 的形参可以有默认参数,默认参数可以是
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值