2013-11-17 3 views
1

Я смотрю на потенциальных путях только сохранение частот триграмм в памяти и вычислении Юниграммы и Биграммные частот на лета следующим образом:Сформировать юниграммы и биграммы из списка триграмма

дан триграммы U, V , ш: (., V, W)

графа (V, W) = сумма т.е. сумма по всем ¯u

Аналогично, граф (ш) = сумма

В этом уверен (, ш.) приводит к появлению нескольких недостающих униграмм, например маркер начала предложения, но делает ли это звук как действительный подход к созданию униграмм и биграмм?

ответ

3

Да. Это будет работать. Вы можете проверить это, сделав себе крошечный корпус и вручную сделав подсчет, чтобы убедиться, что он выходит так же.

from collections import Counter 

corpus = [['the','dog','walks'], ['the','dog','runs'], ['the','cat','runs']] 
corpus_with_ends = [['<s>','<s>'] + s + ['<e>'] for s in corpus] 

trigram_counts = Counter(trigram for s in corpus_with_ends for trigram in zip(s,s[1:],s[2:])) 

unique_bigrams = set((b,c) for a,b,c in trigram_counts) 
bigram_counts = dict((bigram,sum(count for trigram,count in trigram_counts.iteritems() if trigram[1:] == bigram)) for bigram in unique_bigrams) 

unique_unigrams = set((c,) for a,b,c in trigram_counts if c != '<e>') 
unigram_counts = dict((unigram,sum(count for trigram,count in trigram_counts.iteritems() if trigram[2:] == unigram)) for unigram in unique_unigrams) 

Теперь вы можете проверить вещи:

>>> true_bigrams = [bigram for s in corpus_with_ends for bigram in zip(s[1:],s[2:])] 
>>> true_bigram_counts = Counter(true_bigrams) 
>>> bigram_counts == true_bigram_counts 
True 

>>> true_unigrams = [(unigram,) for s in corpus_with_ends for unigram in s[2:-1]] 
>>> true_unigram_counts = Counter(true_unigrams) 
>>> unigram_counts == true_unigram_counts 
True 
Смежные вопросы