无法从其vector_ngrams复制经过训练的单词向量

问题描述 投票:0回答:1

只是出于好奇,但是我正在调试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。

如果我错过了某件事或做错了什么,如果有人可以指出我的话,那就太好了。预先感谢!

python-3.x gensim fasttext oov
1个回答
0
投票

一个完整单词的FastText单词矢量的计算不是just其字符n-gram矢量的总和,而是一个原始的完整单词矢量,该单词也已针对词汇中的单词进行了训练。

您从ft.wv[word]中获得的已知单词的完整单词向量已经预先计算了此组合。有关完整计算的示例,请参见adjust_vectors()方法:

https://github.com/RaRe-Technologies/gensim/blob/68ec5b8ed7f18e75e0b13689f4da53405ef3ed96/gensim/models/keyedvectors.py#L2282

raw全字向量在.vectors_vocab对象的model.wv数组中。

((如果这还不足以解决问题,请确保您使用的是最新的gensim,因为最近有很多FT修复程序。并且请确保您的ngram哈希列表与ft_ngram_hashes()的输出匹配库的方法–否则,您的手动ngram-list-creation和后续的哈希操作可能会有所不同。)

© www.soinside.com 2019 - 2024. All rights reserved.