2013-02-22 4 views
12

Mit gensim konnte ich Themen aus einer Reihe von Dokumenten in LSA extrahieren, aber wie greife ich auf die Themen aus den LDA-Modellen?Wie drucke ich die LDA-Themenmodelle von Gensim? Python

Wenn die lda.print_topics(10) Druck der Code gab den folgenden Fehler, weil print_topics() Rückkehr ein 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 

Der Code:

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

Etwas in Ihrem Code fehlt, nämlich corpus_tfidf Berechnung. Würden Sie bitte das verbleibende Stück hinzufügen? – mel

Antwort

14

Nach einigem Herumspielen, wie es scheint, print_topics(numoftopics) für die ldamodel hat einige Fehler. So ist meine Abhilfe print_topic(topicid) zu verwenden:

>>> 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' ist ein Alias ​​für' show_topics' mit den ersten fünf Themen. Schreiben Sie einfach 'lda.show_topics()', no 'print' notwendig. – mac389

6

Sind Sie eine Protokollierung mit? print_topics druckt auf das Logfile wie in der docs angegeben.

Wie @ mac389 sagt lda.show_topics() ist der Weg zu gehen, um Bildschirm zu drucken.

+0

Ich verwende keine Protokollierung, weil ich die Themen sofort verwenden muss. Du hast recht, die 'lda.show_topics()' oder 'lda.print_topic (i)' ist der Weg zu gehen. – alvas

2

Hier ist Beispielcode Themen zu drucken:

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

Ich habe versucht, Ihren Code auszuführen, wo ich die Liste der Liste mit BOW an Text weiterleite. Ich erhalte folgende Fehlermeldung: Typeerror: show_topics() bekam ein unerwartetes 'Themen' Stichwort Argument – mribot

+1

try num_topics. Ich habe den obigen Code korrigiert. –

7

Ich denke, Syntax von show_topics im Laufe der Zeit verändert hat:

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

Für num_topics Reihe von Themen, Rückkehr NUM_WORDS wichtigsten Wörter (10 Wörter pro Thema, standardmäßig).

Die Themen werden als Liste zurückgegeben - eine Liste von Strings, wenn wahr, oder eine Liste von (Wahrscheinlichkeit, Wort) 2-Tupel, wenn falsch formatiert ist.

Wenn log True ist, geben Sie dieses Ergebnis auch zur Protokollierung aus.

Im Gegensatz zu LSA gibt es keine natürliche Ordnung zwischen den Themen in LDA. Die zurückgegebene num_topics < = self.num_topics-Untermenge aller Themen ist daher willkürlich und kann zwischen zwei LDA-Trainingsläufen wechseln.

3

können Sie:

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

Vor kurzem über ein ähnliches Problem kam, während mit Python 3 und GENSIM 2.3.0 arbeiten. print_topics() und show_topics() gaben keinen Fehler, aber auch nichts zu drucken. Stellt sich heraus, dass show_topics() eine Liste zurückgibt. So kann man einfach tun:

topic_list = show_topics() 
print(topic_list)