为什么Gensim拒绝加载FasttextFacebook库构建的监督模型dict?

问题描述

我当时认为基础字典对于有监督(分类)和无监督(词嵌入)都是相同的。我想分析我使用Gensim为监督问题构建的分类模型(词向量)。但我得到以下错误。我知道 Gensim尚未实现Fastext的“监督学习”部分,而只专注于词嵌入。但是我只想加载字典进行分析。有指针吗?

Traceback (most recent call last):
  File "fasttext_model_analysis.py",line 2,in <module>
    model = FastText.load_fasttext_format('model_ups_tickets_rca.bin')
  File "/usr/local/lib/python3.5/dist-packages/gensim/models/deprecated/fasttext_wrapper.py",line 274,in load_fasttext_format
    model.load_binary_data(encoding=encoding)
  File "/usr/local/lib/python3.5/dist-packages/gensim/models/deprecated/fasttext_wrapper.py",line 301,in load_binary_data
    self.load_dict(f,encoding=encoding)
  File "/usr/local/lib/python3.5/dist-packages/gensim/models/deprecated/fasttext_wrapper.py",line 332,in load_dict
    raise NotImplementedError("Supervised fastText models are not supported")
NotImplementedError: Supervised fastText models are not supported

解决方法

Gensim决定不支持-supervised FastText模式,因为Gensim的重点是不受监督的主题建模。因此,当任何人尝试加载这样的FastText模型时,它都会引发此早期错误,以免误导用户正在运行的东西,或者在内存中具有无法解释的/损坏的半读模型。

但是,在没有完整的模型和分类选项的情况下,提供大量的单词向量可能是合理的。 (仅读取那些单词向量,而忽略不支持的状态,可能对现有的读取代码进行很小的更改。)

您可以随时在Gensim项目问题跟踪器中请求支持(甚至重新评估不支持-supervised模式的决定):https://github.com/RaRe-Technologies/gensim/issues

同时,如果可以将字向量从FastText单独导出为Gensim支持的格式,那么这可能是一个实际的解决方法。看来,来自Facebook的FastText的Python包装器– https://github.com/facebookresearch/fastText/blob/master/python/fasttext_module/fasttext/FastText.py –提供了访问每个单词和向量的方法,因此可以加载并复制到Gensim KeyedVectors实例中,或者以其他方式写入到可读的磁盘文件。

大致(这是未经测试的代码):

import fasttext  # as installed by `pip install fasttext`
from gensim.models import KeyedVectors

ft_model = fasttext.load_model('ft.bin')
kv = KeyedVectors(vector_size=ft_model.get_dimension())
all_words = ft_model.get_words()
all_vectors = [ft_model.get_word_vector(w) for w in all_words]
kv.add(all_words,all_vectors)
kv.save_word2vec_format('ftwords.txt',binary=False)