Keras NLP——詞嵌入模型

一.詞嵌入概念

詞嵌入是一種提供單詞的密集向量表示的方法,可以捕獲單詞的含義。詞嵌入是對簡單的詞袋模型編碼方案的改進,任何一個文檔在詞袋模型方案的編碼下最終形成的是一個巨大的稀疏的向量(大多數是0值),僅僅捕獲的是文檔的內容,而不是詞的意思。詞嵌入模型是在大規模文本語料庫上通過使用一定的算法訓練一組固定長度密集和連續值向量獲得的。每個單詞由嵌入空間中的一個點表示,這些點是根據圍繞目標單詞的單詞學習和移動的。詞本身由自己的伴生詞(文本中詞兩側的詞)來定義的,可以通過嵌入來學習單詞的意思。單詞向量空間表示提供了一個投影,其中具有相似含義的單詞在空間內局部聚類。關於詞嵌入的具體細節請參考本篇博客:遷移學習的概念與方法

二.開發Word2Vec嵌入

Word2Vec是一種用於從文本語料庫中學習詞嵌入模型的算法。有兩種主要的訓練算法可用於從文本學習詞嵌入模型:連續詞袋(CBOW)和Skip-Gram。Word2Vec模型訓練需要大量文本,例如整個維基百科語料庫。在此,僅僅使用一個小文本例子來演示訓練詞嵌入模型的原理。Gensim Python包提供了使用Word2Vec模型的Word2Vec類。從文本學習單詞嵌入模型涉及到文本加載、將文本分割成句子並將它作爲參數傳遞給Word2Vec實例的構造函數。具體而言,每個句子必須被標記化,意味着分成單詞並準備好。句子可以是加載到內存中的文本,也可以是逐步加載文本的迭代器(大規模文本語料庫加載方法)。Gensim Word2Vec構造函數有很多參數,下面是一些值得注意的參數:

  • size:(默認值100)詞嵌入向量的維數
  • window:(默認值5) 目標詞與目標詞周圍詞之間的最大距離
  • min count:(默認值5) 訓練模型時需要考慮的最小字數,小於此計數的單詞將被忽略
  • workers:(默認值3) 訓練時使用的線程數
  • sg:(默認值0) 訓練算法:0表示CBOW,1表示Skip-Gram
    在模型訓練之後,可以通過wv屬性訪問它。還能通過調用單詞矢量模型上的save_word2vec_format()函數將訓練好的模型文件保存到文件中(默認情況下,模型以二進制格式保存以節省空間)。然後還可以通過調用Word2Vec.load()函數再次加載保存的模型。
#!/usr/bin/env python3
# encoding: utf-8
'''
@file: Keras_word2vec.py
@time: 2020/7/5 0005 21:59
@author: Jack
@contact: [email protected]
'''

from gensim.models import Word2Vec

sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
             ['this', 'is', 'the', 'second', 'sentence'],
             ['yet', 'another', 'sentence'],
             ['one', 'more', 'sentence'],
             ['and', 'the', 'final', 'sentence']]

model = Word2Vec(sentences, min_count=1)
print(model)
words = list(model.wv.vocab)
print(words)
print(model['sentence'])
model.save('model.bin')
new_model = Word2Vec.load('model.bin')
print(new_model)

Word2Vec(vocab=14, size=100, alpha=0.025)
['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec', 'second', 'yet', 'another', 'one', 'more', 'and', 'final']
[ 1.5970342e-03  3.0990422e-03 -1.5597004e-03  1.0130922e-04
  4.6453704e-03  4.8387623e-03 -1.7510486e-03 -1.3356048e-03
 -1.9883395e-03  5.9007361e-05 -1.1112307e-03 -4.1536316e-03
  3.6945145e-03 -1.6147217e-03  2.7425054e-03 -3.7472381e-03
 -2.8020672e-03  4.3358863e-03  1.1823174e-03  2.9089549e-03
  3.3314351e-03 -6.5788359e-04  6.9831114e-04  4.0198332e-03
 -3.8785536e-03  3.6612628e-03 -3.7423281e-03 -6.5154553e-04
  1.1573763e-03  2.1937855e-04  1.5912919e-03  8.7182119e-04
 -3.2798641e-03  3.1347673e-03 -2.3850927e-03  4.3258183e-03
 -1.9930664e-03 -3.8760060e-03 -8.6675974e-04  2.8453881e-04
 -1.7244455e-03 -4.9040834e-03 -4.0097716e-03 -4.2938511e-03
  1.0308551e-03  7.8650279e-04  5.0712365e-04  3.5261957e-03
  4.0291143e-03 -2.9941991e-03  2.8647142e-03  1.5664878e-03
  4.4487659e-03  3.3967711e-03  4.8973183e-03 -2.1807828e-03
  2.0259018e-03  1.8970913e-03 -2.1978706e-04 -8.5533579e-04
  2.9131054e-04 -3.3934473e-03 -1.1175221e-03  4.6166801e-03
 -2.0422529e-04  3.1610699e-03  4.8198495e-03  1.6930439e-05
  5.3703779e-04 -4.9693636e-03  2.5525053e-03 -4.3471768e-03
  2.9601078e-03  4.3827929e-03 -3.4209811e-03  3.5368798e-03
  4.8480975e-03 -1.5721031e-03  2.2279820e-03  2.1352980e-03
  4.7594612e-04 -9.6263684e-04 -2.1694885e-03  2.5529866e-03
 -1.8718592e-03  1.5937366e-03 -2.8575391e-03  3.5459616e-03
  3.1409469e-03  3.9983247e-03  2.3655379e-03  2.7748533e-03
 -4.7552404e-03  9.8598364e-04 -4.1911597e-03 -5.8383367e-04
  4.7576688e-03  2.0652534e-03  4.6017808e-03  1.8423117e-03]
