pytorch中嵌入的加权求和

2023-12-31

I have a sequence of 12 words which I represent using a 12x256 matrix (using word embeddings). Let us refer to these as . I wish to take this as input and output a 1x256 vector. However I don't want to use a (12x256) x 256 dense layer. Instead I want to create the output embedding using a weighted summation of the 12 embeddings

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

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


您可以通过 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 的维度上运行,并将其与可学习的权重相加。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pytorch中嵌入的加权求和 的相关文章

随机推荐