【发布时间】: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>}
到目前为止,作为词汇表的字典包含单词字符串和<gensim.models.keyedvectors.Vocab object at 0x106f19588> 对象等。我希望能够查询特定单词的索引。为了使我的训练数据像:
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 表示词汇表中单词的索引,标签表示类别。
公司
我一直在试验的一些解决方案是gensim 的corpora 实用程序:
corpora = gensim.corpora.dictionary.Dictionary(sentences, prune_at=2000000)
print(corpora)
print(getKey(corpora,'am'))
这给了我一个很好的单词词典,但是这个语料库词汇与上面提到的word2vec 函数创建的不一样。
【问题讨论】:
标签: python dictionary nlp word2vec gensim