{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "# Dynamic Topic Models Tutorial" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### What is this tutorial about?\n", "This tutorial will exaplin what Dynamic Topic Models are, and how to use them using the LdaSeqModel class of gensim. I will start with some theory and already documented examples, before moving on to an example run of Dynamic Topic Model on a sample dataset. I will also do an comparison between the python code and the already present gensim wrapper, and illustrate how to easily visualise them and do topic coherence with DTM. Any suggestions to improve documentation or code through PRs/Issues is always appreciated!\n", "\n", "\n", "### Why Dynamic Topic Models?\n", "Imagine you have a gigantic corpus which spans over a couple of years. You want to find semantically similar documents; one from the very beginning of your time-line, and one in the very end. How would you?\n", "This is where Dynamic Topic Models comes in. By having a time-based element to topics, context is preserved while key-words may change.\n", "\n", "David Blei does a good job explaining the theory behind this in this [Google talk](https://www.youtube.com/watch?v=7BMsuyBPx90). If you prefer to directly read the [paper on DTM by Blei and Lafferty](http://repository.cmu.edu/cgi/viewcontent.cgi?article=2036&context=compsci), that should get you upto speed too.\n", "\n", "In his talk, Blei gives a very interesting example of the motivation to use DTM. After running DTM on a dataset of the Science Journal from 1880 onwards, he picks up [this](http://science.sciencemag.org/content/os-1/28/326) paper - The Brain of the Orang (1880). It's topics are concentrated on a topic which must be to do with Monkeys, and with Neuroscience or brains. \n", "\n", "\n", "\n", "He goes ahead to pick up another paper with likely very less common words, but in the same context - analysing monkey brains. In fact, this one is called - \"[Representation of the visual field on the medial wall of occipital-parietal cortex in the owl monkey](http://allmanlab.caltech.edu/PDFs/AllmanKaas1976.pdf)\". Quite the title, eh? Like mentioned before, you wouldn't imagine too many common words in these two papers, about a 100 years apart.\n", "\n", "\n", "\n", "\n", "But a Hellinger Distance based Document-Topic distribution gives a very high similarity value! The same topics evolved smoothly over time and the context remains. A document similarity match using other traditional techniques might not work very well on this!\n", "Blei defines this technique as - \"Time corrected Document Similarity\".\n", "\n", "Another obviously useful analysis is to see how words in a topic change over time. The same broad classified topic starts looking more 'mature' as time goes on. This image illustrates an example from the same paper linked to above.\n", "\n", "\n", "\n", "#### So, briefly put : \n", "\n", "Dynamic Topic Models are used to model the evolution of topics in a corpus, over time. The Dynamic Topic Model is part of a class of probabilistic topic models, like the LDA. \n", "\n", "While most traditional topic mining algorithms do not expect time-tagged data or take into account any prior ordering, Dynamic Topic Models (DTM) leverages the knowledge of different documents belonging to a different time-slice in an attempt to map how the words in a topic change over time.\n", "\n", "[This](http://rare-technologies.com/understanding-and-coding-dynamic-topic-models/) blog post is also useful in breaking down the ideas and theory behind DTM.\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Motivation to code this!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But - why even undertake this, especially when Gensim itself have a wrapper?\n", "The main motivation was the lack of documentation in the original code - and the fact that doing an only python version makes it easier to use gensim building blocks. For example, for setting up the Sufficient Statistics to initialize the DTM, you can just pass a pre-trained gensim LDA model!\n", "\n", "There is some clarity on how they built their code now - Variational Inference using Kalman Filters, as described in section 3 of the paper. The mathematical basis for the code is well described in the appendix of the paper. If the documentation is lacking or not clear, comments via Issues or PRs via the gensim repo would be useful in improving the quality.\n", "\n", "This project was part of the Google Summer of Code 2016 program: I have been regularly blogging about my progress with implementing this, which you can find [here](http://rare-technologies.com/author/bhargav/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Using LdaSeqModel for DTM" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Gensim already has a wrapper for original C++ DTM code, but the `LdaSeqModel` class is an effort to have a pure python implementation of the same.\n", "Using it is very similar to using any other gensim topic-modelling algorithm, with all you need to start is an iterable gensim corpus, id2word and a list with the number of documents in each of your time-slices." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# setting up our imports\n", "\n", "from gensim.models import ldaseqmodel\n", "from gensim.corpora import Dictionary, bleicorpus\n", "import numpy\n", "from gensim.matutils import hellinger" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We will be loading the corpus and dictionary from disk. Here our corpus in the Blei corpus format, but it can be any iterable corpus.\n", "The data set here consists of news reports over 3 months (March, April, May) downloaded from here and cleaned. \n", "\n", "TODO: better, more interesting data-set.\n", "\n", "### What is a time-slice?\n", "A very important input for DTM to work is the `time_slice` input. It should be a list which contains the number of documents in each time-slice. In our case, the first month had 438 articles, the second 430 and the last month had 456 articles. This means we'd need an input which looks like this: `time_slice = [438, 430, 456]`. \n", "Technically, a time-slice can be a month, year, or any way you wish to split up the number of documents in your corpus, time-based.\n", "\n", "Once you have your corpus, id2word and time_slice ready, we're good to go!" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# loading our corpus and dictionary\n", "dictionary = Dictionary.load('Corpus/news_dictionary')\n", "corpus = bleicorpus.BleiCorpus('Corpus/news_corpus')\n", "# it's very important that your corpus is saved in order of your time-slices!\n", "\n", "time_slice = [438, 430, 456]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For DTM to work it first needs the Sufficient Statistics from a trained LDA model on the _*same*_ dataset. \n", "By default LdaSeqModel trains it's own model and passes those values on, but can also accept a pre-trained gensim LDA model, or a numpy matrix which contains the Suff Stats.\n", "\n", "We will be training our model in default mode, so gensim LDA will be first trained on the dataset.\n", "\n", "NOTE: You have to set logging as true to see your progress!" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [], "source": [ "ldaseq = ldaseqmodel.LdaSeqModel(corpus=corpus, id2word=dictionary, time_slice=time_slice, num_topics=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that our model is trained, let's see what our results look like.\n", "\n", "### Results\n", "Much like LDA, the points of interest would be in what the topics are and how the documents are made up of these topics.\n", "In DTM we have the added interest of seeing how these topics evolve over time.\n", "\n", "Let's go through some of the functions to print Topics and analyse documents.\n", "\n", "### Printing Topics\n", "\n", "To print all topics from a particular time-period, simply use `print_topics`. \n", "The input parameter to `print_topics` is a time-slice option. By passing `0` we are seeing the topics in the 1st time-slice. \n", "\n", "The result would be a list of lists, where each individual list contains a tuple of the most probable words in the topic. i.e `(word, word_probability)`" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[[('last', 0.0030000000000000001),\n", " ('market', 0.0030000000000000001),\n", " ('year', 0.0030000000000000001),\n", " ('firm', 0.0030000000000000001),\n", " ('use', 0.0030000000000000001),\n", " ('net', 0.002),\n", " ('company', 0.002),\n", " ('information', 0.002),\n", " ('growth', 0.002),\n", " ('bank', 0.002),\n", " ('oil', 0.002),\n", " ('firms', 0.002),\n", " ('economic', 0.002),\n", " ('search', 0.002),\n", " ('much', 0.002),\n", " ('sales', 0.002),\n", " ('economy', 0.002),\n", " ('prices', 0.002),\n", " ('government', 0.002),\n", " ('european', 0.002)],\n", " [('music', 0.0060000000000000001),\n", " ('best', 0.0040000000000000001),\n", " ('show', 0.0040000000000000001),\n", " ('last', 0.0040000000000000001),\n", " ('uk', 0.0040000000000000001),\n", " ('number', 0.0030000000000000001),\n", " ('top', 0.0030000000000000001),\n", " ('first', 0.0030000000000000001),\n", " ('tv', 0.0030000000000000001),\n", " ('band', 0.0030000000000000001),\n", " ('bbc', 0.0030000000000000001),\n", " ('like', 0.002),\n", " ('album', 0.002),\n", " ('song', 0.002),\n", " ('british', 0.002),\n", " ('three', 0.002),\n", " ('make', 0.002),\n", " ('police', 0.002),\n", " ('singer', 0.002),\n", " ('year', 0.002)],\n", " [('club', 0.0050000000000000001),\n", " ('game', 0.0040000000000000001),\n", " ('chelsea', 0.0040000000000000001),\n", " ('united', 0.0040000000000000001),\n", " ('players', 0.0040000000000000001),\n", " ('league', 0.0040000000000000001),\n", " ('last', 0.0030000000000000001),\n", " ('cup', 0.0030000000000000001),\n", " ('arsenal', 0.0030000000000000001),\n", " ('think', 0.0030000000000000001),\n", " ('first', 0.0030000000000000001),\n", " ('football', 0.0030000000000000001),\n", " ('play', 0.0030000000000000001),\n", " ('manchester', 0.0030000000000000001),\n", " ('win', 0.0030000000000000001),\n", " ('time', 0.0030000000000000001),\n", " ('manager', 0.0030000000000000001),\n", " ('good', 0.0030000000000000001),\n", " ('like', 0.0030000000000000001),\n", " ('liverpool', 0.0030000000000000001)],\n", " [('film', 0.0080000000000000002),\n", " ('best', 0.0070000000000000001),\n", " ('mobile', 0.0060000000000000001),\n", " ('games', 0.0040000000000000001),\n", " ('million', 0.0040000000000000001),\n", " ('phone', 0.0040000000000000001),\n", " ('broadband', 0.0030000000000000001),\n", " ('uk', 0.0030000000000000001),\n", " ('technology', 0.0030000000000000001),\n", " ('director', 0.0030000000000000001),\n", " ('video', 0.0030000000000000001),\n", " ('phones', 0.0030000000000000001),\n", " ('first', 0.0030000000000000001),\n", " ('last', 0.0030000000000000001),\n", " ('game', 0.002),\n", " ('number', 0.002),\n", " ('according', 0.002),\n", " ('films', 0.002),\n", " ('award', 0.002),\n", " ('actor', 0.002)],\n", " [('government', 0.0060000000000000001),\n", " ('blair', 0.0050000000000000001),\n", " ('labour', 0.0050000000000000001),\n", " ('minister', 0.0040000000000000001),\n", " ('prime', 0.0030000000000000001),\n", " ('public', 0.0030000000000000001),\n", " ('party', 0.0030000000000000001),\n", " ('election', 0.0030000000000000001),\n", " ('says', 0.0030000000000000001),\n", " ('home', 0.0030000000000000001),\n", " ('security', 0.0030000000000000001),\n", " ('make', 0.0030000000000000001),\n", " ('say', 0.0030000000000000001),\n", " ('brown', 0.0030000000000000001),\n", " ('bbc', 0.0030000000000000001),\n", " ('howard', 0.0030000000000000001),\n", " ('lord', 0.0030000000000000001),\n", " ('plans', 0.002),\n", " ('tory', 0.002),\n", " ('secretary', 0.002)]]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ldaseq.print_topics(time=0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can see 5 different fairly well defined topics:\n", "1. Economy\n", "2. Entertainment\n", "3. Football\n", "4. Technology and Entertainment\n", "5. Government" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Looking for Topic Evolution\n", "\n", "To fix a topic and see it evolve, use `print_topic_times`.\n", "The input parameter is the `topic_id`\n", "In this case, we are looking at the evolution of the technology topic." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you look at the lower frequencies; the word \"may\" is creeping itself into prominence. This makes sense, as the 3rd time-slice are news reports about the economy in the month of may. This isn't present at all in the first time-slice because it's still March!\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[[('last', 0.0030000000000000001),\n", " ('market', 0.0030000000000000001),\n", " ('year', 0.0030000000000000001),\n", " ('firm', 0.0030000000000000001),\n", " ('use', 0.0030000000000000001),\n", " ('net', 0.002),\n", " ('company', 0.002),\n", " ('information', 0.002),\n", " ('growth', 0.002),\n", " ('bank', 0.002),\n", " ('oil', 0.002),\n", " ('firms', 0.002),\n", " ('economic', 0.002),\n", " ('search', 0.002),\n", " ('much', 0.002),\n", " ('sales', 0.002),\n", " ('economy', 0.002),\n", " ('prices', 0.002),\n", " ('government', 0.002),\n", " ('european', 0.002)],\n", " [('market', 0.0030000000000000001),\n", " ('last', 0.0030000000000000001),\n", " ('year', 0.0030000000000000001),\n", " ('firm', 0.0030000000000000001),\n", " ('use', 0.0030000000000000001),\n", " ('company', 0.002),\n", " ('growth', 0.002),\n", " ('net', 0.002),\n", " ('information', 0.002),\n", " ('economic', 0.002),\n", " ('firms', 0.002),\n", " ('bank', 0.002),\n", " ('oil', 0.002),\n", " ('search', 0.002),\n", " ('much', 0.002),\n", " ('sales', 0.002),\n", " ('economy', 0.002),\n", " ('prices', 0.002),\n", " ('european', 0.002),\n", " ('may', 0.002)],\n", " [('market', 0.0030000000000000001),\n", " ('last', 0.0030000000000000001),\n", " ('year', 0.0030000000000000001),\n", " ('firm', 0.0030000000000000001),\n", " ('use', 0.0030000000000000001),\n", " ('information', 0.0030000000000000001),\n", " ('net', 0.0030000000000000001),\n", " ('company', 0.002),\n", " ('growth', 0.002),\n", " ('firms', 0.002),\n", " ('search', 0.002),\n", " ('economic', 0.002),\n", " ('much', 0.002),\n", " ('oil', 0.002),\n", " ('bank', 0.002),\n", " ('economy', 0.002),\n", " ('sales', 0.002),\n", " ('may', 0.002),\n", " ('european', 0.002),\n", " ('however,', 0.002)]]" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ldaseq.print_topic_times(topic=0) # evolution of 1st topic" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Document - Topic Proportions\n", "the function `doc_topics` checks the topic proportions on documents already trained on. It accepts the document number in the corpus as an input.\n", "\n", "Let's pick up document number 558 arbitrarily and have a look." ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['set', 'time,\"', 'chairman', 'decision', 'news', 'director', 'former', 'vowed', '\"it', 'results', 'club', 'third', 'home', 'paul', 'saturday.', 'south', 'conference', 'leading', '\"some', 'survival', 'needed', 'coach', \"don't\", 'every', 'trouble', 'desperate', 'eight', 'first', 'win', 'going', 'park', 'near', 'chance', 'manager', 'league', 'milan', 'games', 'go', 'game', 'foot', 'say', 'upset', \"i'm\", 'poor', 'season.', 'executive', 'road', '24', 'debut', 'portsmouth.', 'give', 'claiming', 'steve', 'break', 'rivals', 'boss', 'kevin', 'premiership', 'little', 'left', 'table.', 'life', 'join', 'years.', 'bring', 'season,', 'director.', 'became', 'st', 'according', 'official', 'hope', 'shocked', 'though', 'phone', 'charge', '14', 'website.', 'time,', 'claimed', 'kept', 'bond', 'appointment', 'unveil', 'november', 'picked', 'confirmed,', 'believed', 'deep', 'position', 'surprised', 'negotiations', 'talks', 'gmt', 'middlesbrough', 'replaced', 'appear', 'football,', '\"i\\'m', 'charge.', 'saints', 'southampton', 'sturrock', 'wednesday.', 'harry', 'poised', 'ninth', 'quit', 'relieved', 'chance.\"', 'decision.\"', 'hero', 'redknapp,', 'redknapp', \"saints'\", 'first-team', \"wouldn't\", \"mary's.\", 'portsmouth', \"redknapp's\", 'pompey', 'academy', \"harry's\", 'cult', 'rupert', 'time\".', 'coast', '57,', 'succeed', 'duties', \"'i\", 'bitter,', \"mandaric's\", \"portsmouth's\", 'wigley,', 'wigley', \"southampton',\", '1500', 'mandaric', \"'absolutely\", 'lowe', '\"disappointed\"', 'velimir', 'not\\',\"', 'disgusted', 'disappointed,', 'mandaric,', 'fratton', 'replaces', 'masterminding', 'angry,', 'vowed:', 'informed.\"', 'zajec']\n" ] } ], "source": [ "# to check Document - Topic proportions, use `doc-topics`\n", "words = [dictionary[word_id] for word_id, count in corpus[558]]\n", "print (words)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It's pretty clear that it's a news article about football. What topics will it likely be comprised of?" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 5.46298825e-05 5.46298825e-05 9.32273855e-01 6.75622555e-02\n", " 5.46298825e-05]\n" ] } ], "source": [ "doc = ldaseq.doc_topics(558) # check the 558th document in the corpuses topic distribution\n", "print (doc)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's look at our topics as desribed by us, again:\n", "\n", "1. Economy\n", "2. Entertainment\n", "3. Football\n", "4. Technology and Entertainment\n", "5. Government\n", "\n", "Our topic distribution for the above document is largely in topics 3 and 4. Considering it is a document about a news article on a football match, the distribution makes perfect sense!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If we wish to analyse a document not in our training set, we can use simply pass the doc to the model similar to the `__getitem__` funciton for `LdaModel`.\n", "\n", "Let's let our document be a hypothetical news article about the effects of Ryan Giggs buying mobiles affecting the British economy." ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[ 0.40632917 0.00110497 0.3465658 0.24489509 0.00110497]\n" ] } ], "source": [ "doc_football_1 = ['economy', 'bank', 'mobile', 'phone', 'markets', 'buy', 'football', 'united', 'giggs']\n", "doc_football_1 = dictionary.doc2bow(doc_football_1)\n", "doc_football_1 = ldaseq[doc_football_1]\n", "print (doc_football_1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Pretty neat! Topic 1 is about the Economy, and this document also has traces of football and technology, so topics 1, 3, and 4 got correctly activated." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Distances between documents\n", "\n", "One of the more handy uses of DTMs topic modelling is that we can compare documents across different time-frames and see how similar they are topic-wise. When words may not necessarily overlap over these time-periods, this is very useful.\n", "\n", "The current dataset doesn't provide us the diversity for this to be an effective example; but we will nevertheless illustrate how to do the same.\n", "\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": true }, "outputs": [], "source": [ "doc_football_2 = ['arsenal', 'fourth', 'wenger', 'oil', 'middle', 'east', 'sanction', 'fluctuation']\n", "doc_football_2 = dictionary.doc2bow(doc_football_2)\n", "doc_football_2 = ldaseq[doc_football_2]" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "0.35085394585966118" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hellinger(doc_football_1, doc_football_2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The topic distributions are quite related - matches well in football and economy." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let's try with documents that shouldn't be similar." ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "0.95132142484351623" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "doc_governemt_1 = ['tony', 'government', 'house', 'party', 'vote', 'european', 'official', 'house']\n", "doc_governemt_1 = dictionary.doc2bow(doc_governemt_1)\n", "doc_governemt_1 = ldaseq[doc_governemt_1]\n", "\n", "hellinger(doc_football_1, doc_governemt_1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As expected, the value is very high, meaning the topic distributions are far apart.\n", "\n", "For more information on how to use the gensim distance metrics, check out [this notebook](https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/distance_metrics.ipynb)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Performance\n", "\n", "The code currently runs between 5 to 7 times slower than the original C++ DTM code. The bottleneck is in the scipy `optimize.fmin_cg` method for updating obs. Speeding this up would fix things up!\n", "\n", "Since it uses iterable gensim corpuses, the memory stamp is also cleaner. \n", "\n", "TODO: check memory, check BLAS, see how performance can be improved memory and speed wise. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The advantages of the python port are that unlike the C++ code we needn't treat it like a black-box; PRs to help make the code better are welcomed, as well as help to make the documentation clearer and improve performance. It is also in pure python and doesn't need any dependancy outside of what gensim already needs. The added functionality of being able to analyse new documents is also a plus!\n", "\n", "## Choosing your best Dynamic Topic Model.\n", "\n", "Like we've been going on and on before, the advantage in having a python port is the transparency with which you can train your DTM.\n", "We'll go over two key ideas: changing variance, and changing suff stats.\n", "\n", "\n", "### Chain Variance\n", "One of the key aspects of topic evolution is how fast/slow these topics evolve. And this is where the factor of `variance` comes in.\n", "By setting the `chain_variance` input to the DTM model higher, we can tweak our topic evolution.\n", "The default value is 0.005. (this is the value suggested by Blei in his tech talk and is the default value in the C++ code)\n", "\n", "Let us see a small example illustrating the same.\n", "Let's first see the evolution of values for the first time-slice." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[[('music', 0.0060000000000000001),\n", " ('best', 0.0040000000000000001),\n", " ('show', 0.0040000000000000001),\n", " ('last', 0.0040000000000000001),\n", " ('uk', 0.0040000000000000001),\n", " ('number', 0.0030000000000000001),\n", " ('top', 0.0030000000000000001),\n", " ('first', 0.0030000000000000001),\n", " ('tv', 0.0030000000000000001),\n", " ('band', 0.0030000000000000001),\n", " ('bbc', 0.0030000000000000001),\n", " ('like', 0.002),\n", " ('album', 0.002),\n", " ('song', 0.002),\n", " ('british', 0.002),\n", " ('three', 0.002),\n", " ('make', 0.002),\n", " ('police', 0.002),\n", " ('singer', 0.002),\n", " ('year', 0.002)],\n", " [('music', 0.0060000000000000001),\n", " ('best', 0.0040000000000000001),\n", " ('show', 0.0040000000000000001),\n", " ('number', 0.0040000000000000001),\n", " ('last', 0.0040000000000000001),\n", " ('uk', 0.0040000000000000001),\n", " ('top', 0.0030000000000000001),\n", " ('first', 0.0030000000000000001),\n", " ('tv', 0.0030000000000000001),\n", " ('band', 0.0030000000000000001),\n", " ('bbc', 0.0030000000000000001),\n", " ('album', 0.002),\n", " ('like', 0.002),\n", " ('song', 0.002),\n", " ('british', 0.002),\n", " ('three', 0.002),\n", " ('make', 0.002),\n", " ('singer', 0.002),\n", " ('police', 0.002),\n", " ('year', 0.002)],\n", " [('music', 0.0060000000000000001),\n", " ('best', 0.0040000000000000001),\n", " ('show', 0.0040000000000000001),\n", " ('number', 0.0040000000000000001),\n", " ('last', 0.0040000000000000001),\n", " ('uk', 0.0040000000000000001),\n", " ('tv', 0.0030000000000000001),\n", " ('top', 0.0030000000000000001),\n", " ('band', 0.0030000000000000001),\n", " ('first', 0.0030000000000000001),\n", " ('bbc', 0.0030000000000000001),\n", " ('song', 0.0030000000000000001),\n", " ('album', 0.002),\n", " ('like', 0.002),\n", " ('british', 0.002),\n", " ('three', 0.002),\n", " ('make', 0.002),\n", " ('singer', 0.002),\n", " ('record', 0.002),\n", " ('rock', 0.002)]]" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ldaseq.print_topic_times(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let us do the same, but after increasing the `chain_variance` value." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Users/bhargavvader/Open_Source/gensim/gensim/models/ldaseqmodel.py:217: RuntimeWarning: divide by zero encountered in double_scalars\n", " convergence = numpy.fabs((bound - old_bound) / old_bound)\n" ] } ], "source": [ "ldaseq_chain = ldaseqmodel.LdaSeqModel(corpus=corpus, id2word=dictionary, time_slice=time_slice, num_topics=5, chain_variance=0.05)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It's noticable that the values are moving more freely after increasing the chain_variance. Film went from highest probability to 5th to 8th!" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[[('film', 0.012),\n", " ('last', 0.0040000000000000001),\n", " ('number', 0.0040000000000000001),\n", " ('top', 0.0030000000000000001),\n", " ('yukos', 0.0030000000000000001),\n", " ('uk', 0.0030000000000000001),\n", " ('court', 0.0030000000000000001),\n", " ('first', 0.002),\n", " ('russian', 0.002),\n", " ('box', 0.002),\n", " ('company', 0.002),\n", " ('deal', 0.002),\n", " ('sale', 0.002),\n", " ('three', 0.002),\n", " ('sales', 0.002),\n", " ('sold', 0.002),\n", " ('oil', 0.002),\n", " ('group', 0.002),\n", " ('director', 0.002),\n", " ('firm', 0.002)],\n", " [('number', 0.0050000000000000001),\n", " ('last', 0.0040000000000000001),\n", " ('uk', 0.0040000000000000001),\n", " ('top', 0.0040000000000000001),\n", " ('film', 0.0030000000000000001),\n", " ('first', 0.0030000000000000001),\n", " ('chart', 0.0030000000000000001),\n", " ('sales', 0.002),\n", " ('yukos', 0.002),\n", " ('group', 0.002),\n", " ('company', 0.002),\n", " ('sold', 0.002),\n", " ('court', 0.002),\n", " ('russian', 0.002),\n", " ('record', 0.002),\n", " ('three', 0.002),\n", " ('sale', 0.002),\n", " ('music', 0.002),\n", " ('released', 0.002),\n", " ('year', 0.002)],\n", " [('number', 0.0050000000000000001),\n", " ('uk', 0.0040000000000000001),\n", " ('last', 0.0040000000000000001),\n", " ('top', 0.0040000000000000001),\n", " ('chart', 0.0030000000000000001),\n", " ('show', 0.0030000000000000001),\n", " ('group', 0.0030000000000000001),\n", " ('film', 0.002),\n", " ('three', 0.002),\n", " ('first', 0.002),\n", " ('music', 0.002),\n", " ('record', 0.002),\n", " ('band', 0.002),\n", " ('sales', 0.002),\n", " ('company', 0.002),\n", " ('bid', 0.002),\n", " ('sold', 0.002),\n", " ('deutsche', 0.002),\n", " ('year', 0.002),\n", " ('including', 0.002)]]" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ldaseq_chain.print_topic_times(2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### LDA Model and DTM\n", "\n", "For the first slice of DTM to get setup, we need to provide it sufficient stats from an LDA model. As discussed before, this is done by fitting gensim LDA on the dataset first. \n", "\n", "We also, however, have the option of passing our own model or suff stats values. Our final DTM results are heavily influenced by what we pass over here. We already know what a \"Good\" or \"Bad\" LDA model is (if not, read about it [here](http://nbviewer.jupyter.org/github/dsquareindia/gensim/blob/280375fe14adea67ce6384ba7eabf362b05e6029/docs/notebooks/topic_coherence_tutorial.ipynb)). \n", "\n", "It's quite obvious, then, that by passing a \"bad\" LDA model we will get not so satisfactory results; and by passing a better fitted or better trained LDA we will get better results. The same logic goes if we wish to directly pass the `suff_stats` numpy matrix." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Visualising Dynamic Topic Models.\n", "\n", "Let us use pyLDAvis to visualise both the DTM wrapper and DTM python port.\n", "With the new `DTMvis` methods it is now very straightforward to visualise DTM for a particular time-slice." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from gensim.models.wrappers.dtmmodel import DtmModel\n", "from gensim.corpora import Dictionary, bleicorpus\n", "import pyLDAvis\n", "\n", "# dtm_path = \"/Users/bhargavvader/Downloads/dtm_release/dtm/main\"\n", "# dtm_model = DtmModel(dtm_path, corpus, time_slice, num_topics=5, id2word=dictionary, initialize_lda=True)\n", "# dtm_model.save('dtm_news')\n", "\n", "# if we've saved before simply load the model\n", "dtm_model = DtmModel.load('dtm_news')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you take some time to look at the topics, you will notice large semantic similarities with the wrapper and the python DTM. \n", "Functionally, the python DTM replicates the wrapper quite well." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "
\n", "" ], "text/plain": [ "" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "doc_topic, topic_term, doc_lengths, term_frequency, vocab = dtm_model.dtm_vis(time=0, corpus=corpus)\n", "vis_wrapper = pyLDAvis.prepare(topic_term_dists=topic_term, doc_topic_dists=doc_topic, doc_lengths=doc_lengths, vocab=vocab, term_frequency=term_frequency)\n", "pyLDAvis.display(vis_wrapper)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now let us do the same for the python DTM." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In particular, look at topic 2 of the wrapper and topic 3 of the python port. Notice how they are both about football." ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "
\n", "" ], "text/plain": [ "" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "doc_topic, topic_term, doc_lengths, term_frequency, vocab = ldaseq.dtm_vis(time=0, corpus=corpus)\n", "vis_dtm = pyLDAvis.prepare(topic_term_dists=topic_term, doc_topic_dists=doc_topic, doc_lengths=doc_lengths, vocab=vocab, term_frequency=term_frequency)\n", "pyLDAvis.display(vis_dtm)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Visualising topics is a handy way to compare topic models." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Topic Coherence for DTM\n", "\n", "Similar to visualising DTM time-slices, finding coherence values for both python DTM and the wrapper is very easy.\n", "We just have to specify the time-slice we want to find coherence for.\n", "The following examples will illustrate this." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "U_mass topic coherence\n", "Wrapper coherence is -1.8017627313\n", "DTM Python coherence is -1.80238943495\n", "C_v topic coherence\n", "Wrapper coherence is 0.647868838777\n", "DTM Python coherence is 0.621369722784\n" ] } ], "source": [ "from gensim.models.coherencemodel import CoherenceModel\n", "import pickle\n", "\n", "# we just have to specify the time-slice we want to find coherence for.\n", "topics_wrapper = dtm_model.dtm_coherence(time=0)\n", "topics_dtm = ldaseq.dtm_coherence(time=2)\n", "\n", "# running u_mass coherence on our models\n", "cm_wrapper = CoherenceModel(topics=topics_wrapper, corpus=corpus, dictionary=dictionary, coherence='u_mass')\n", "cm_DTM = CoherenceModel(topics=topics_dtm, corpus=corpus, dictionary=dictionary, coherence='u_mass')\n", "\n", "print (\"U_mass topic coherence\")\n", "print (\"Wrapper coherence is \", cm_wrapper.get_coherence())\n", "print (\"DTM Python coherence is\", cm_DTM.get_coherence())\n", "\n", "# to use 'c_v' we need texts, which we have saved to disk.\n", "texts = pickle.load(open('Corpus/texts', 'rb'))\n", "cm_wrapper = CoherenceModel(topics=topics_wrapper, texts=texts, dictionary=dictionary, coherence='c_v')\n", "cm_DTM = CoherenceModel(topics=topics_dtm, texts=texts, dictionary=dictionary, coherence='c_v')\n", "\n", "print (\"C_v topic coherence\")\n", "print (\"Wrapper coherence is \", cm_wrapper.get_coherence())\n", "print (\"DTM Python coherence is\", cm_DTM.get_coherence())" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Our values are a little behind the wrapper - but not by much. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conclusion\n", "\n", "So while there is already a python wrapper of DTM, a pure python implementation will be useful to better understand what goes on undcer the hood and tune our model. When it comes to performance, the C++ is undoubtedly faster, but we can continue to work on ours to make it as fast.\n", "As for evaluating the results, our topics are on par if not better than the wrapper!\n", "\n", "On a more personal note, implementing Dynamic Topic Models with the Google Summer of Code 2016 program was a great learning experience. Gensim and RaRe Technologies have been a joy to work with, and Lev and Radim have been great mentors throughout, especially when things became slow or difficult. \n", "I look forward to continuing my contribution to gensim for a long time!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.2" } }, "nbformat": 4, "nbformat_minor": 0 }