词向量 - 实际动手使用word2vec

在自然语言处理的任务中,无论哪种算法都需要将文本形态的词转换成为向量形式的词向量(word embedding)。良好的词向量可以达到语义相近的词在词向量空间里聚集在一起,这对后续的文本分类,文本聚类等等算法提供良好的数据样本,本文将详细介绍如何使用word2vec构建中文词向量

这里所需要用到的包,这些包需要首先使用pip或者conda安装

jiaba
gensim
sklearn

一、中文语料库

本文采用的是搜狗实验室的搜狗新闻语料库,数据链接 http://www.sogou.com/labs/resource/cs.php

下载下来的文件名为: news_sohusite_xml.full.tar.gz

二、数据预处理

2.1 解压数据文件

cd 到原始文件目录下,执行解压命令:

tar -zvxf news_sohusite_xml.full.tar.gz

2.2 提取有效内容

语料库中提供了很多的数据项,但是这里我们只需要使用 <content> </content> 中的内容,执行如下命令:

cat news_sohusite_xml.dat | iconv -f gbk -t utf-8 -c | grep "<content>" > corpus.txt

得到文件名为corpus.txt的文件。这里注意如果在windows下打开就会出现很多的编码错误,所以要么使用linux,要么在windows下使用bash 进行处理。不要在windows下编写python代码处理数据

2.3 分词

注意,对于中文来讲送给word2vec的文件是需要分词的,这样才可以较好的表达文本的意思。分词可以采用jieba分词实现

对原始文本内容进行分词,python 程序如下:

filePath = 'D:\\ML_learning\\NLP_data\\corpus.txt'
fileSegWordDonePath = 'D:\\ML_learning\\NLP_data\\corpusSegDone.txt'
fileTrainRead = pd.read_csv(filePath)
fileTrain = pd.Series(fileTrainRead.iloc[:,0])
f = lambda x: x[9:-11]
fileTrain = fileTrain.apply(f)

fileTrain.dropna(how='any')

fileTrainSeg = []
for line in fileTrain:
    data = jieba.cut(line, cut_all=False)
    # print(list(data))
    fileTrainSeg.append(" ".join(list(data)))

output_list = pd.Series(fileTrainSeg)
output_list.to_csv(fileSegWordDonePath, encoding='utf-8')

可以使用Pandas的特性快速批量的对数据进行格式化:

  • 使用pd.apply() 来对每行数据进行处理, 一句语句就可以删除所有string的起始的<content> 和结尾的</content>
  • 使用dropna 来去除数据为空的行

三、构建词向量

3.1 构建词向量

执行以下程序:

from gensim.models import word2vec
import pandas as pd

mopdelfilePath = 'D:\\ML_learning\\NLP_data\\model.bin'
fileSegWordDonePath = 'D:\\ML_learning\\NLP_data\\corpusSegDone.txt'

fileTrainRead = pd.read_csv(fileSegWordDonePath)
train_sentences = pd.Series(fileTrainRead.iloc[:, 1])
f = lambda x: str(x).split(" ")
train_sentences = train_sentences.apply(f)

model = word2vec.Word2Vec(train_sentences, size=300)
model.save(mopdelfilePath)

上面的代码将读入分词文件,并将其传入到word2vec中用来构建词向量,最后将构建出来的词向量保存。这里我们设置word2vec创建300维的词向量

3.2 显示并使用词向量

3.3.1 查看词向量

from gensim.models import word2vec
mopdelfilePath = 'D:\\ML_learning\\NLP_data\\model.bin'
model = word2vec.Word2Vec.load(mopdelfilePath)
print(model.wv['中国'])

可以得到如下结果(300维的一个向量):

[ 2.2904966 -2.2582266 -2.7562246 1.2342433 2.717599 1.377568
2.720106 0.9635297 -1.6690013 1.2432543 2.7351687 2.4857194

....

0.6931309 -1.1371846 -0.8067352 2.2179334 -1.1542435 1.1875417
0.76617193 1.3922322 -2.2338731 0.97370434 1.9159969 -1.706138 ]

3.3.2 查看词表中的词

from gensim.models import word2vec
mopdelfilePath = 'D:\\ML_learning\\NLP_data\\model.bin'
model = word2vec.Word2Vec.load(mopdelfilePath)
index = 1000
print (model.wv.index2word[1000])

