1. 程式人生 > >windows下 word2vec學習筆記

windows下 word2vec學習筆記

1)安裝

gensim是word2vec的python版本,官網地址:gensim官網

在Anaconda相應的環境下執行以下命令,即可安裝成功:

pip install  --upgrade gensim

gensim中函式的使用方法,英文版介紹:gensim API

2)使用訓練好的模型

google提供了word2vec訓練好的model: GoogleNews-vectors-negative300.bin.gz 。

使用WinRAR解壓後。原文利用了下面python程式碼將檔案轉為txt格式,得到的txt檔案大約10G,生成時需要一些時間。

from gensim.models.keyedvectors import KeyedVectors

model = KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
model.save_word2vec_format('GoogleNews-vectors-negative300.txt', binary=False)

實際過程中發現生成txt後,可能由於檔案過大,讀取時間非常慢,執行3)中的操作時特別消耗時間。後來發現直接用bin也可以,所以不需要執行上面的程式碼。

3)利用下面的程式碼讀入model,測試結果。

from gensim.models.keyedvectors import KeyedVectors

model = KeyedVectors.load_word2vec_format("GoogleNews-vectors-negative300.bin", binary=True)

# 檢視word的詞向量
print(model['word'])
print(model['word'][0])

# 檢視所有的詞
print(model.wv.vocab.keys())

# 計算兩個詞的相似度/相關程度
y1 = model.similarity("woman", "man")
print("woman和man的相似度為:", y1)

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

# 尋找對應關係
print(' "boy" is to "father" as "girl" is to ...? ')
y3 = model.most_similar(['girl', 'father'], ['boy'], topn=3)
for item in y3:
    print(item[0], item[1])

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))

# 尋找不合群的詞
y4 = model.doesnt_match("breakfast cereal dinner lunch".split())
print("不合群的詞:", y4)