torch 自定义操作层, 前向和反向过程
在torch中定义正向一定要注意是否使用Variable
比如,在定义层的forward中
正确定义是这样的:
def forward(self, infeature):
infeature = infeature.reshape(self.inshape[1], self.inshape[2]) / self.p_pixel_num
infeature = torch.mm(infeature, self.pooling).reshape(self.outshape)
return infeature
错误定义如下:
def forward(self, feature):
infeature = infeature.reshape(self.inshape[1], self.inshape[2]) / self.p_pixel_num
infeature = torch.mm(infeature, self.pooling).reshape(self.outshape)
outfinfeature= Variable(infeature)
return outf
使用错误定义会导致梯度传播时,梯度数据为None,且之后的所有梯度为None
原因是添加了Variable,导致梯度不能传播。、
在反向计算中,如果在正向中全部使用的是torch接口,则不需要自己写反向过程。
如果在正向使用自定义操作, 则需要自定义反向过程。具体反向过程定义和正向定义类似。
如有其他相关问题: