python - 我正在尝试从 Word2Vec 词汇表中获取特定单词的键
问题描述
Word2Vec
目前我正在尝试对文本语料库执行文本分类。为了做到这一点,我决定word2vec
在gensim
. 为此,我有以下代码:
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
表示词在词汇表中的索引,标签表示类。
语料库
我一直在尝试的一些解决方案corpora
是gensim
:
corpora = gensim.corpora.dictionary.Dictionary(sentences, prune_at=2000000)
print(corpora)
print(getKey(corpora,'am'))
word2vec
这给了我一个很好的单词字典,但是这个语料库词汇与上面提到的函数创建的不一样。
解决方案
TL;博士:
model.wv.vocab['my_word'].index
'my_word'
您想要其索引的单词在哪里(例如'hello'
,,'the'
等)。
很长的故事:
之所以如此,是因为 gensim 将Vocab
对象存储在model.wv.vocab
字典中。
这就是你'raining.': <gensim.models.keyedvectors.Vocab object at 0x106f19470>
在尝试打印字典时得到结果的原因。
该Vocab
对象使用索引初始化,如下所示:
wv.vocab[word] = Vocab(count=v, index=len(wv.index2word))
因此允许访问此属性。
我不明白你为什么需要这样表示它,但这应该可以解决问题。
更多细节可以在他们的源代码中找到
推荐阅读
- python - 将列表元素存储在单个变量中以进行查询
- android - API 级别 30 为印地语提供了不受支持的语言错误代码
- pygame - Pygame:音乐比应有的慢
- python - 令牌登录身份验证 Django REST
- python - Python:从巨大的 JSON 中获取特定值并将其存储为列表
- python - 无法获取绘图 /usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:3: MatplotlibDeprecationWarning:
- python - 我们可以从 AWS S3 复制图像并将其写入 excel 文件(S3)而不使用 Python 在本地存储数据吗?
- javascript - React Hooks - 即使对象为空,仍会调用 useEffect
- java - 在 switch case 方法调用中预期的表达式
- python - 如何将代码发送到 3ds Max 脚本侦听器