最近在使用词嵌入向量表示我的数据标签,并且在试图理解torch.nn.Embedding函数。
函数提供一个简单的查找表,输入主要为词字典的大小和词嵌入的维度两个参数,输出为对应的词嵌入向量。
torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, _weight=None, _freeze=False, device=None, dtype=None)
词字典的大小num_embeddings限制了索引大小只能从0~ num_embeddings-1。num_embeddings(int) – size of the dictionary of embeddings,就是你给nn.Embedding函数的张量里的索引个数要在0~num_embeddings-1之间;embedding_dim (int) – the size of each embedding vector也即生成的词嵌入向量的最后一个维度。For example:
import torch.nn as nn
import torch
embedding = nn.Embedding(10, 3)
input = torch.LongTensor([[1, 2, 4, 5], [4, 3, 2, 9]])
这里输入的向量input里包含的索引:1,2,3,4,5,9 均在[0,10)之间。embdding的第二个参数就决定了input的每一个数会被扩展到3维。所以最后生成的词嵌入维度如下,其中出现了两个2和两个4,因此索引出来了两个相同的词嵌入向量[-0.6431, 0.0748, 0.6969]和[ 1.4970, 1.3448, -0.9685]。
embedding(input)
tensor([[[-0.0251, -1.6902, 0.7172],
[-0.6431, 0.0748, 0.6969],
[ 1.4970, 1.3448, -0.9685],
[-0.3677, -2.7265, -0.1685]],
[[ 1.4970, 1.3448, -0.9685],
[ 0.4362, -0.4004, 0.9400],
[-0.6431, 0.0748, 0.6969],
[ 0.9124, -2.3616, 1.1151]]])