NPL之如何使用Glove--词向量转化

1. Glove 简单介绍

GloVe(Global Vectors for Word Representation)是一种“用于获取词的向量表示的无监督学习算法。” 简而言之,GloVe允许我们获取文本语料库,并将该语料库中的每个单词直观地转换为高维空间中的位置。 这意味着相似的词将被放在一起。
如果您想详细了解GloVe的工作原理,请在最后找到链接的文章。

2. 下载预训练了的Glove的Vector

访问https://nlp.stanford.edu/projects/glove/.
在Download pre-trained word vectors的下面你可以下载四种不一样的预训练数据集。
本文是使用第一个比较小的。在这里插入图片描述
你也可以直接用这个链接下载glove.6B.zip
下载后解压,里面应该有四个文件
在这里插入图片描述
我们下面的例子就用glove.6B.50d.txt文件

3. 生成wordslist.npy与wordVector.npy两个文件

  1. 加载glove.6B.50d.txt文件 --把你的文件放在一个你自己的目录下面,我是放在glove_data这个目录下面
  2. 用numpy 保存生成两个文件wordslist.npy,wordVector.npy
import numpy as np
from scipy import spatial
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE

embeddings_dict = {}

with open("./glove_data/glove.6B.50d.txt", 'r', encoding="utf-8") as f:
    for line in f:
        values = line.split()
        word = values[0]
        vector = np.asarray(values[1:], "float32")
        embeddings_dict[word] = vector
np.save('./glove_data//wordsList', np.array(list(embeddings_dict.keys())))
np.save('./glove_data//wordVectors', np.array(list(embeddings_dict.values()), dtype='float32'))

结果
在这里插入图片描述

4. Glove的使用

  1. 导入wordslist.npy,wordVector.npy
  2. 用wordslist查询baseball这个词的索引
  3. 用wordVectors通过索引查询baseball的词向量
wordsList = np.load('./glove_data/wordsList.npy')
print('Loaded the word list!')

wordsList = wordsList.tolist()  # Originally loaded as numpy array
wordVectors = np.load('./glove_data/wordVectors.npy')
print('Loaded the word vectors!')
print(len(wordsList))
# print(wordsList)
print(wordVectors.shape)

baseballIndex = wordsList.index('baseball')
print(baseballIndex)
print(wordVectors[baseballIndex])

运行结果

Loaded the word list!
Loaded the word vectors!
400001
(400001, 50)
1444
[-1.9327    1.0421   -0.78515   0.91033   0.22711  -0.62158  -1.6493
  0.07686  -0.5868    0.058831  0.35628   0.68916  -0.50598   0.70473
  1.2664   -0.40031  -0.020687  0.80863  -0.90566  -0.074054 -0.87675
 -0.6291   -0.12685   0.11524  -0.55685  -1.6826   -0.26291   0.22632
  0.713    -1.0828    2.1231    0.49869   0.066711 -0.48226  -0.17897
  0.47699   0.16384   0.16537  -0.11506  -0.15962  -0.94926  -0.42833
 -0.59457   1.3566   -0.27506   0.19918  -0.36008   0.55667  -0.70315
  0.17157 ]

5. 定义一个函数计算某个词与其它词的距离,然后排序

找King这个词距离最近的其它的词。
因为找出来太多了,所以我们去前5个看看

def find_closest_embeddings(embedding):
    return sorted(embeddings_dict.keys(), key=lambda word: spatial.distance.euclidean(embeddings_dict[word], embedding))
#print(find_closest_embeddings(embeddings_dict["king"]))
print(find_closest_embeddings(embeddings_dict["king"])[1:6])

结果

['prince', 'queen', 'uncle', 'ii', 'grandson']

6. 词向量的计算

例如, twig-branch+hand ≈ finger

print(find_closest_embeddings(embeddings_dict["twig"] - embeddings_dict["branch"] + embeddings_dict["hand"])[:5])

结果是fingernails是距离最近的

['fingernails', 'toenails', 'stringy', 'peeling', 'shove']

7 图片展示

利用TSNE降维,把每个词的词向量转化为二维向量,然后展示出来。

tsne = TSNE(n_components=2, random_state=0)
words =  list(embeddings_dict.keys())
vectors = [embeddings_dict[word] for word in words]
Y = tsne.fit_transform(vectors[:500])
plt.scatter(Y[:, 0], Y[:, 1])
for label, x, y in zip(words, Y[:, 0], Y[:, 1]):
    plt.annotate(label, xy=(x, y), xytext=(0, 0), textcoords="offset points")

plt.show()

运行结果
在这里插入图片描述

9. python环境中的所需包的版本

执行环境的所需相关的包的版本如下

import numpy as np
import scipy as scipy
import sklearn as sklearn
1.18.1
1.4.1
0.22.1

8. 参考资料

[1] https://medium.com/analytics-vidhya/basics-of-using-pre-trained-glove-vectors-in-python-d38905f356db
[2] Original GloVe Paper: https://nlp.stanford.edu/pubs/glove.pdf
[3] Original t-SNE Paper: http://jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf

  • 12
    点赞
  • 77
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茫茫人海一粒沙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值