【问题标题】:I am trying to get the key of a particular word from a Word2Vec Vocabulary我正在尝试从 Word2Vec 词汇表中获取特定单词的键
【发布时间】:2018-05-07 14:36:10
【问题描述】:

Word2Vec

目前我正在尝试对文本语料库执行文本分类。为此,我决定在gensim 的帮助下执行word2vec。为此,我有以下代码:

sentences = MySentences("./corpus_samples") # a memory-friendly iterator
model = gensim.models.Word2Vec(sentences, size=100, window=5, min_count=5, workers=4)

我的句子基本上是一个处理文件的类I/O

class MySentences(object):
    def __init__(self, dirname):
        self.dirname = dirname

    def __iter__(self):
        for fname in os.listdir(self.dirname):
            for line in open(os.path.join(self.dirname, fname)):
                yield line.split()

现在我们可以通过以下几行获取已创建模型的词汇表:

print(model.wv.vocab)

其输出如下(示例):

t at 0x106f19438>, 'raining.': <gensim.models.keyedvectors.Vocab object at 0x106f19470>, 'fly': <gensim.models.keyedvectors.Vocab object at 0x106f194a8>, 'rain.': <gensim.models.keyedvectors.Vocab object at 0x106f194e0>, 'So…': <gensim.models.keyedvectors.Vocab object at 0x106f19518>, 'Ohhh,': <gensim.models.keyedvectors.Vocab object at 0x106f19550>, 'weird.': <gensim.models.keyedvectors.Vocab object at 0x106f19588>}

到目前为止,作为词汇表的字典包含单词字符串和&lt;gensim.models.keyedvectors.Vocab object at 0x106f19588&gt; 对象等。我希望能够查询特定单词的索引。为了使我的训练数据像:

w91874 w2300 w6 w25363 w6332 w11 w767 w297441 w12480 w256 w23270 w13482 w22236 w259 w11 w26959 w25 w1613 w25363 w111 __label__4531492575592394249
w17314 w5521 w7729 w767 w10147 w111 __label__1315009618498473661
w305 w6651 w3974 w1005 w54 w109 w110 w3974 w29 w25 w1513 w3645 w6 w111 __label__-400525901828896492
w30877 w72 w11 w2828 w141417 w77033 w10147 w111 __label__4970306416006110305
w3332 w1107 w4809 w1009 w327 w84792 w6 w922 w11 w2182 w79887 w1099 w111 __label__-3645735357732416904
w471 w14752 w1637 w12348 w72 w31330 w930 w11569 w863 w25 w1439 w72 w111 __label__-5932391056759866388
w8081 w5324 w91048 w875 w13449 w1733 w111 __label__3812457715228923422

其中wxxxx 表示词汇表中单词的索引,标签表示类别。


公司

我一直在试验的一些解决方案是gensimcorpora 实用程序:

corpora = gensim.corpora.dictionary.Dictionary(sentences, prune_at=2000000)
print(corpora)
print(getKey(corpora,'am'))

这给了我一个很好的单词词典,但是这个语料库词汇与上面提到的word2vec 函数创建的不一样。

【问题讨论】:

    标签: python dictionary nlp word2vec gensim


    【解决方案1】:

    TL;DR:

    model.wv.vocab['my_word'].index

    其中'my_word' 是您想要其索引的单词(例如'hello''the' 等)。

    长篇大论:

    之所以如此,是因为 gensim 将 Vocab 对象存储在 model.wv.vocab 字典中。

    这就是您在尝试打印字典时得到类似'raining.': &lt;gensim.models.keyedvectors.Vocab object at 0x106f19470&gt; 的结果的原因。

    Vocab 对象使用索引初始化,如下所示:

    wv.vocab[word] = Vocab(count=v, index=len(wv.index2word))

    因此允许访问此属性。

    我不明白您为什么需要这样表示,但这应该可以解决问题。

    更多详情可以在他们的source找到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 2020-02-28
      • 2018-12-12
      • 2023-01-27
      • 2016-06-06
      • 2023-03-24
      • 2016-10-07
      相关资源
      最近更新 更多