在深度学习模型中,Embedding层在代码层面上的意义是:一个保存了固定字典和大小的简单查找表。这个模块常用来保存词嵌入和用下标检索它们。模块的输入是一个下标的列表,输出是对应的词嵌入。
当输入是一个batch时,则这个输入矩阵是一个N维矩阵([batch_size,Seq_len]),输出矩阵([batch_size,Seq_len,embed_size])
PyTorch:
import torch
from torch import nn
from torch.autograd import Variable
embeds = nn.Embedding(20,5)
word_to_ix = {}
for i in range(20):
word_to_ix[i] = i+1
hello_idx = torch.LongTensor([[3,6],[8,9]])
hello_idx = Variable(hello_idx)
embeds(hello_idx)
tensor([[[-0.7695, 0.1445, -0.7704, -0.6968, 0.1774],
[-0.5415, 0.2232, -0.3729, 1.5091, 1.5055]],
[[ 0.2723, 0.5890, 0.3809, 2.1650, 1.0792],
[ 0.6174, 0.3788, 1.3872, 0.4625, 0.4803]]],
grad_fn=<EmbeddingBackward>)
hello_idx = torch.LongTensor([[2,4]])
hello_idx = Variable(hello_idx)
embeds(hello_idx)
tensor([[[-0.7695, 0.1445, -0.7704, -0.6968, 0.1774],
[-0.5415, 0.2232, -0.3729, 1.5091, 1.5055]]],
grad_fn=<EmbeddingBackward>)
TensorFlow:
tf.nn.embedding_lookup()就是根据input_ids中的id,寻找embeddings中的第id行。比如input_ids=[1,3,5],则找出embeddings中第1,3,5行,组成一个tensor返回。
embedded_words = tf.nn.embedding_lookup(embedding_w, self.inputs)