2018年10月11日 星期四

Pytorch 實作 word embedding : 運用 nn.Embedding()


Pytorch 產生 word embedding : 運用 nn.Embedding()

用法


torch.nn.Embedding(num_embeddingsembedding_dimpadding_idx=Nonemax_norm=Nonenorm_type=2scale_grad_by_freq=Falsesparse=False_weight=None)


num_embeddings (int) : embeddings 字典裡面有多少個詞
embedding_dim (int) : 產生的 embedding vector 要有多少維度?  --> 這個要自己決定

其他細節參數看這裡


範例


import torch
import torch.nn as nn 
from torch.autograd import Variable 

# embedding 字典
word_dict = {'hello': 0, 'paul': 1, 'chao': 2} #三個詞,三個相對 tensors 數值

embeds = nn.Embedding(3, 10) #三個詞(tensors數值),設十維

#從 dictionary 產生 tensor 數值
paul_idx = torch.LongTensor([word_dict['paul']]) 
print(paul_idx) 

#產生變數
paul_idx = Variable(paul_idx) 
print(paul_idx) 

#進行 embedding
paul_embed = embeds(paul_idx) 
print(paul_embed)



結果


tensor([2])
tensor([2])
tensor([[ 1.3302,  0.4645,  0.5615, -0.0327,  1.5131, -1.9684, -0.8720, -0.5227, 1.2371,  0.6098]], grad_fn=)

最後便產生了一個十維的 word embedding 可供運用



沒有留言:

張貼留言