词向量--原理、word2vec、GloVe及其实现

2023-11-21 00:20

本文主要是介绍词向量--原理、word2vec、GloVe及其实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

词向量--原理、word2vec、GloVe及其实现

  • 数据集
  • word2vec
    • CBOW
    • Skip-Gram模型
    • 改进的方法
      • 层次softmax
      • 负采样
    • 代码实现
  • GloVe
  • Refenrence

这学期选了研究生的NLP课程,期间有几次homework,在此记录一下。第一次作业的题目是

Implement a word clustering method based on neural network language model.

  • Use word2vec to train distributed representations;
  • Analyze and visualize the (full or partial) result in nearest neighbors or linear structures;
  • Optional: Use GloVe to train distributed representations and do the same analysis.

数据集

NLP的数据集有很多,这里我用了text8,它是enwiki8的前100,000,000个单词。里面只包含a-z以及空格,所以不用进行什么预处理。
jupyter看一下text8的数据内容

text8 = open("./text8")
content = text8.readline()
content[:1000] 

OUTPUT

' anarchism originated as a term of abuse first used against early working class radicals including the diggers of the 
english revolution and the sans culottes of the french revolution whilst the term is still used in a pejorative way 
to describe any act that used violent means to destroy the organization of society it has also been 
taken up as a positive label by self defined anarchists the word anarchism is derived from the greek without archons ruler 
chief king anarchism as a political philosophy is the belief that rulers are unnecessary and should be abolished although there are differing interpretations of what this means anarchism also refers to related social movements 
that advocate the elimination of authoritarian institutions particularly the state the word anarchy as most anarchists use 
it does not imply chaos nihilism or anomie but rather a harmonious anti authoritarian society in place of what are 
regarded as authoritarian political structures and coercive economic instituti'

word2vec

word2vec方法出来以前,一般词向量都是one-hot形式。虽然它很简单,但是有两个缺点。一个是one-hot分裂了不同单词之间的联系;另一个就是它的表示太稀疏了。

分布式表示,也即词向量,可以解决上面这两个问题。它的基本思想是,将每个单词映射到一个向量上面。这个短的向量表示词的属性,也包含着与其他单词的关系。word2vec就是用的这个思想,它采用一个双层的神经网络进行词向量的学习。其有两个模型:CBOW(continuous bag-of-word)SG(skip-gram)

CBOW

