词向量--原理、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

相关文章

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

在Linux中改变echo输出颜色的实现方法

《在Linux中改变echo输出颜色的实现方法》在Linux系统的命令行环境下,为了使输出信息更加清晰、突出,便于用户快速识别和区分不同类型的信息,常常需要改变echo命令的输出颜色,所以本文给大家介... 目python录在linux中改变echo输出颜色的方法技术背景实现步骤使用ANSI转义码使用tpu

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

golang版本升级如何实现

《golang版本升级如何实现》:本文主要介绍golang版本升级如何实现问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录golanwww.chinasem.cng版本升级linux上golang版本升级删除golang旧版本安装golang最新版本总结gola

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Mysql实现范围分区表(新增、删除、重组、查看)

《Mysql实现范围分区表(新增、删除、重组、查看)》MySQL分区表的四种类型(范围、哈希、列表、键值),主要介绍了范围分区的创建、查询、添加、删除及重组织操作,具有一定的参考价值,感兴趣的可以了解... 目录一、mysql分区表分类二、范围分区(Range Partitioning1、新建分区表:2、分

MySQL 定时新增分区的实现示例

《MySQL定时新增分区的实现示例》本文主要介绍了通过存储过程和定时任务实现MySQL分区的自动创建,解决大数据量下手动维护的繁琐问题,具有一定的参考价值,感兴趣的可以了解一下... mysql创建好分区之后,有时候会需要自动创建分区。比如,一些表数据量非常大,有些数据是热点数据,按照日期分区MululbU