PyTorch 词向量(Word Embedding)

主要介绍了解著名的词向量(Word Embedding)模型−word2vec。采用Word2vec模型,利用相关模型组生成词向量(Word Embedding)入。Word2vec模型采用纯c语言实现,并手动计算梯度。下面的步骤解释了PyTorch中word2vec模型的实现。

1、导入模块

如下所述,实现词向量(Word Embedding)中的库:

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

2、SkipGramModel函数

word2vec类实现词向量(Word Embedding)的SkipGramModel。它包括emb_size,emb_dimension, u_embedding, v_embedding类型的属性。

class SkipGramModel(nn.Module):
   def __init__(self, emb_size, emb_dimension):
      super(SkipGramModel, self).__init__()
      self.emb_size = emb_size
      self.emb_dimension = emb_dimension
      self.u_embeddings = nn.Embedding(emb_size, emb_dimension, sparse=True)
      self.v_embeddings = nn.Embedding(emb_size, emb_dimension, sparse = True)
      self.init_emb()
   def init_emb(self):
      initrange = 0.5 / self.emb_dimension
      self.u_embeddings.weight.data.uniform_(-initrange, initrange)
      self.v_embeddings.weight.data.uniform_(-0, 0)
   def forward(self, pos_u, pos_v, neg_v):
      emb_u = self.u_embeddings(pos_u)
      emb_v = self.v_embeddings(pos_v)
      score = torch.mul(emb_u, emb_v).squeeze()
      score = torch.sum(score, dim = 1)
      score = F.logsigmoid(score)
      neg_emb_v = self.v_embeddings(neg_v)
      neg_score = torch.bmm(neg_emb_v, emb_u.unsqueeze(2)).squeeze()
      neg_score = F.logsigmoid(-1 * neg_score)
      return -1 * (torch.sum(score)+torch.sum(neg_score))
   def save_embedding(self, id2word, file_name, use_cuda):
      if use_cuda:
         embedding = self.u_embeddings.weight.cpu().data.numpy()
      else:
         embedding = self.u_embeddings.weight.data.numpy()
      fout = open(file_name, 'w')
      fout.write('%d %d\n' % (len(id2word), self.emb_dimension))
      for wid, w in id2word.items():
         e = embedding[wid]
         e = ' '.join(map(lambda x: str(x), e))
         fout.write('%s %s\n' % (w, e))
def test():
   model = SkipGramModel(100, 100)
   id2word = dict()
   for i in range(100):
      id2word[i] = str(i)
   model.save_embedding(id2word)         

3、执行

实现了使词向量模型以正确的方式显示的主要方法。

if __name__  ==  '__main__':
   test()
推荐阅读
cjavapy编程之路首页