In [1]:
from string import punctuation
from nltk import RegexpTokenizer
from nltk.stem.porter import PorterStemmer
from nltk.corpus import stopwords
from sklearn.datasets import fetch_20newsgroups
newsgroups = fetch_20newsgroups()
eng_stopwords = set(stopwords.words('english'))
tokenizer = RegexpTokenizer('\s+', gaps=True)
stemmer = PorterStemmer()
translate_tab = {ord(p): u" " for p in punctuation}
def text2tokens(raw_text):
"""
Convert raw test to list of stemmed tokens
"""
clean_text = raw_text.lower().translate(translate_tab)
tokens = [token.strip() for token in tokenizer.tokenize(clean_text)]
tokens = [token for token in tokens if token not in eng_stopwords]
stemmed_tokens = [stemmer.stem(token) for token in tokens]
return filter(lambda token: len(token) > 2, stemmed_tokens) # skip short tokens
dataset = [text2tokens(txt) for txt in newsgroups['data']] # convert a documents to list of tokens
In [2]:
from gensim.corpora import Dictionary
dictionary = Dictionary(documents=dataset, prune_at=None)
dictionary.filter_extremes(no_below=5, no_above=0.3, keep_n=None) # use Dictionary to remove un-relevant tokens
dictionary.compactify()
d2b_dataset = [dictionary.doc2bow(doc) for doc in dataset] # convert list of tokens to bag of word representation
In [3]:
%%time
from gensim.models import LdaMulticore
num_topics = 15
lda_fst = LdaMulticore(corpus=d2b_dataset, num_topics=num_topics,
id2word=dictionary, workers=4, eval_every=None, passes=10, batch=True)
lda_snd = LdaMulticore(corpus=d2b_dataset, num_topics=num_topics,
id2word=dictionary, workers=4, eval_every=None, passes=20, batch=True)
In [4]:
import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode()
def plot_difference(mdiff, title="", annotation=None):
"""
Helper function for plot difference between models
"""
annotation_html = None
if annotation is not None:
annotation_html = [["+++ {}<br>--- {}".format(", ".join(int_tokens),
", ".join(diff_tokens))
for (int_tokens, diff_tokens) in row]
for row in annotation]
data = go.Heatmap(z=mdiff, colorscale='RdBu', text=annotation_html)
layout = go.Layout(width=950, height=950, title=title,
xaxis=dict(title="topic"), yaxis=dict(title="topic"))
py.iplot(dict(data=[data], layout=layout))
In gensim, you can visualise topic different with matrix and annotation. For this purposes, you can use method diff
from LdaModel.
This function return matrix with distances mdiff and matrix with annotations annotation. Read the docstring for more detailed info.
In cells mdiff[i][j] we can see a distance between topic_i from the first model and topic_j from the second model.
In cells annotation[i][j] we can see [tokens from intersection, tokens from difference] between topic_i from first model and topic_j from the second model.
In [5]:
LdaMulticore.diff?
Short description:
In an ideal world, we would like to see different topics decorrelated between themselves. In this case, our matrix would look like this:
In [6]:
mdiff = [[1.] * num_topics for _ in range(num_topics)] # all topics will be decorrelated
for topic_num in range(num_topics):
mdiff[topic_num][topic_num] = 0. # topic_i == topic_i
plot_difference(mdiff, title="Topic difference (one model) in ideal world")
Unfortunately, in real life, not everything is so good, and the matrix looks different.
Short description (annotations):
In [7]:
mdiff, annotation = lda_fst.diff(lda_fst, distance='jaccard', num_words=50)
plot_difference(mdiff, title="Topic difference (one model) [jaccard distance]", annotation=annotation)
If you compare a model with itself, you want to see as many red elements as possible (except diagonal). With this picture, you can look at the not very red elements and understand which topics in the model are very similar and why (you can read annotation if you move your pointer to cell).
Jaccard is stable and robust distance function, but this function not enough sensitive for some purposes. Let's try to use Hellinger distance now.
In [8]:
mdiff, annotation = lda_fst.diff(lda_fst, distance='hellinger', num_words=50)
plot_difference(mdiff, title="Topic difference (one model)[hellinger distance]", annotation=annotation)
You see that everything has become worse, but remember that everything depends on the task.
You need to choose the function with which your personal point of view about topics similarity and your task (from my experience, Jaccard is fine).
Sometimes, we want to look at the patterns between two different models and compare them.
You can do this by constructing a matrix with the difference
In [9]:
mdiff, annotation = lda_fst.diff(lda_snd, distance='jaccard', num_words=50)
plot_difference(mdiff, title="Topic difference (two models)[jaccard distance]", annotation=annotation)
Looking at this matrix, you can find similar and different topics (and relevant tokens which describe the intersection and difference)