【问题标题】:Adding noise when using embedding layer in pytorch在 pytorch 中使用嵌入层时添加噪声
【发布时间】:2021-01-02 00:06:39
【问题描述】:

我正在构建一个生成器g,它接收一个潜在代码(形状为 100 的向量)并输出一个图像。具体来说,我有 1000 张 MNIST 图像,我希望网络为每个图像 x_i 学习一个潜在代码 z_i,例如 g(z_i)=x_i(这种方法称为生成潜在优化)。所以我使用了 nn.Embedding(1000,embedding_dim=100) 和标准生成器架构,它接收来自嵌入的代码并输出图像。至于损失,我将重建损失与嵌入向量权重的正则化结合起来。

我的问题是:我想在将潜在代码向量插入生成器之前为其添加噪声(以使潜在代码紧凑)。但是我是初学者,我不知道在添加噪音时是否应该调用 detach() 。我不完全确定我的方法。我不想了解噪音的规模或任何东西。 这是我的尝试:

class net(nn.Module):
  def __init__():
    self.embed = nn.Embedding(1000,embedding_dim=100)
    self.generator = nn.sequential( nn.Linear(100, 84), .... )
  def forward(batch_indices):
    batch_codes = self.embed(batch_indices)
    noise = torch.randn_like(batch_codes) * sigma
    noisy_batch_codes = batch_codes + noise # SHOULD THIS BE batch_codes.detach() + noise ??
    return self.generator(noisy_batch_codes)

g = net()
optim = SGD(g.parameters(), lr=0.01)
for epoch in range(num_epochs):
  for orig_images, orig_images_idx in trainloader:
    optim.zero_grad()
    output = g(orig_images_idx)
    reconstruction_loss = nn.MSELoss()(output, orig_images)
    embed_vector_weights = g.embed.weight[orig_images_idx]
    reg_loss = torch.norm(embed_vector_weights) * reg_coeff
    loss = reconstruction_loss + reg_loss
    loss.backward()
    optim.step()

【问题讨论】:

    标签: pytorch


    【解决方案1】:

    如果您在添加噪声之前分离,则梯度不会传播到您的编码器(在本例中为嵌入层),因此您的编码器权重将永远不会更新。因此,如果您希望编码器学习,您可能应该分离。

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 2020-06-14
      • 2011-08-16
      • 2021-11-12
      • 2020-05-09
      • 1970-01-01
      • 2014-11-01
      • 2015-02-04
      • 1970-01-01
      相关资源
      最近更新 更多