Word2Vec(vocab=14, size=100, alpha=0.025)

三.可視化詞嵌入

在矢量上使用投影方法將其降維,例如scikit-learn中提供的那些方法,然後使用Matplotlib將投影繪製爲散點圖來可視化詞嵌入。

#!/usr/bin/env python3
# encoding: utf-8
'''
@file: Keras_word2vec.py
@time: 2020/7/5 0005 21:59
@author: Jack
@contact: [email protected]
'''

from gensim.models import Word2Vec
from sklearn.decomposition import PCA
from matplotlib import pyplot

sentences = [['this', 'is', 'the', 'first', 'sentence', 'for', 'word2vec'],
             ['this', 'is', 'the', 'second', 'sentence'],
             ['yet', 'another', 'sentence'],
             ['one', 'more', 'sentence'],
             ['and', 'the', 'final', 'sentence']]

model = Word2Vec(sentences, min_count=1)
print(model)
words = list(model.wv.vocab)
print(words)
print(model['sentence'])
model.save('model.bin')
new_model = Word2Vec.load('model.bin')
print(new_model)
X = model[model.wv.vocab]
pca = PCA(n_components=2)
result = pca.fit_transform(X)
pyplot.scatter(result[:, 0], result[:, 1])
for i, word in enumerate(words):
    pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))
pyplot.show()

在這裏插入圖片描述

四.詞嵌入預訓練模型

訓練自己的單詞向量可能是給定NLP問題的最佳方法。但是它可能不但需要很長時間,還需要海量的數據以及對訓練算法方面的一些專業知識也有要求。另一種方法就是簡單地使用現有的預訓練單詞嵌入模型。Google的Word2Vec模型時在其新聞數據(約1000億字)上訓練得到的;它包含300多萬個單詞和短語,詞向量是300維的,這是一個1.53GB的文件,下載鏈接爲:Word2Vec預訓練模型 ,模型下載好之後,可以通過Gensim庫的KeyedVectors.load_word2vec_format()函數將此模型加載到內存中,然後通過一個有趣的例子來測試下是否載入成功:

from gensim.models import KeyedVectors

filename = r'F:\工作資料\NLP\詞嵌入模型\Word2Vec\GoogleNews-vectors-negative300.bin'
model = KeyedVectors.load_word2vec_format(filename, binary=True)
result = model.most_similar(positive=['woman', 'king'], negative=['man'], topn=1)
print(result)
[('queen', 0.7118192315101624)]

此外,斯坦福大學的研究人員也開發了一套像Word2Vec一樣的詞嵌入模型訓練算法,稱爲全局向量詞表示(Global Vector for Word Representation)法,簡稱Glove(NLP從業者似乎更喜歡Glove)。與Word2Vec一樣,Glove研究人員也提供預訓練的單詞向量,可供選擇。下載Glove預訓練模型後,第一步是通過Gensim的glove2word2vec()函數將Glove文件格式轉換爲Word2Vec文件格式。Glove預訓練模型下載鏈接爲:Glove預訓練模型

from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
glove_input_file = 'glove/glove.6B.100d.txt'
word2vec_output_file = 'glove.6B.100d.txt.word2vec'
glove2word2vec(glove_input_file ,word2vec_output_file )
filename = 'glove.6B.100d.txt.word2vec'
model = KeyedVectors.load_word2vec_format(filename,binary=False)
result = model.most_similar(positive=['woman','king'],negative=['man'],topn=1)
print(result)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章