CBOW是用上下文的单词预测中心单词:
在这里插入图片描述
考虑最简单的情况,只用一个周围词预测中心词。
在这里插入图片描述
假设单词表容量是 V V V,词向量维度是 N N N。网络输入的编码模式是one-hot向量,则其尺寸为 V × 1 V\times1 V×1。第一层与第二层的网络权重为一个 V × N V\times N V×N的矩阵:
W = ( w 11 … w 1 N ⋮ ⋱ ⋮ w V 1 … w V N ) W=\left( \begin{array}{ccc} w_{11} & \ldots & w_{1N}\\ \vdots & \ddots & \vdots\\ w_{V1} & \ldots & w_{VN}\\ \end{array} \right) W=w11wV1w1NwVN如果输入一个one-hot形式的向量 x = ( 0 , 0 , … , 1 , … , 0 ) T , x I = 0 x=\left( 0,0,\ldots,1,\ldots,0\right)^{T},x_{I}=0 x=(0,0,,1,,0)T,xI=0到模型之中,那么第一层的对应的计算公式为
h = W T x I = W ( I , ⋅ ) x I = v I h=W^Tx_I=W_{(I,\cdot)}x_I=v_I h=WTxI=W(I,)xI=vI也就是说,矩阵 W W W的第 I I I行就是对应的单词表中的第 I I I个单词。
下一层的权重是一个 N × V N\times V N×V的矩阵 W ′ = { w i j ′ } W'=\{ w_{ij}' \} W={wij}。用此矩阵可以计算最后一层的logits u j = W ′ T h j = v j ′ T h u_j=W'^Th_j=v_j^{\prime T}h uj=WThj=vjTh之后就可以用softmax来得到单词 j j j的后验表达式 y j = p ( w j ∣ w I ) = e u j ∑ k = 1 V e u k = e v j ′ T h ∑ k = 1 V e v j ′ T h y_j=p(w_j|w_I)=\frac{e^{u_j}}{\sum_{k=1}^Ve^{u_k}}=\frac{e^{v_j^{\prime T}h}}{\sum_{k=1}^Ve^{v_j^{\prime T}h}} yj=p(wjwI)=k=1Veukeuj=k=1VevjThevjTh为了训练CBOW模型,我们需要定义一个损失函数。一个最直接的想法就是采用最大似然估计来最大化上述的后验概率 max ⁡ p ( w o ∣ w I ) \max p(w_o|w_I) maxp(wowI)也就是 E o = − log ⁡ p ( w o ∣ w I ) = − log ⁡ e u o ∑ k = 1 V e u k = − u o + ∑ k = 1 V log ⁡ e u k \begin{aligned} E_o &= -\log p(w_o|w_I) \\ &= -\log \frac{e^{u_o}}{\sum_{k=1}^Ve^{u_k}} \\ &= -u_o+\sum_{k=1}^V\log e^{u_k} \end{aligned} Eo=logp(wowI)=logk=1Veukeuo=uo+k=1Vlogeuk接着我们计算后向传导。首先定义 ∂ E o ∂ u j = e u j ∑ k = 1 V e u k − t j = y j − t j \frac{\partial E_o}{\partial u_j}=\frac{e^{u_j}}{\sum_{k=1}^Ve^{u_k}}-t_j=y_j-t_j ujEo=k=1Veukeujtj=yjtj其中 t j = { 1 if  j = o 0 otherwise t_j =\left \{ \begin{array}{rl} 1 & \text{if }j=o \\ 0 & \text{otherwise} \end{array} \right. tj={10if j=ootherwise接着通过链式法则推导梯度 ∂ E o ∂ v j = ∂ E o ∂ u j ⋅ ∂ u j ∂ v j = ( y j − t j ) ⋅ h ∂ E o ∂ v I = ∑ j = 1 V ∂ E o ∂ u j ⋅ ∂ u j ∂ h j ⋅ ∂ h j ∂ v I = ∑ j = 1 V ( y j − t j ) v j ′ \begin{gathered} \frac{\partial E_o}{\partial v_j}=\frac{\partial E_o}{\partial u_j}\cdot \frac{\partial u_j}{\partial v_j}=(y_j-t_j)\cdot h \\ \frac{\partial E_o}{\partial v_I}=\sum_{j=1}^V\frac{\partial E_o}{\partial u_j}\cdot\frac{\partial u_j}{\partial h_j}\cdot\frac{\partial h_j}{\partial v_I}=\sum_{j=1}^V(y_j-t_j)v'_j \end{gathered} vjEo=ujEovjuj=(yjtj)hvIEo=j=1VujEohjujvIhj=j=1V(yjtj)vj终于将其推倒完成了。需要注意的是,真正实现的时候使用多个周边词预测中心词,此时输入向量的维度将变为 C × V C\times V C×V
在这里插入图片描述
表达式是类似的,在计算中间的 h h h向量时,用这 C C C个输入的平均值代替 h = 1 C W T ( x 1 + ⋯ + x C ) = 1 C ( v 1 + ⋯ v C ) h=\frac{1}{C}W^T(x_1+\cdots+x_C)=\frac{1}{C}(v_1+\cdots v_C) h=C1WT(x1++xC)=C1(v1+vC)损失函数变为 E = − log ⁡ p ( w o ∣ w I , 1 , ⋯ , w I , C ) = − u o + ∑ k = 1 V log ⁡ e u k = − v o ′ T + ∑ k = 1 V log ⁡ e v k h \begin{aligned} E &= -\log p(w_o|w_{I,1}, \cdots,w_{I,C}) \\ &= -u_o + \sum_{k=1}^V\log e^{u_k} \\ &= -v_o^{\prime T}+\sum_{k=1}^V\log e^{v_kh} \end{aligned} E=logp(wowI,1,,wI,C)=uo+k=1Vlogeuk=voT+k=1Vlogevkh

Skip-Gram模型

SG模型与上述的CBOW类似,唯一不同的是使用中心词预测周围词。
在这里插入图片描述
在这里插入图片描述
损失函数变为 E = − log ⁡ p ( w o , 1 , ⋯ , w o , C ∣ w I ) = − log ⁡ ( ∏ c = 1 C u j c ∑ k = 1 V e u k ) = − ∑ c = 1 C u j c + C ∑ k = 1 V log ⁡ u k \begin{aligned} E &= -\log p(w_{o,1}, \cdots,w_{o,C}|w_I) \\ &= -\log \left( \prod_{c=1}^C\frac{u_{j_c}}{\sum_{k=1}^Ve^{u_k}} \right) \\ &= -\sum_{c=1}^Cu_{j_c}+C\sum_{k=1}^V\log u_k \end{aligned} E=logp(wo,1,,wo,CwI)=log(c=1Ck=1Veukujc)=c=1Cujc+Ck=1Vloguk

改进的方法

层次softmax

层次softmax基于霍夫曼树。这使我们能够将计算一个单词的概率分解为一系列概率计算,从而使我们不必计算所有单词的昂贵归一化。
在这里插入图片描述

负采样