得到结果如下:

存款

可以得到词表中第1000个词为: 存款

3.3.3 显示空间距离相近的词

一个好的词向量可以实现词义相近的一组词在词向量空间中也是接近的,可以通过显示词向量空间中相近的一组词并判断它们语义是否相近来评价词向量构建的好坏:

from gensim.models import word2vec
mopdelfilePath = 'D:\\ML_learning\\NLP_data\\model.bin'
model = word2vec.Word2Vec.load(mopdelfilePath)
 
indexes = model.wv.most_similar_cosmul('中国')
for index in indexes:
    print(index)

得到的结果如下 与给定词最相近的词以及相似度:

('我国', 0.8150987029075623)
('亚洲', 0.794571578502655)
('印度', 0.7809259295463562)
('国内', 0.7792256474494934)
('日本', 0.7718893885612488)
('美国', 0.7644745707511902)
('全球', 0.7569549083709717)
('本国', 0.7533475160598755)

四、二维空间中显示词向量

现在的词向量是300维的,为了能直观的显示这些词在向量空间中的分布,这里将词向量采用PCA进行降维,得到二维的词向量,并打印出来,代码如下:
中文的显示需要做特殊处理,需要加入字词文件

from gensim.models import word2vec
from sklearn.decomposition import PCA
import numpy as np
import matplotlib
import matplotlib.pyplot as plt

mopdelfilePath = 'D:\\ML_learning\\NLP_data\\model.bin'
model = word2vec.Word2Vec.load(mopdelfilePath)
raw_word_vec = model.wv.vectors

cent_word1 = "中国"
cent_word2 = "成都"
cent_word3 = "淘宝"
cent_word4 = "自行车"
cent_word5 = "计算机"

wordList1 = model.wv.most_similar_cosmul(cent_word1)
wordList2 = model.wv.most_similar_cosmul(cent_word2)
wordList3 = model.wv.most_similar_cosmul(cent_word3)
wordList4 = model.wv.most_similar_cosmul(cent_word4)
wordList5 = model.wv.most_similar_cosmul(cent_word5)


wordList1 = np.append([item[0] for item in wordList1], cent_word1)
wordList2 = np.append([item[0] for item in wordList2], cent_word2)
wordList3 = np.append([item[0] for item in wordList3], cent_word3)
wordList4 = np.append([item[0] for item in wordList4], cent_word4)
wordList5 = np.append([item[0] for item in wordList5], cent_word5)

def get_word_index(word):
    index = model.wv.vocab[word].index
    return index

index_list1 = map(get_word_index, wordList1)
index_list2 = map(get_word_index, wordList2)
index_list3 = map(get_word_index, wordList3)
index_list4 = map(get_word_index, wordList4)
index_list5 = map(get_word_index, wordList5)

vec_reduced = PCA(n_components=2).fit_transform(raw_word_vec)
zhfont = matplotlib.font_manager.FontProperties(fname=r'C:\Nuance\python_env\basic_dev\Lib\site-packages\matplotlib\mpl-data\fonts\ttf\msyh.ttf')
x = np.arange(-10, 10, 0.1)
y = x
plt.plot(x, y)

for i in index_list1:
    plt.text(vec_reduced[i][0], vec_reduced[i][1], model.wv.index2word[i], color='r', fontproperties=zhfont)

for i in index_list2:
    plt.text(vec_reduced[i][0], vec_reduced[i][1], model.wv.index2word[i], color='b', fontproperties=zhfont)

for i in index_list3:
    plt.text(vec_reduced[i][0], vec_reduced[i][1], model.wv.index2word[i], color='g', fontproperties=zhfont)

for i in index_list4:
    plt.text(vec_reduced[i][0], vec_reduced[i][1], model.wv.index2word[i], color='k', fontproperties=zhfont)

for i in index_list5:
    plt.text(vec_reduced[i][0], vec_reduced[i][1], model.wv.index2word[i], color='c', fontproperties=zhfont)
plt.show()

下图是执行结果:

image.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,701评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,649评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,037评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,994评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,018评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,796评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,481评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,370评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,868评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,014评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,153评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,832评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,494评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,039评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,437评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,131评论 2 356

推荐阅读更多精彩内容