Rit*_*hik 17 embedding pytorch
从多次搜索和pytorch文档本身,我可以发现在嵌入层内部有一个查找表,其中存储了嵌入向量。我无法理解的是:
在这方面的任何帮助将不胜感激。谢谢。
gor*_*jan 17
这真是个好问题!PyTorch 的嵌入层(Tensorflow 也是如此)用作查找表,只是为了检索每个输入的嵌入,即索引。考虑以下情况,您有一个句子,其中每个单词都被标记化。因此,句子中的每个单词都用唯一的整数(索引)表示。如果索引(单词)列表是[1, 5, 9],并且您想使用50维度向量(嵌入)对每个单词进行编码,您可以执行以下操作:
# The list of tokens
tokens = torch.tensor([0,5,9], dtype=torch.long)
# Define an embedding layer, where you know upfront that in total you
# have 10 distinct words, and you want each word to be encoded with
# a 50 dimensional vector
embedding = torch.nn.Embedding(num_embeddings=10, embedding_dim=50)
# Obtain the embeddings for each of the words in the sentence
embedded_words = embedding(tokens)
Run Code Online (Sandbox Code Playgroud)
现在,回答您的问题:
在前向传递期间,句子中每个标记的值将以与 Numpy 的索引工作类似的方式获得。因为在后端,这是一个可微分操作,在反向传递(训练)期间,Pytorch 将计算每个嵌入的梯度并相应地重新调整它们。
权重是嵌入本身。词嵌入矩阵实际上是一个权重矩阵,会在训练过程中学习到。
本身没有实际功能。正如我们上面定义的,句子已经被标记化(每个词都用一个唯一的整数表示),我们可以得到句子中每个标记的嵌入。
最后,正如我多次提到的索引示例,让我们尝试一下。
# Let us assume that we have a pre-trained embedding matrix
pretrained_embeddings = torch.rand(10, 50)
# We can initialize our embedding module from the embedding matrix
embedding = torch.nn.Embedding.from_pretrained(pretrained_embeddings)
# Some tokens
tokens = torch.tensor([1,5,9], dtype=torch.long)
# Token embeddings from the lookup table
lookup_embeddings = embedding(tokens)
# Token embeddings obtained with indexing
indexing_embeddings = pretrained_embeddings[tokens]
# Voila! They are the same
np.testing.assert_array_equal(lookup_embeddings.numpy(), indexing_embeddings.numpy())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4392 次 |
| 最近记录: |