我正在阅读字嵌入上的py手电文档。
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(5)
word_to_ix = {"hello": 0, "world": 1, "how":2, "are":3, "you":4}
embeds = nn.Embedding(2, 5) # 2 words in vocab, 5 dimensional embeddings
lookup_tensor = torch.tensor(word_to_ix["hello"], dtype=torch.long)
hello_embed = embeds(lookup_tensor)
print(hello_embed)输出:
tensor([-0.4868, -0.6038, -0.5581, 0.6675, -0.1974])这看起来不错,但是如果我将lookup_tensor行替换为
lookup_tensor = torch.tensor(word_to_ix["how"], dtype=torch.long)我得到的错误是:
RuntimeError: index out of range at /Users/soumith/minicondabuild3/conda-bld/pytorch_1524590658547/work/aten/src/TH/generic/THTensorMath.c:343
我不明白它为什么会给RunTime在hello_embed = embeds(lookup_tensor)上的错误。
发布于 2018-07-22 15:38:57
当您声明embeds = nn.Embedding(2, 5)时,词汇表大小为2,嵌入大小为5。也就是说,每个单词都将由大小为5的向量表示,而词汇表中只有2个单词。
lookup_tensor = torch.tensor(word_to_ix["how"], dtype=torch.long)嵌入将尝试查找与拼写中的第三个单词对应的向量,但是嵌入的词汇量为2,这就是为什么会出现错误。
如果您声明embeds = nn.Embedding(5, 5),它应该可以正常工作。
https://stackoverflow.com/questions/51456059
复制相似问题