torch.nn.Embedding


 

自然語言中的常用的構建詞向量方法,將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即可得出嵌入向量


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM