Печатать биграммы с помощью gensim

Я хочу выучить биграммы из корпуса, используя генсим, а затем просто распечатать изученные биграммы. Я не видел пример, который делает это. помощь оценена

from gensim.models import Phrases
documents = ["the mayor of new york was there", "human computer interaction and machine learning has now become a trending research area","human computer interaction is interesting","human computer interaction is a pretty interesting subject", "human computer interaction is a great and new subject", "machine learning can be useful sometimes","new york mayor was present", "I love machine learning because it is a new subject area", "human computer interaction helps people to get user friendly applications"]
sentence_stream = [doc.split(" ") for doc in documents]

bigram = Phrases(sentence_stream)

# how can I print all bigrams learned and just the bigrams, including "new_york" and "human computer" ?enter code here

3 ответа

Ответ OP будет работать, если вы тренируете модель с помощью класса Phrasesкак уже упоминалось, и печать биграмм без сохранения модели. Это не сработает, если вы сохраните модель, а затем снова загрузите ее в будущем. Когда вы загружаете модель после сохранения, вам нужно будет использоватьPhraser класс следующим образом:

from gensim.models.phrases import Phraser

а затем загрузите модель:

bigram_model = Phraser.load('../../whatever_bigram_model')

Затем, если вы используете следующий метод в качестве ответа упомянутого OP, т.е.

Ответ от OP

import operator
sorted(
    {k:v for k,v in bigram_model.vocab.items() if b'_' in k if v>=bigram_model.min_count}.items(),
    key=operator.itemgetter(1),
    reverse=True)

Вы получите сообщение об ошибке:

AttributeError: 'Phraser' object has no attribute 'vocab'

Решение

Обойти это можно с помощью следующего кода:

for bigram in bigram_model.phrasegrams.keys():
    print(bigram)

Выход:

(b'word1', b'word2')
(b'word3', b'word4')

Это решение работает в обеих ситуациях, для постоянной и непостоянной модели, в примере, приведенном OP, модифицированная версия моего решения, которая работает:

for ngrams, _ in bigram.vocab.items():
    unicode_ngrams = ngrams.decode('utf-8')
    if '_' in unicode_ngrams:
        print(unicode_ngrams)

Дает:

the_mayor
mayor_of
of_new
new_york
york_was
was_there
human_computer
computer_interaction
interaction_and
and_machine
machine_learning
learning_has
has_now
now_become

В выводе есть еще кое-что, но я его обрезал, в интересах длины этого ответа

Надеюсь, мой ответ внесет ясность.

Вдохновленный комментариями gojomo. Вот полное решение.

      from gensim.models.phrases import Phrases, pseudocorpus

documents = ["the mayor of new york was there",
             "human computer interaction and machine learning has now become a trending research area",
             "human computer interaction is interesting","human computer interaction is a pretty interesting subject",
             "human computer interaction is a great and new subject",
             "machine learning can be useful sometimes",
             "new york mayor was present",
             "i love machine learning because it is a new subject area",
             "human computer interaction helps people to get user friendly applications"]

sentence_stream = [doc.split(" ") for doc in documents]

def get_all_bigrams(bigram_model):
    corpus =  pseudocorpus(bigram_model.vocab, bigram_model.delimiter, bigram_model.common_terms)
    bigrams = []
    for bigram, score in bigram_model.export_phrases(corpus, bigram_model.delimiter, as_tuples=False):     
        if score >= bigram_model.threshold:
            bigrams.append(bigram.decode('utf-8'))
    return bigrams

bigram = Phrases(sentence_stream, min_count=1)
bigrams = get_all_bigrams(bigram)
print(bigrams)
['new_york', 'human_computer', 'computer_interaction', 'machine_learning', 'is_a']
import operator
sorted(
    {k:v for k,v in bigram.vocab.items() if b'_' in k if v>=bigram.min_count}.items(),
    key=operator.itemgetter(1),
    reverse=True)
Другие вопросы по тегам