2016-03-01 98 views
14

对于语料库的预处理,我打算从语料库中提取常用短语,为此我尝试使用短语 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'] 

但是,当我竭力试图o打印列车数据的词汇表,我可以看到bigram,但是它没有与测试数据一起工作,哪里出错了?

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}) 

回答

17

我得到了问题的解决方案,有两个参数我没有照顾它应传递给词()模型,这些都是

  1. min_count忽略总收集数低于此的所有单词和双字母。 Bydefault它值是5

  2. 表示用于形成短语(较高意味着更少的词组)的阈值。如果(cnt(a,b)-min_count)* N /(cnt(a)* cnt(b))>阈值,则接受单词a和b的短语,其中N是总词汇量大小。 Bydefault它值是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是真正真棒:)

+1

比你的宝贵答案。但在这个例子中,bigram并没有把“machine”,“learning”作为“machine_learning”。你知道为什么会发生吗? – 2017-09-10 05:16:56

+1

如果在训练两次之前在句子中添加“机器学习”,然后将其添加到发送的变量中,您将获得“machine_learning”。如果它看不到这一对的频率,那么它不会直观地知道。 – ethanenglish

相关问题