Python基於word2vec的詞語相似度計算

 詞語相似度計算

在商品搜索的過程中,可以計算用戶輸入的關鍵字與數據庫中商品名間的相似度,在商品數據庫中找出相似度最大的商品,推薦給用戶。比如“凳子”跟“椅子”的語意更相近,跟“香蕉”或“冰箱”的語意相對較遠,這種相近的程度就是詞語的相似度。在實際的工程開發中可以通過word2vec實現詞語相似度的計算。

from sklearn.datasets import fetch_20newsgroups

news = fetch_20newsgroups(subset='all')
X, y = news.data, news.target

from bs4 import BeautifulSoup
import nltk, re


# 把段落分解成由句子組成的list(每個句子又被分解成詞語)
def news_to_sentences(news):
    news_text = BeautifulSoup(news, 'lxml').get_text()
    tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
    raw_sentences = tokenizer.tokenize(news_text)

    # 對每個句子進行處理,分解成詞語
    sentences = []
    for sent in raw_sentences:
        sentences.append(re.sub('[^a-zA-Z]', ' ', sent.lower().strip()).split())
    return sentences


sentences = []

for x in X:
    sentences += news_to_sentences(x)

# import numpy
# # 將預處理過的"詞庫"保存到文件中,便於調試
# numpy_array = numpy.array(sentences)
# numpy.save('sentences.npy', numpy_array)
#
# # 將預處理後的"詞庫"從文件中讀出,便於調試
# numpy_array = numpy.load('sentences.npy')
# sentences = numpy_array.tolist()


from gensim.models import word2vec

model = word2vec.Word2Vec(sentences, workers=2, size=300, min_count=20, window=5,sample=1e-3)

model.init_sims(replace=True)

# 保存word2vec訓練參數便於調試
# model.wv.save_word2vec_format('word2vec_model.bin', binary=True)
# model.wv.load_word2vec_format('word2vec_model.bin', binary=True)

print('詞語相似度計算:')
print('morning vs morning:{0}').format(model.n_similarity('morning', 'morning'))
print('morning vs afternoon:{0}').format(model.n_similarity('morning', 'afternoon'))
print('morning vs hello:{0}').format(model.n_similarity('morning', 'hello'))
print('morning vs shell:{0}').format(model.n_similarity('morning', 'shell'))


# 運行結果
morning vs morning:1.0
morning vs afternoon:0.871482
morning vs hello:0.731609
morning vs shell:0.709714

調試技巧

在開發調試的過程中,會出現錯誤,需要重新運行程序。如果每次修改後,都從頭開始執行,肯定會消耗很多無用的時間。比如,預處理後的文本結果和word2vec的訓練參數,這些中間結果可以保持下來,當遇到問題時,就可以從文件中讀取結果,而不需要每次都從頭開始。

gensim庫word2vec的使用詳解

from gensim.models import Word2Vec 
model = Word2Vec(sentences, sg=1, size=100, window=5, min_count=5, negative=3, sample=0.001, hs=1, workers=4)

# 訓練後的模型保存與加載
model.save(fname) 
model = Word2Vec.load(fname)

# 模型使用(詞語相似度計算等)
model.most_similar(positive=['woman', 'king'], negative=['man']) 
#輸出[('queen', 0.50882536), ...] 
  
model.doesnt_match("breakfast cereal dinner lunch".split())  # 找出不匹配的詞語
#輸出'cereal' 
  
model.similarity('woman', 'man')  # 兩個詞的相似性距離
#輸出0.73723527 
  
model['computer']     # 輸出單詞向量
#輸出array([-0.00449447, -0.00310097, 0.02421786, ...], dtype=float32)




參數解釋:

1.sg=1是skip-gram算法,對低頻詞敏感;默認sg=0爲CBOW算法。

2.size是輸出詞向量的維數,值太小會導致詞映射因爲衝突而影響結果,值太大則會耗內存並使算法計算變慢,一般值取爲100到200之間。

3.window是句子中當前詞與目標詞之間的最大距離,3表示在目標詞前看3-b個詞,後面看b個詞(b在0-3之間隨機)。

4.min_count是對詞進行過濾,頻率小於min-count的單詞則會被忽視,默認值爲5。

5.negative和sample可根據訓練結果進行微調,sample表示更高頻率的詞被隨機下采樣到所設置的閾值,默認值爲1e-3。

6.hs=1表示層級softmax將會被使用,默認hs=0且negative不爲0,則負採樣將會被選擇使用。

7.workers控制訓練的並行,此參數只有在安裝了Cpython後纔有效,否則只能使用單核。

詳細參數說明可查看word2vec源代碼。

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章