词向量 - 实际动手使用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 提取有效内容

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

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的起始的 和结尾的
* 使用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

猜你喜欢

转载自blog.csdn.net/sfw_123817/article/details/81304658