首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有火炬的可学习LeakyReLU激活函数

问具有火炬的可学习LeakyReLU激活函数
EN

Stack Overflow用户
提问于 2021-12-13 13:08:51
回答 1查看 607关注 0票数 1

我试图为可逆可训练LeakyReLu编写一个类,在这个类中,模型在每次迭代中修改negative_slope,

代码语言:javascript
复制
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,负斜率都不会更新。还有什么我必须修改的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-13 14:20:22

您的优化器知道应该更新InvertibleLeakyReLU.negative_slope吗?

我猜是-不:

self.negative_slope不被定义为nn.Parameter,因此,默认情况下,当您用model.parameters() negative_slope初始化优化器时,并不是优化参数之一。

您可以将negative_slope定义为nn.Parameter

代码语言:javascript
复制
self.negative_slope = nn.Parameter(data=torch.tensor(negative_slope), requires_grad=True)

或者,将negative_slope从模型中的所有InvertibleLeakyReLU显式传递给优化器。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70335181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档