2013-02-22 28 views
12

Utilizzo di gensim Sono stato in grado di estrarre argomenti da un set di documenti in LSA ma come accedere agli argomenti generati dai modelli LDA?Come stampare i modelli di argomenti LDA da gensim? Python

Quando si stampa il lda.print_topics(10) il codice ha dato il seguente errore perché print_topics() ritorno un NoneType:

Traceback (most recent call last): 
    File "/home/alvas/workspace/XLINGTOP/xlingtop.py", line 93, in <module> 
    for top in lda.print_topics(2): 
TypeError: 'NoneType' object is not iterable 

Il codice:

from gensim import corpora, models, similarities 
from gensim.models import hdpmodel, ldamodel 
from itertools import izip 

documents = ["Human machine interface for lab abc computer applications", 
       "A survey of user opinion of computer system response time", 
       "The EPS user interface management system", 
       "System and human system engineering testing of EPS", 
       "Relation of user perceived response time to error measurement", 
       "The generation of random binary unordered trees", 
       "The intersection graph of paths in trees", 
       "Graph minors IV Widths of trees and well quasi ordering", 
       "Graph minors A survey"] 

# remove common words and tokenize 
stoplist = set('for a of the and to in'.split()) 
texts = [[word for word in document.lower().split() if word not in stoplist] 
     for document in documents] 

# remove words that appear only once 
all_tokens = sum(texts, []) 
tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1) 
texts = [[word for word in text if word not in tokens_once] 
     for text in texts] 

dictionary = corpora.Dictionary(texts) 
corpus = [dictionary.doc2bow(text) for text in texts] 

# I can print out the topics for LSA 
lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2) 
corpus_lsi = lsi[corpus] 

for l,t in izip(corpus_lsi,corpus): 
    print l,"#",t 
print 
for top in lsi.print_topics(2): 
    print top 

# I can print out the documents and which is the most probable topics for each doc. 
lda = ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=50) 
corpus_lda = lda[corpus] 

for l,t in izip(corpus_lda,corpus): 
    print l,"#",t 
print 

# But I am unable to print out the topics, how should i do it? 
for top in lda.print_topics(10): 
    print top 
+0

Manca qualcosa nel codice, vale a dire corpus_tfidf computation. Vorresti aggiungere il pezzo rimanente? – mel

risposta

14

Dopo un po 'fare in giro, sembra che print_topics(numoftopics) per la ldamodel ha qualche bug Così la mia soluzione è utilizzare print_topic(topicid):

>>> print lda.print_topics() 
None 
>>> for i in range(0, lda.num_topics-1): 
>>> print lda.print_topic(i) 
0.083*response + 0.083*interface + 0.083*time + 0.083*human + 0.083*user + 0.083*survey + 0.083*computer + 0.083*eps + 0.083*trees + 0.083*system 
... 
+4

'print_topics' è un alias per' show_topics' con i primi cinque argomenti. Basta scrivere 'lda.show_topics()', non è necessario 'print'. – mac389

6

Stai usando qualsiasi registrazione? print_topics stampa nel file di registro come indicato nello docs.

Come dice @ mac389, lda.show_topics() è la via da percorrere per stampare sullo schermo.

+0

Non sto usando alcuna registrazione perché ho bisogno di usare immediatamente gli argomenti. hai ragione, il 'lda.show_topics()' o 'lda.print_topic (i)' è la strada da percorrere. – alvas

2

Ecco il codice di esempio per stampare gli argomenti:

def ExtractTopics(filename, numTopics=5): 
    # filename is a pickle file where I have lists of lists containing bag of words 
    texts = pickle.load(open(filename, "rb")) 

    # generate dictionary 
    dict = corpora.Dictionary(texts) 

    # remove words with low freq. 3 is an arbitrary number I have picked here 
    low_occerance_ids = [tokenid for tokenid, docfreq in dict.dfs.iteritems() if docfreq == 3] 
    dict.filter_tokens(low_occerance_ids) 
    dict.compactify() 
    corpus = [dict.doc2bow(t) for t in texts] 
    # Generate LDA Model 
    lda = models.ldamodel.LdaModel(corpus, num_topics=numTopics) 
    i = 0 
    # We print the topics 
    for topic in lda.show_topics(num_topics=numTopics, formatted=False, topn=20): 
     i = i + 1 
     print "TopiC#" + str(i) + ":", 
     for p, id in topic: 
      print dict[int(id)], 

     print "" 
+0

Ho provato a eseguire il codice in cui passo l'elenco di liste che contengono BOW in testo. Ottengo il seguente errore: TypeError: show_topics() ha ottenuto un argomento di parole chiave inattese 'topics' – mribot

+1

try num_topics. Ho corretto il codice sopra. –

7

penso sintassi del show_topics è cambiato nel tempo:

show_topics(num_topics=10, num_words=10, log=False, formatted=True) 

Per num_topics certo numero di argomenti, tornare NUM_WORDS parole più significative (10 parole per argomento, per impostazione predefinita).

Gli argomenti vengono restituiti come un elenco: un elenco di stringhe se formattato è Vero o un elenco di (2) tuple (probabilità, parola) se False.

Se log è True, anche questo risultato viene emesso per registrare.

A differenza di LSA, non esiste un ordinamento naturale tra gli argomenti in LDA. Il num_topics restituito < = il sottoinsieme self.num_topics di tutti gli argomenti è quindi arbitrario e può cambiare tra due esecuzioni di allenamento LDA.

3

è possibile utilizzare:

for i in lda_model.show_topics(): 
    print i[0], i[1] 
0

Recentemente, mi sono imbattuto in un problema simile mentre si lavora con Python 3 e Gensim 2.3.0. print_topics() e show_topics() non davano alcun errore ma non stampavano nulla. Risulta che show_topics() restituisce una lista. Quindi si può semplicemente fare:

topic_list = show_topics() 
print(topic_list) 
Problemi correlati