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

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

hdu4407(容斥原理)

题意:给一串数字1,2,......n,两个操作:1、修改第k个数字,2、查询区间[l,r]中与n互质的数之和。 解题思路:咱一看,像线段树,但是如果用线段树做,那么每个区间一定要记录所有的素因子,这样会超内存。然后我就做不来了。后来看了题解,原来是用容斥原理来做的。还记得这道题目吗?求区间[1,r]中与p互质的数的个数,如果不会的话就先去做那题吧。现在这题是求区间[l,r]中与n互质的数的和

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、