把手写笔记搬上来,以后就用博客进行学习记录了,加油!
word2vec 总结
1、两种方式:CBOW(context(w) --->w), skip-gram(w--->context(w))
但其实这两个的区别只是CBOW中的center word作为context的mean,梯度下降法更新center word后,再以同尺度、同时更新所有context words;而skip-gram则由于center word不用context的mean进行初始化,因此,使用梯度下降更新center word对应更新不同context words的尺度也是不同的;
2、由于样本量太大,文本词量太大,如果每一次参数更新都使用全量样本进行计算,则计算量太大,于是产生两种减少计算量的运算方法:层级softmax, negative-sampling
(1)层级softmax需要现根据样本,以样本中单词词频为依据构建一颗哈夫曼树,词频越高离根节点越近,其中每个节点都对应一个参数,根据这个参数进行二元分类(左or右),因此每个词在这棵树中都可从根节点经由n个中间节点到达,即经过n次二分类可得,并且越常见的单词,词频越高,离根节点越近,则二分类次数越少,计算量越小,从而可从整体上减少总文本的计算量
但由于需要构建哈夫曼树,当样本量非常大时,同样非常耗时,所以比较是和样本量也就是单词量较少的文本
(2)negative-sampling则是通过在现有样本中再抽样,从而减小计算量,这个可以有效减少计算量,适合大样本量
根据Distributed Representations of Words and Phrases and their Compositionality论文中的词向量训练方法(即skip-gram&negative-sampling)
损失函数采用NCE(噪声对比估计)loss
复现论文代码如下:
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch
import random
import numpy as np
import scipy
import sklearn
import os
from collections import Counter
from torch.nn.parameter import Parameter
# In[2]:
random.seed(53113)
np.random.seed(53113)
torch.manual_seed(53113)
# In[3]:
K = 100 #neg_samples_num
C=3 #context_window
embedding_size = 100
learning_rate = 0.2
epoch = 2
max_vocab_size = 30000
batch_size = 128
# In[4]:
#text8英文文本
with open(os.path.join(os.path.abspath('..')+'\\text8.train.txt'),'r') as file:
text = file.read()
text_list = text.lower().split()
#print(text_list[:10])
##!!!nuk的数目要用所有词的总词数减去常用词总词