【问题标题】:Weighted summation of embeddings in pytorchpytorch 中嵌入的加权求和
【发布时间】:2019-10-27 04:49:53
【问题描述】:

我有一个 12 个单词的序列,我使用 12x256 矩阵(使用单词嵌入)表示。让我们将它们称为。我希望将此作为输入并输出一个 1x256 向量。但是我不想使用 (12x256) x 256 密集层。相反,我想使用 12 个嵌入的加权求和来创建输出嵌入

wi 是标量(因此存在权重共享)。

如何在 pytorch 中创建可训练的 wi?我是新手,只熟悉 nn.Linear 等标准模块。

【问题讨论】:

  • 想了想,是不是用卷积的解决方案?怎么样? conv1d 还是 conv2d?
  • 嵌入的加权总和是什么意思?嵌入点是根据它的索引获得适当的向量(就像你说的词嵌入)。您所描述的是一个简单的[words, dimensionality] 矩阵乘以[words] 大小的向量(我假设也可以是[words, dimensionality])并沿零维求和。如果这就是你想要的,你可以在自定义torch.nn.Module 的构造函数中创建wis,方法是在__init__ 内发出self.weights = torch.nn.Parameter(torch.randn(words, 1))(类似于答案描述的内容)。

标签: pytorch


【解决方案1】:

您可以通过 kernel_size = 1 的一维卷积来实现这一点

import torch

batch_size=2

inputs = torch.randn(batch_size, 12, 256)
aggregation_layer = torch.nn.Conv1d(in_channels=12, out_channels=1, kernel_size=1)
weighted_sum = aggregation_layer(inputs)

这样的卷积将有 12 个参数。在您提供的公式中,每个参数都将等于 e_i。

换句话说,这个卷积将运行大小为 256 的维度,并将其与可学习的权重相加。

【讨论】:

    【解决方案2】:

    这应该可以解决加权平均:

    from torch import nn
    import torch
    
    
    class LinearWeightedAvg(nn.Module):
        def __init__(self, n_inputs):
            super(LinearWeightedAvg, self).__init__()
            self.weights = nn.ParameterList([nn.Parameter(torch.randn(1)) for i in range(n_inputs)])
    
        def forward(self, input):
            res = 0
            for emb_idx, emb in enumerate(input):
                res += emb * self.weights[emb_idx]
            return res
    
    
    example_data = torch.rand(12, 256)
    wa_layer = LinearWeightedAvg(12)
    res = wa_layer(example_data)
    print(res.shape)  
    

    受我之前在 pytorch 论坛上收到的答案启发的答案:
    https://discuss.pytorch.org/t/dense-layer-with-different-inputs-for-each-neuron/47348

    【讨论】:

      猜你喜欢
      • 2018-11-17
      • 2019-07-22
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多