负采样思想是基于噪声对比估计(类似的对抗生成对抗网络)的概念,该概念坚持认为,好的模型应通过逻辑回归将伪信号与真实信号区分开。
同样,负采样目标背后的动机类似于随机梯度下降:与其考虑到我们拥有的数千个观测值,每次都改变所有权重,我们仅使用其中的 K K K个并增加计算量效率也显着提高(取决于阴性样品的数量)。
在原始论文中,作者使用会标分布选择否定词。 选择一个单词作为否定采样的概率与其频率有关,经验公式为 P ( w i ) = f ( w i ) 3 4 ∑ j = 0 n f ( w j ) 3 4 P(w_i)=\frac{f(w_i)^{\frac{3}{4}}}{\sum_{j=0}^nf(w_j)^{\frac{3}{4}}} P(wi)=j=0nf(wj)43f(wi)43

代码实现

这部分使用gensim软件包进行实现。首先导入所需包

from gensim.models import word2vec

加载语料

sentences = word2vec.Text8Corpus("./text8")

gensim提供了很友好的API,word2vec.Word2Vec()函数的原型如下所示

class gensim.models.word2vec.Word2Vec(sentences=None, corpus_file=None, size=100, alpha=0.025, window=5, 
min_count=5, max_vocab_size=None, sample=0.001, seed=1, workers=3, min_alpha=0.0001, sg=0, hs=0, negative=5, ns_exponent=0.75, cbow_mean=1, hashfxn=<built-in function hash>, iter=5, null_word=0, trim_rule=None,sorted_vocab=1, batch_words=10000, compute_loss=False, callbacks=(), max_final_vocab=None)

这里设置词向量的维度为200

model = word2vec.Word2Vec(sentences, size=200)

训练完后看一下其中某一向量

vec_king = model.wv["king"]
vec_king 

OUTPUT

array([-2.33487463e+00, -2.94242352e-01,  8.58403683e-01,  8.11171889e-01,3.38901699e-01, -2.57826972e+00, 
-1.46598172e+00,  2.26720309e+00,...
-6.03341758e-01, -2.41992116e+00, 1.58592343e+00, 
1.19147336e+00], dtype=float32)

当然也可以保存模型以及加载

model.save("./text8.model")
model1 = word2vec.Word2Vec.load('text8.model')
model1

OUTPUT

<gensim.models.word2vec.Word2Vec at 0x156967860>

词向量最有名的应用莫过于从语义角度解释词的差异

for e in model.most_similar("man"): print(e[0], e[1])

OUTPUT

woman 0.6996182203292847
girl 0.5773996710777283
boy 0.5519055128097534
creature 0.5370252728462219
person 0.5368808507919312
gentleman 0.5074084997177124
stranger 0.503169059753418
men 0.4922099709510803
evil 0.4899784326553345
mortal 0.48563891649246216

意思是说和man最接近的单词是woman,余弦相似度为0.699。
使用t-SNE算法可以对词向量进行二维投影分析:

from sklearn.decomposition import IncrementalPCA    
from sklearn.manifold import TSNE                  
import numpy as np                                 def reduce_dimensions(model):
num_dimensions = 2  vectors = [] labels = [] cnt = 0for word in model.wv.vocab:cnt += 1vectors.append(model.wv[word])labels.append(word)if cnt == 10000:breakvectors = np.asarray(vectors)labels = np.asarray(labels)vectors = np.asarray(vectors)tsne = TSNE(n_components=num_dimensions, random_state=0)vectors = tsne.fit_transform(vectors)x_vals = [v[0] for v in vectors]y_vals = [v[1] for v in vectors]return x_vals, y_vals, labelsx_vals, y_vals, labels = reduce_dimensions(model)def plot_with_matplotlib(x_vals, y_vals, labels):import matplotlib.pyplot as pltimport randomrandom.seed(0)plt.figure(figsize=(12, 12))plt.scatter(x_vals, y_vals)indices = list(range(len(labels)))selected_indices = random.sample(indices, 25)for i in selected_indices:plt.annotate(labels[i], (x_vals[i], y_vals[i]))plot_with_matplotlib(x_vals, y_vals, labels)

OUTPUT
在这里插入图片描述

GloVe

Standford的GloVe包是基于C和shell的

./demo.sh -CORPUS text8 -VECTOR_SIZE 200 -WINDOW_SIZE 5

OUTPUT

mkdir -p build$ build/vocab_count -min-count 5 -verbose 2 < text8 > vocab.txt
BUILDING VOCABULARY
Processed 17005207 tokens.
Counted 253854 unique words.
Truncating vocabulary at min count 5.
Using vocabulary of size 71290....
TRAINING MODEL
Read 60666468 lines.
Initializing parameters...Using random seed 1591149439
done.
vector size: 50
vocab size: 71290
x_max: 10.000000
alpha: 0.750000
06/03/20 - 11:10.10AM, iter: 001, cost: 0.071225
06/03/20 - 11:10.19AM, iter: 002, cost: 0.052664
06/03/20 - 11:10.28AM, iter: 003, cost: 0.046694
...
06/03/20 - 11:12.07AM, iter: 014, cost: 0.036438
06/03/20 - 11:12.16AM, iter: 015, cost: 0.036235

