自然語言中的常用的構建詞向量方法,將id化后的語料庫,映射到低維稠密的向量空間中,pytorch 中的使用如下:
import torch import torch.utils.data as Data import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable word_to_id = {'hello':0, 'world':1} embeds = nn.Embedding(2, 10) hello_idx = torch.LongTensor([word_to_id['hello']]) # hello_idx = Variable(hello_idx) hello_embed = embeds(hello_idx) print(hello_embed) if __name__ == '__main__': pass
輸出:
需要注意的幾點:
1)id化后的數據需要查表構建詞向量時,idx必須是Long型的tensor
2)查表操作embeds即可得出嵌入向量