python - 如何使用 gensim 从语料库中提取短语

标签 python nlp gensim

为了预处理语料库,我打算从语料库中提取常用短语,为此我尝试在 gensim 中使用 短语 模型,我尝试了下面的代码,但它没有给我想要的输出。

我的代码

from gensim.models import Phrases
documents = ["the mayor of new york was there", "machine learning can be useful sometimes"]

sentence_stream = [doc.split(" ") for doc in documents]
bigram = Phrases(sentence_stream)
sent = [u'the', u'mayor', u'of', u'new', u'york', u'was', u'there']
print(bigram[sent])

输出

[u'the', u'mayor', u'of', u'new', u'york', u'was', u'there']

但应该是这样的

[u'the', u'mayor', u'of', u'new_york', u'was', u'there']

但是当我尝试打印火车数据的词汇时,我可以看到二元组,但它不适用于测试数据,我哪里出错了?

print bigram.vocab

defaultdict(<type 'int'>, {'useful': 1, 'was_there': 1, 'learning_can': 1, 'learning': 1, 'of_new': 1, 'can_be': 1, 'mayor': 1, 'there': 1, 'machine': 1, 'new': 1, 'was': 1, 'useful_sometimes': 1, 'be': 1, 'mayor_of': 1, 'york_was': 1, 'york': 1, 'machine_learning': 1, 'the_mayor': 1, 'new_york': 1, 'of': 1, 'sometimes': 1, 'can': 1, 'be_useful': 1, 'the': 1}) 

最佳答案

我得到了问题的解决方案,有两个参数我没有处理,应该传递给 Phrases() 模型,它们是

  1. min_count 忽略所有收集的总计数低于此值的单词和二元组。 默认值为 5

  2. 阈值表示形成短语的阈值(越高意味着短语越少)。如果 (cnt(a, b) - min_count) * N/(cnt(a) * cnt(b)) > 阈值,则接受单词 a 和 b 的短语,其中 N 是总词汇量。 默认值为 10.0

对于我上面的带有两个语句的训练数据,阈值是0,所以我更改了训练数据集并添加了这两个参数。

我的新代码

from gensim.models import Phrases
documents = ["the mayor of new york was there", "machine learning can be useful sometimes","new york mayor was present"]

sentence_stream = [doc.split(" ") for doc in documents]
bigram = Phrases(sentence_stream, min_count=1, threshold=2)
sent = [u'the', u'mayor', u'of', u'new', u'york', u'was', u'there']
print(bigram[sent])

输出

[u'the', u'mayor', u'of', u'new_york', u'was', u'there']

Gensim 真的很棒 :)

关于python - 如何使用 gensim 从语料库中提取短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35716121/

相关文章:

python - 如何构建包含双字母的 gensim 字典?

python - 如何使用gensim LDA获取文档的完整主题分布?

python : subclass `type` to create specialized types (e. g。一个 "list of int")

python - NLTK 的 Vader 评分文本示例

java - Stanford Core NLP - 理解共指消解

python - 如何通过重复索引拆分数据帧并进行枚举?

python - 将 CamelCase 导入为小写是否符合 PEP8?

python - 逐字逐句阅读 list ,只读最后的

python - python中如何通过调用__init__方法中的方法来引入对象的属性?

python - 通过 Gensim 查找未见文档的主题