【问题标题】:Gensim fast text get vocab or word indexGensim 快速文本获取词汇或单词索引
【发布时间】:2021-10-31 12:43:01
【问题描述】:

尝试使用gensim's fasttext,测试gensim的示例代码,将argument替换为corpus_iterable的小改动

https://radimrehurek.com/gensim/models/fasttext.html

gensim_version == 4.0.1

from gensim.models import FastText
from gensim.test.utils import common_texts  # some example sentences

print(common_texts[0])
['human', 'interface', 'computer']
print(len(common_texts))
9
model = FastText(vector_size=4, window=3, min_count=1)  # instantiate
model.build_vocab(corpus_iterable=common_texts)
model.train(corpus_iterable=common_texts, total_examples=len(common_texts), epochs=10)

它可以工作,但有没有办法为模型提供get the vocab。例如,在Tensorflow Tokenizer 中有一个word_index,它将返回all the words。这里有类似的吗?

【问题讨论】:

    标签: machine-learning nlp gensim word-embedding fasttext


    【解决方案1】:

    模型将词向量存储在.wv 对象中。我不知道您使用的是哪个 gensim 版本,但对于 Gensim 4,您可以通过调用 model.wv.key_to_index 获取键控向量。你会得到一个包含单词及其索引的字典

    from gensim.models import FastText
    from gensim.test.utils import common_texts  # some example sentences
    print(common_texts[0])
    # ['human', 'interface', 'computer']
    print(len(common_texts))
    # 9
    model = FastText(vector_size=4, window=3, min_count=1)  # instantiate
    model.build_vocab(corpus_iterable=common_texts)
    model.train(corpus_iterable=common_texts, total_examples=len(common_texts), epochs=10)
    # get vocab keys with indices
    vocab = model.wv.key_to_index
    print(vocab)
    # output
    # {'system': 0, 'graph': 1, 'trees': 2, 'user': 3, 'minors': 4, 'eps': 5, 'time': 6, 
    # 'response': 7, 'survey': 8, 'computer': 9, 'interface': 10, 'human': 11}
    

    【讨论】:

    • 注意你也可以使用model.wv.index_to_key作为键的有序列表,每个键在model.wv.vectors中行的匹配位置持有对应的向量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    • 2016-06-06
    • 2023-03-24
    • 1970-01-01
    • 2014-11-07
    相关资源
    最近更新 更多