注意力神经机器翻译中的嵌入层

Embedding layer in neural machine translation with attention

我正试图通过此 website.

了解如何实现 seq-to-seq 模型

我的问题:nn.embedding 只是 returns 每个单词的一些 ID,所以每个单词的嵌入在整个训练过程中都是相同的吗?还是在训练的过程中发生了变化?

我的第二个问题是因为我很困惑在训练之后,nn.embedding 的输出是否是 word2vec 词嵌入之类的东西。

提前致谢

根据PyTorch docs

A simple lookup table that stores embeddings of a fixed dictionary and size.

This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings.

简而言之,nn.Embedding 将一系列词汇索引嵌入到新的嵌入 space 中。确实可以粗略理解为word2vec风格的机制。

作为一个虚拟示例,让我们创建一个嵌入层,将总共 10 个词汇作为输入(即输入数据仅包含总共 10 个唯一标记),以及 returns 嵌入的词向量在 5 维 space。换句话说,每个单词都表示为 5 维向量。虚拟数据是 3 个单词的序列,索引依次为 1、2 和 3。

>>> embedding = nn.Embedding(10, 5)
>>> embedding(torch.tensor([1, 2, 3]))
tensor([[-0.7077, -1.0708, -0.9729,  0.5726,  1.0309],
        [ 0.2056, -1.3278,  0.6368, -1.9261,  1.0972],
        [ 0.8409, -0.5524, -0.1357,  0.6838,  3.0991]],
       grad_fn=<EmbeddingBackward>)

你可以看到这三个词现在都表示为 5 维向量。我们还看到有一个grad_fn函数,也就是说这一层的权重会通过backprop来调整。这回答了您关于嵌入层是否可训练的问题:答案是肯定的。事实上,这就是嵌入的全部要点:我们期望嵌入层学习有意义的表示,king - man = queen 的著名示例是这些嵌入层可以学习的经典示例。


编辑

正如文档所述,嵌入层是从矩阵中进行的简单查找 table。你可以通过

看到这个
>>> embedding.weight
Parameter containing:
tensor([[-1.1728, -0.1023,  0.2489, -1.6098,  1.0426],
        [-0.7077, -1.0708, -0.9729,  0.5726,  1.0309],
        [ 0.2056, -1.3278,  0.6368, -1.9261,  1.0972],
        [ 0.8409, -0.5524, -0.1357,  0.6838,  3.0991],
        [-0.4569, -1.9014, -0.0758, -0.6069, -1.2985],
        [ 0.4545,  0.3246, -0.7277,  0.7236, -0.8096],
        [ 1.2569,  1.2437, -1.0229, -0.2101, -0.2963],
        [-0.3394, -0.8099,  1.4016, -0.8018,  0.0156],
        [ 0.3253, -0.1863,  0.5746, -0.0672,  0.7865],
        [ 0.0176,  0.7090, -0.7630, -0.6564,  1.5690]], requires_grad=True)

您会看到该矩阵的第一行、第二行和第三行对应于上例中 returned 的结果。换句话说,对于索引为 n 的词汇表,嵌入层将简单地“查找”其权重矩阵中的第 n 行和 return 该行向量;因此查找 table.