1. 程式人生 > >python 環境下gensim中的word2vec的使用筆記

python 環境下gensim中的word2vec的使用筆記

centos 7, python2.7, gensim (0.13.1)

語料:

程式:

# -*- coding: utf-8 -*-
'''
Created on 2016年8月29日
測試gensim使用
@author: root
'''

from gensim.models import word2vec
import logging
import numpy as np
# 主程式
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus(u"/media/sf_workspace/nlp-workspace/nltk-test/word2vec/data/text8"
) # 載入語料 n_dim=200 model = word2vec.Word2Vec(sentences, size=n_dim) # 訓練skip-gram模型; 預設window=5 # n_dim = 300 # #Initialize model and build vocab # imdb_w2v = Word2Vec(size=n_dim, min_count=1) # imdb_w2v.build_vocab(sentences) # #Train the model over train_reviews (this may take several minutes) # imdb_w2v.train(sentences)
# obtain the word vectors as follows: text=["hi","no"] vec = np.zeros(n_dim).reshape((1, n_dim)) print type(vec) count = 0. for word in text: try: vec += model[word].reshape((1, n_dim)) print vec count += 1. except KeyError: continue if count != 0: vec /= count print
count print vec # 計算兩個詞的相似度/相關程度 y1 = model.similarity("woman", "man") print u"woman和man的相似度為:", y1 print "--------\n" # 計算某個詞的相關詞列表 y2 = model.most_similar("good", topn=20) # 20個最相關的 print u"和good最相關的詞有:\n" for item in y2: print item[0], item[1] print "--------\n" # 尋找對應關係 print ' "boy" is to "father" as "girl" is to ...? \n' y3 = model.most_similar(['girl', 'father'], ['boy'], topn=3) for item in y3: print item[0], item[1] print "--------\n" more_examples = ["he his she", "big bigger bad", "going went being"] for example in more_examples: a, b, x = example.split() predicted = model.most_similar([x, b], [a])[0][0] print "'%s' is to '%s' as '%s' is to '%s'" % (a, b, x, predicted) print "--------\n" # 尋找不合群的詞 y4 = model.doesnt_match("breakfast cereal dinner lunch".split()) print u"不合群的詞:", y4 print "--------\n" # 儲存模型,以便重用 model.save("text8.model") # 對應的載入方式 # model_2 = word2vec.Word2Vec.load("text8.model") # 以一種C語言可以解析的形式儲存詞向量 model.save_word2vec_format("text8.model.bin", binary=True) # 對應的載入方式 # model_3 = word2vec.Word2Vec.load_word2vec_format("text8.model.bin", binary=True) if __name__ == "__main__": pass

中文

語料格式示例:

一一
一一列舉
一一對應 一丁點 一丁點兒 一萬年
一丈紅
一下
一下子
一不做
一不小心
一專多能
一世
一丘之貉
一業
一叢
一絲一毫
一絲不掛
一絲不苟
一個
一個勁
一個樣
一中
一中一臺
一中全會
一舉
一舉一動
一舉兩得
一舉多得

# -*- coding: utf-8 -*-
'''
Created on 2016年8月29日
測試gensim使用,處理中文語料
@author: root
'''

from gensim.models import word2vec
import logging
import sys
reload(sys) #重新載入sys
sys.setdefaultencoding("utf8") #設定預設編碼格式
# 主程式
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.Text8Corpus(u"/media/sf_workspace/nlp-workspace/nltk-test/word2vec/data/test1.txt")  # 載入語料
model = word2vec.Word2Vec(sentences,min_count=1, size=200)  # 訓練skip-gram模型

# 計算兩個詞的相似度/相關程度
y1 = model.similarity(u"淮南子", u"淮南子")
print  y1
print "--------\n"

# 計算某個詞的相關詞列表
y2 = model.most_similar(u"淮南子", topn=20)  # 20個最相關的
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

參考: