我试图为可逆可训练LeakyReLu编写一个类,在这个类中,模型在每次迭代中修改negative_slope,
class InvertibleLeakyReLU(nn.Module):
def __init__(self, negative_slope):
super(InvertibleLeakyReLU, self).__init__()
self.negative_slope = torch.tensor(negative_slope, requires_grad=True)
def forward(self, input, logdet = 0, reverse = False):
if reverse == True:
input = torch.where(input>=0.0, input, input *(1/self.negative_slope))
log = - torch.where(input >= 0.0, torch.zeros_like(input), torch.ones_like(input) * math.log(self.negative_slope))
logdet = (sum(log, dim=[1, 2, 3]) +logdet).mean()
return input, logdet
else:
input = torch.where(input>=0.0, input, input *(self.negative_slope))
log = torch.where(input >= 0.0, torch.zeros_like(input), torch.ones_like(input) * math.log(self.negative_slope))
logdet = (sum(log, dim=[1, 2, 3]) +logdet).mean()
return input, logdet 不管我设置了requires_grad=True,负斜率都不会更新。还有什么我必须修改的吗?
发布于 2021-12-13 14:20:22
您的优化器知道应该更新InvertibleLeakyReLU.negative_slope吗?
我猜是-不:
self.negative_slope不被定义为nn.Parameter,因此,默认情况下,当您用model.parameters() negative_slope初始化优化器时,并不是优化参数之一。
您可以将negative_slope定义为nn.Parameter
self.negative_slope = nn.Parameter(data=torch.tensor(negative_slope), requires_grad=True)或者,将negative_slope从模型中的所有InvertibleLeakyReLU显式传递给优化器。
https://stackoverflow.com/questions/70335181
复制相似问题