1. 程式人生 > >【python gensim使用】word2vec詞向量處理中文語料

【python gensim使用】word2vec詞向量處理中文語料

word2vec介紹
word2vec官網:https://code.google.com/p/word2vec/

word2vec是google的一個開源工具,能夠根據輸入的詞的集合計算出詞與詞之間的距離。
它將term轉換成向量形式,可以把對文字內容的處理簡化為向量空間中的向量運算,計算出向量空間上的相似度,來表示文字語義上的相似度。
word2vec計算的是餘弦值,距離範圍為0-1之間,值越大代表兩個詞關聯度越高。
詞向量:用Distributed Representation表示詞,通常也被稱為“Word Representation”或“Word Embedding(嵌入)”。
簡言之:詞向量表示法讓相關或者相似的詞,在距離上更接近。

具體使用(處理中文)
收集語料
本文:亞馬遜中文書評語料,12萬+句子文字。 
語料以純文字形式存入txt文字。 
注意: 
理論上語料越大越好 
理論上語料越大越好 
理論上語料越大越好 
重要的事情說三遍。 
因為太小的語料跑出來的結果並沒有太大意義。

分詞
中文分詞工具還是很多的,我自己常用的: 
- 中科院NLPIR 
- 哈工大LTP 
- 結巴分詞

注意:分詞文字將作為word2vec的輸入檔案。

分詞文字示例 


word2vec使用
python,利用gensim模組。 
win7系統下在通常的python基礎上gensim模組不太好安裝,所以建議使用anaconda,具體參見: python開發之anaconda【以及win7下安裝gensim】

直接上程式碼——
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
功能:測試gensim使用,處理中文語料
時間:2016年5月21日 20:49:07
"""

from gensim.models import word2vec
import logging

# 主程式
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus(u"C:\\Users\\lenovo\\Desktop\\word2vec實驗\\亞馬遜中文書評語料.txt")  # 載入語料
model = word2vec.Word2Vec(sentences, size=200)  # 預設window=5

model.save("./text8.model")

model.save_word2vec_format("./text8.model.bin",binary=True)
model= word2vec.Word2Vec.load_word2vec_format("./text8.model.bin", binary=True)
--------------------- 

 

# 計算兩個詞的相似度/相關程度
y1 = model.similarity(u"不錯", u"好")
print u"【不錯】和【好】的相似度為:", y1
print "--------\n"

# 計算某個詞的相關詞列表
y2 = model.most_similar(u"書", topn=20)  # 20個最相關的
print u"和【書】最相關的詞有:\n"
for item in y2:
    print item[0], item[1]
print "--------\n"

# 尋找對應關係
print u"書-不錯,質量-"
y3 = model.most_similar([u'質量', u'不錯'], [u'書'], topn=3)
for item in y3:
    print item[0], item[1]
print "--------\n"

# 尋找不合群的詞
y4 = model.doesnt_match(u"書 書籍 教材 很".split())
print u"不合群的詞:", y4
print "--------\n"

# 儲存模型,以便重用
model.save(u"書評.model")
# 對應的載入方式
# model_2 = word2vec.Word2Vec.load("text8.model")

# 以一種C語言可以解析的形式儲存詞向量
model.save_word2vec_format(u"書評.model.bin", binary=True)
# 對應的載入方式
# model_3 = word2vec.Word2Vec.load_word2vec_format("text8.model.bin", binary=True)

if __name__ == "__main__":
    pass
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
執行結果
【不錯】和【好】的相似度為: 0.790186663972
--------

和【書】最相關的詞有:

書籍 0.675163209438
書本 0.633386790752
確實 0.568059504032
教材 0.551493048668
正品 0.532882153988
沒得說 0.529319941998
好 0.522468209267
據說 0.51004421711
圖書 0.508755385876
挺 0.497194319963
新書 0.494331330061
很 0.490583062172
不錯 0.476392805576
正版 0.460161447525
紙張 0.454929769039
可惜 0.450752496719
工具書 0.449723362923
的確 0.448629021645
商品 0.444284260273
紙質 0.443040698767
--------

書-不錯,質量-
精美 0.507958948612
總的來說 0.496103972197
材質 0.493623793125
--------

不合群的詞: 很
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
參考資料
【python gensim使用】word2vec詞向量處理英文語料: 
http://blog.csdn.net/churximi/article/details/51472203 
深度學習:使用 word2vec 和 gensim: 
http://www.open-open.com/lib/view/open1420687622546.html
--------------------- 
作者:竹聿Simon 
來源:CSDN 
原文:https://blog.csdn.net/churximi/article/details/51472300 
版權宣告:本文為博主原創文章,轉載請附上博文連結!

 

import gensim
import codecs
from gensim.models import word2vec
import re
from gensim.corpora.dictionary import Dictionary

import pickle
import logging

import numpy as np
# 引入日誌配置
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus('D:/csvtxt/corpus.txt')
model = word2vec.Word2Vec(sentences, size=100,min_count=1)###不過濾只出現1次的詞
model.save('word2vec.model')
print(model.similarity('怎麼','如何'))
###將模型儲存為txt
file=codecs.open('D:/csvtxt/corpus.txt','r+',encoding='utf-8').read()
file1=re.sub('\r\n',' ',file)
file2=file1.split(' ')
vector=[]
for each in file2:
    line=list(model[each])
    lines=[str(i) for i in line]
    linestr=' '.join(lines)
    L=each+' '+linestr
    vector.append(L)
vect='\n'.join(vector)
ff=codecs.open('D:/csvtxt/xyz-add-wordvec.txt','w+',encoding='utf-8')
ff.write(vect)
--------------------- 
作者:zcancandice 
來源:CSDN 
原文:https://blog.csdn.net/weixin_38889448/article/details/79977071 
版權宣告:本文為博主原創文章,轉載請附上博文連結!