torch.nn.functional.embedding¶
- torch.nn.functional.embedding(input, weight, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False)[source][source]¶
生成一个简单的查找表,该表在固定的字典和大小中查找嵌入。
此模块通常用于使用索引检索词嵌入。模块的输入是一个索引列表和嵌入矩阵,输出是相应的词嵌入。
更多详情请见
torch.nn.Embedding
。注意
注意,此函数相对于
weight
中指定行padding_idx
的解析梯度应与数值梯度不同。注意
注意,:class:`torch.nn.Embedding`与该函数不同,它在构造时将
weight
中由padding_idx
指定的行初始化为零。- 参数:
输入(LongTensor)- 包含嵌入矩阵索引的 Tensor
weight(张量)- 行数等于最大可能索引 + 1 的嵌入矩阵,列数等于嵌入大小
padding_idx(int,可选)- 如果指定,则
padding_idx
处的条目不会对梯度产生影响;因此,在训练过程中,padding_idx
处的嵌入向量不会被更新,即它保持为固定的“填充”。max_norm(浮点数,可选)- 如果给定,则每个范数大于
max_norm
的嵌入向量将被重新归一化,使其范数为max_norm
。注意:这将就地修改weight
。norm_type (float, optional) – 计算选项
max_norm
的 p-norm 的 p。默认为2
。scale_grad_by_freq (bool, 可选) – 如果提供,则将梯度按 mini-batch 中单词的频率的倒数进行缩放。默认为
False
。sparse(布尔值,可选)- 如果
True
,则相对于weight
的梯度将是稀疏张量。有关稀疏梯度的更多详细信息,请参阅torch.nn.Embedding
下的注释。
- 返回类型:
- 形状:
输入:任意形状的 LongTensor,包含要提取的索引
重量:浮点类型嵌入矩阵,形状为(V, embedding_dim),其中 V = 最大索引 + 1,embedding_dim = 嵌入大小
输出:(*, embedding_dim),其中*是输入形状
示例:
>>> # a batch of 2 samples of 4 indices each >>> input = torch.tensor([[1, 2, 4, 5], [4, 3, 2, 9]]) >>> # an embedding matrix containing 10 tensors of size 3 >>> embedding_matrix = torch.rand(10, 3) >>> F.embedding(input, embedding_matrix) tensor([[[ 0.8490, 0.9625, 0.6753], [ 0.9666, 0.7761, 0.6108], [ 0.6246, 0.9751, 0.3618], [ 0.4161, 0.2419, 0.7383]], [[ 0.6246, 0.9751, 0.3618], [ 0.0237, 0.7794, 0.0528], [ 0.9666, 0.7761, 0.6108], [ 0.3385, 0.8612, 0.1867]]]) >>> # example with padding_idx >>> weights = torch.rand(10, 3) >>> weights[0, :].zero_() >>> embedding_matrix = weights >>> input = torch.tensor([[0, 2, 0, 5]]) >>> F.embedding(input, embedding_matrix, padding_idx=0) tensor([[[ 0.0000, 0.0000, 0.0000], [ 0.5609, 0.5384, 0.8720], [ 0.0000, 0.0000, 0.0000], [ 0.6262, 0.2438, 0.7471]]])