![](/img/trans.png)
[英]How to turn a list of words into a list of vectors using a pre-trained word2vec model(Google)?
[英]Cannot reproduce pre-trained word vectors from its vector_ngrams
只是出於好奇,但我正在調試 gensim 的 FastText 代碼以復制詞匯外 (OOV) 單詞的實現,但我無法完成它。 因此,我遵循的過程是用玩具語料庫訓練一個小模型,然后比較詞匯表中單詞的結果向量。 這意味着如果整個過程沒問題,輸出數組應該是相同的。
這是我用於測試的代碼:
from gensim.models import FastText
import numpy as np
# Default gensim's function for hashing ngrams
from gensim.models._utils_any2vec import ft_hash_bytes
# Toy corpus
sentences = [['hello', 'test', 'hello', 'greeting'],
['hey', 'hello', 'another', 'test']]
# Instatiate FastText gensim's class
ft = FastText(sg=1, size=5, min_count=1, \
window=2, hs=0, negative=20, \
seed=0, workers=1, bucket=100, \
min_n=3, max_n=4)
# Build vocab
ft.build_vocab(sentences)
# Fit model weights (vectors_ngram)
ft.train(sentences=sentences, total_examples=ft.corpus_count, epochs=5)
# Save model
ft.save('./ft.model')
del ft
# Load model
ft = FastText.load('./ft.model')
# Generate ngrams for test-word given min_n=3 and max_n=4
encoded_ngrams = [b"<he", b"<hel", b"hel", b"hell", b"ell", b"ello", b"llo", b"llo>", b"lo>"]
# Hash ngrams to its corresponding index, just as Gensim does
ngram_hashes = [ft_hash_bytes(n) % 100 for n in encoded_ngrams]
word_vec = np.zeros(5, dtype=np.float32)
for nh in ngram_hashes:
word_vec += ft.wv.vectors_ngrams[nh]
# Compare both arrays
print(np.isclose(ft.wv['hello'], word_vec))
對於比較數組的每個維度,此腳本的輸出都是 False。
如果有人能指出我遺漏了什么或做錯了什么,那就太好了。 提前致謝!
一個完整詞的 FastText 詞向量的計算不僅是其字符 n-gram 向量的總和,而且還是一個原始的完整詞向量,該向量也針對詞匯表中的詞進行了訓練。
您從ft.wv[word]
返回的全詞向量已經預先計算了這種組合。 有關此完整計算的示例,請參閱adjust_vectors()
方法:
原始全字矢量是在一個.vectors_vocab
的上陣列model.wv
對象。
(如果這還不足以解決問題:確保您使用的是最新的gensim
,因為最近有許多 FT 修復。並且,確保您的 ngram-hashes 列表與庫的ft_ngram_hashes()
方法的輸出相匹配– 如果沒有,您的手動 ngram-list-creation 和隨后的散列可能會做一些不同的事情。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.