训练好的模型可以用gensim加载

from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectorsglove_file = './glove/vectors.txt'
tmp_file = './glove2word2vector.txt'from gensim.scripts.glove2word2vec import glove2word2vec
glove2word2vec(glove_file, tmp_file)model = KeyedVectors.load_word2vec_format(tmp_file)
for e in model.most_similar("man"): print(e[0], e[1])

OUTPUT

woman 0.8029251098632812
girl 0.7217116355895996
my 0.714549720287323
thing 0.6998955011367798
love 0.6971036791801453
said 0.6951542496681213
young 0.6937921047210693
who 0.6918587684631348
she 0.690385639667511
story 0.688470721244812

可以看到和word2vec相比,GloVe对词向量的计算似乎更好一些。

Refenrence

[1] https://zhuanlan.zhihu.com/p/50125315
[2] https://blog.csdn.net/qq_41664845/article/details/82971728
[3] https://zhuanlan.zhihu.com/p/136247620
[4] https://ruder.io/word-embeddings-softmax/index.html#hierarchicalsoftmax
[5] https://www.youtube.com/watch?v=B95LTf2rVWM
[6] https://towardsdatascience.com/hierarchical-softmax-and-negative-sampling-short-notes-worth-telling-2672010dbe08
[7]https://radimrehurek.com/gensim/auto_examples/tutorials/run_word2vec.html#sphx-glr-auto-examples-tutorials-run-word2vec-py
[8] https://blog.csdn.net/hustqb/article/details/78144384
[9]https://radimrehurek.com/gensim/auto_examples/tutorials/run_word2vec.html#sphx-glr-auto-examples-tutorials-run-word2vec-py
[10] https://zhuanlan.zhihu.com/p/31023929

这篇关于词向量--原理、word2vec、GloVe及其实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/398493

相关文章

Spring Boot循环依赖原理、解决方案与最佳实践(全解析)

《SpringBoot循环依赖原理、解决方案与最佳实践(全解析)》循环依赖指两个或多个Bean相互直接或间接引用,形成闭环依赖关系,:本文主要介绍SpringBoot循环依赖原理、解决方案与最... 目录一、循环依赖的本质与危害1.1 什么是循环依赖?1.2 核心危害二、Spring的三级缓存机制2.1 三

pytorch自动求梯度autograd的实现

《pytorch自动求梯度autograd的实现》autograd是一个自动微分引擎,它可以自动计算张量的梯度,本文主要介绍了pytorch自动求梯度autograd的实现,具有一定的参考价值,感兴趣... autograd是pytorch构建神经网络的核心。在 PyTorch 中,结合以下代码例子,当你

C#中async await异步关键字用法和异步的底层原理全解析

《C#中asyncawait异步关键字用法和异步的底层原理全解析》:本文主要介绍C#中asyncawait异步关键字用法和异步的底层原理全解析,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录C#异步编程一、异步编程基础二、异步方法的工作原理三、代码示例四、编译后的底层实现五、总结C#异步编程

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

JS+HTML实现在线图片水印添加工具

《JS+HTML实现在线图片水印添加工具》在社交媒体和内容创作日益频繁的今天,如何保护原创内容、展示品牌身份成了一个不得不面对的问题,本文将实现一个完全基于HTML+CSS构建的现代化图片水印在线工具... 目录概述功能亮点使用方法技术解析延伸思考运行效果项目源码下载总结概述在社交媒体和内容创作日益频繁的

openCV中KNN算法的实现

《openCV中KNN算法的实现》KNN算法是一种简单且常用的分类算法,本文主要介绍了openCV中KNN算法的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录KNN算法流程使用OpenCV实现KNNOpenCV 是一个开源的跨平台计算机视觉库,它提供了各

OpenCV图像形态学的实现

《OpenCV图像形态学的实现》本文主要介绍了OpenCV图像形态学的实现,包括腐蚀、膨胀、开运算、闭运算、梯度运算、顶帽运算和黑帽运算,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起... 目录一、图像形态学简介二、腐蚀(Erosion)1. 原理2. OpenCV 实现三、膨胀China编程(

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

使用Python实现全能手机虚拟键盘的示例代码

《使用Python实现全能手机虚拟键盘的示例代码》在数字化办公时代,你是否遇到过这样的场景:会议室投影电脑突然键盘失灵、躺在沙发上想远程控制书房电脑、或者需要给长辈远程协助操作?今天我要分享的Pyth... 目录一、项目概述:不止于键盘的远程控制方案1.1 创新价值1.2 技术栈全景二、需求实现步骤一、需求