【问题标题】:Learnable LeakyReLU activation function with PytorchPytorch 的可学习 LeakyReLU 激活函数
【发布时间】:2022-01-16 22:57:11
【问题描述】:

我正在尝试为 Invertible trainable 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,负斜率不会更新。还有其他需要修改的地方吗?

【问题讨论】:

标签: python deep-learning pytorch tensor activation-function


【解决方案1】:

您的优化器是否知道它应该更新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)

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

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2021-01-20
    • 2021-12-14
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    相关资源
    最近更新 更多