{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Shashank Kapadia",
  "title_listed": "Evaluate Topic Models: Latent Dirichlet Allocation (LDA)",
  "keywords": "",
  "domain": "文本处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0/",
  "publish_date": "2019-08-19",
  "corpus_stage": "",
  "notes": "",
  "id": "536288d74c9e",
  "collected_at": "2026-10-02T10:02:49",
  "title": "Evaluate Topic Models: Latent Dirichlet Allocation (LDA) | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n# Evaluate Topic Models: Latent Dirichlet Allocation (LDA)\nA step-by-step guide to building interpretable topic models\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nAugust 19, 201912 min read\n![](../images/000.webp)\n**Preface:** This article aims to provide consolidated information on the underlying topic and is not to be considered as the original work. The information and the code are repurposed through several online articles, research papers, books, and open-source code.\nIn the previous [article](https://towardsdatascience.com/end-to-end-topic-modeling-in-python-latent-dirichlet-allocation-lda-35ce4ed6b3e0), I introduced the concept of topic modeling and walked through the code for developing your first topic model using Latent Dirichlet Allocation (LDA) method in Python using  _Gensim_ implementation.\nPursuing that understanding, in this article, we’ll go a few steps deeper by outlining the framework to quantitatively evaluate topic models through the measure of topic coherence and share the code template in Python using  _Gensim_ implementation to allow for end-to-end model development.\n## Why evaluate topic models?\nWe know probabilistic topic models, such as LDA, are popular tools for text analysis, providing both a predictive and latent topic representation of the corpus. However, there is a longstanding assumption that the latent space discovered by these models is generally meaningful and useful, and that evaluating such assumptions is challenging due to its unsupervised training process. Besides, there is a no-gold standard list of topics to compare against every corpus.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\nNevertheless, it is equally important to identify if a trained model is objectively good or bad, as well have an ability to compare different models/methods. To do so, one would require an objective measure for the quality. Traditionally, and still for many practical applications, to evaluate if “the correct thing” has been learned about the corpus, an implicit knowledge and “eyeballing” approaches are used. Ideally, we’d like to capture this information in a single metric that can be maximized, and compared.\nLet’s take a look at roughly what approaches are commonly used for the evaluation:\n**Eyeballing Models**\n  * Top N words\n  * Topics/documents\n\n\n**Intrinsic evaluation metrics**\n  * Capturing model semantics\n  * Topics interpretability\n\n\n**Human judgements**\n  * What is a topic?\n\n\n**Extrinsic evaluation metrics/evaluation at task**\n  * Is the model good at performing predefined tasks, such as classification?\n\n\nNatural language is messy, ambiguous and full of subjective interpretation, and sometimes, trying to cleanse ambiguity reduces the language to an unnatural form. In this article, we’ll explore more about topic coherence, an intrinsic evaluation metric, and how you can use it to quantitatively justify the model selection.\n## What is topic coherence?\nBefore we understand topic coherence, let’s briefly look at the perplexity measure. Perplexity as well is one of the intrinsic evaluation metric, and is widely used for language model evaluation. It captures how surprised a model is by new data it has not seen before and is measured as the normalized log-likelihood of a held-out test set.\nFocussing on the log-likelihood part, you can think of the perplexity metric as measuring how probable some new unseen data is given the model that was learned earlier. That is to say, how well does the model represent or reproduce the statistics of the held-out data?\nHowever, recent studies have shown that predictive likelihood (or equivalently, perplexity) and human judgment are often not correlated, and even sometimes slightly anti-correlated.\n> Optimizing for perplexity may not yield human-interpretable topics.\nThis limitation of perplexity measure served as a motivation for more work trying to model the human judgment and, thus,  _Topic Coherence._\nThe concept of topic coherence combines a number of measures into a framework to evaluate the coherence between topics inferred by a model. But before that…\n**What is topic coherence?**\nTopic Coherence measures score a single topic by measuring the degree of semantic similarity between high scoring words in the topic. These measurements help distinguish between topics that are semantically interpretable topics and topics that are artifacts of statistical inference. But …\n**What is coherence?**\nA set of statements or facts is said to be coherent, if they support each other. Thus, a coherent fact set can be interpreted in a context that covers all or most of the facts. An example of a coherent fact set is “the game is a team sport”, “the game is played with a ball”, “the game demands great physical efforts.”\n## Coherence measures\nLet’s take quick look at different coherence measures, and how they are calculated:\n  1. _**C_v**_ measure is based on a sliding window, one-set segmentation of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity\n  2. _**C_p**_ is based on a sliding window, one-preceding segmentation of the top words and the confirmation measure of Fitelson’s coherence\n  3. _**C_uci**_ measure is based on a sliding window and the pointwise mutual information (PMI) of all word pairs of the given top words\n  4. _**C_umass**_ is based on document cooccurrence counts, a one-preceding segmentation and a logarithmic conditional probability as confirmation measure\n  5. _**C_npmi**_ is an enhanced version of the C_uci coherence using the normalized pointwise mutual information (NPMI)\n  6. _**C_a**_ is baseed on a context window, a pairwise comparison of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity\n\n\nThere is, of course, a lot more to the concept of topic model evaluation, and the coherence measure. However, keeping in mind the length, and purpose of this article, let’s apply these concepts into developing a model that is at least better than with the default parameters. Also, we’ll be re-purposing already available online pieces of code to support this exercise instead of re-inventing the wheel.\n## Model implementation\nThe complete code is available as a [Jupyter Notebook on GitHub](https://github.com/kapadias/medium-articles/blob/master/natural-language-processing/topic-modeling/Evaluate%20Topic%20Models.ipynb).\n  1. Loading data\n  2. Data cleaning\n  3. Phrase modeling: Bi-grams and tri-grams\n  4. Data transformation: Corpus and dictionary\n  5. Base model\n  6. Hyperparameter tuning\n  7. Final model\n  8. Visualize results\n\n\n## **Loading data**\n![](../images/001.png)\nFor this tutorial, we’ll use the dataset of papers published in NIPS conference. The NIPS conference (Neural Information Processing Systems) is one of the most prestigious yearly events in the machine learning community. The CSV data file contains information on the different NIPS papers that were published from 1987 until 2016 (29 years!). These papers discuss a wide variety of topics in machine learning, from neural networks to optimization methods, and many more.\nLet’s start by looking at the content of the file:\npython\n\n```\nimport zipfile\nimport pandas as pd\nimport os\n\n# Open the zip file\nwith zipfile.ZipFile(\"./data/NIPS Papers.zip\", \"r\") as zip_ref:\n    # Extract the file to a temporary directory\n    zip_ref.extractall(\"temp\")\n\n# Read the CSV file into a pandas DataFrame\npapers = pd.read_csv(\"temp/NIPS Papers/papers.csv\")\n\n# Print head\npapers.head()\n```\n\n![](../images/body-259d0a982ec4632eec1b.png)\n## Data cleaning\nSince the goal of this analysis is to perform topic modeling, we will solely focus on the text data from each paper, and drop other metadata columns.\npython\n\n```\n# Remove the columns\npapers = papers.drop(columns=['id', 'title', 'abstract', \n                              'event_type', 'pdf_name', 'year'], axis=1)\n\n# sample only 100 papers\npapers = papers.sample(100)\n\n# Print out the first rows of papers\npapers.head()\n```\n\n**Remove punctuation/lower casing**\nNext, let’s perform a simple preprocessing on the content of paper_text column to make them more amenable for analysis, and reliable results. To do that, we’ll use a regular expression to remove any punctuation, and then lowercase the text.\npython\n\n```\n# Load the regular expression library\nimport re\n\n# Remove punctuation\npapers['paper_text_processed'] = papers['paper_text'].map(lambda x: re.sub('[,\\.!?]', '', x))\n\n# Convert the titles to lowercase\npapers['paper_text_processed'] = papers['paper_text_processed'].map(lambda x: x.lower())\n\n# Print out the first rows of papers\npapers['paper_text_processed'].head()\n```\n\n![](../images/body-40583ec8ac50d22756c7.png)\n**Tokenize words and further clean-up text**\nLet’s tokenize each sentence into a list of words, removing punctuations and unnecessary characters altogether.\npython\n\n```\nimport gensim\nfrom gensim.utils import simple_preprocess\n\ndef sent_to_words(sentences):\n    for sentence in sentences:\n        yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))  # deacc=True removes punctuations\n\ndata = papers.paper_text_processed.values.tolist()\ndata_words = list(sent_to_words(data))\n\nprint(data_words[:1][0][:30])\n```\n\n![](../images/body-9e7231d03de10a86a618.png)\n## Phrase modeling: Bigram and trigram models\nBigrams are two words frequently occurring together in the document. Trigrams are 3 words frequently occurring. Some examples in our example are: ‘back_bumper’, ‘oil_leakage’, ‘maryland_college_park’ etc.\n[Gensim’s Phrases model](https://radimrehurek.com/gensim/models/phrases.html) can build and implement the bigrams, trigrams, quadgrams and more. The two important arguments to Phrases are min_count and threshold.\n> The higher the values of these param, the harder it is for words to be combined.\npython\n\n```\n# Build the bigram and trigram models\nbigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases.\ntrigram = gensim.models.Phrases(bigram[data_words], threshold=100)  \n\n# Faster way to get a sentence clubbed as a trigram/bigram\nbigram_mod = gensim.models.phrases.Phraser(bigram)\ntrigram_mod = gensim.models.phrases.Phraser(trigram)\n```\n\n**Remove stopwords, make bigrams and lemmatize**\nThe phrase models are ready. Let’s define the functions to remove the stopwords, make trigrams and lemmatization, and call them sequentially.\npython\n\n```\n# NLTK Stop words\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nstop_words = stopwords.words('english')\nstop_words.extend(['from', 'subject', 're', 'edu', 'use'])\n\n# Define functions for stopwords, bigrams, trigrams and lemmatization\ndef remove_stopwords(texts):\n    return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]\n\ndef make_bigrams(texts):\n    return [bigram_mod[doc] for doc in texts]\n\ndef make_trigrams(texts):\n    return [trigram_mod[bigram_mod[doc]] for doc in texts]\n\ndef lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):\n    \"\"\"https://spacy.io/api/annotation\"\"\"\n    texts_out = []\n    for sent in texts:\n        doc = nlp(\" \".join(sent)) \n        texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])\n    return texts_out\n```\n\nLet’s call the functions in order.\npython\n\n```\n!python -m spacy download en_core_web_sm\nimport spacy\n\n# Remove Stop Words\ndata_words_nostops = remove_stopwords(data_words)\n\n# Form Bigrams\ndata_words_bigrams = make_bigrams(data_words_nostops)\n\n# Initialize spacy 'en' model, keeping only tagger component (for efficiency)\nnlp = spacy.load(\"en_core_web_sm\", disable=['parser', 'ner'])\n\n# Do lemmatization keeping only noun, adj, vb, adv\ndata_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])\n\nprint(data_lemmatized[:1][0][:30])\n```\n\n![](../images/body-b1720d1c1e2e9e402a50.png)\n## Data transformation: Corpus and dictionary\nThe two main inputs to the LDA topic model are the dictionary(id2word) and the corpus. Let’s create them.\npython\n\n```\nimport gensim.corpora as corpora\n\n# Create Dictionary\nid2word = corpora.Dictionary(data_lemmatized)\n\n# Create Corpus\ntexts = data_lemmatized\n\n# Term Document Frequency\ncorpus = [id2word.doc2bow(text) for text in texts]\n\n# View\nprint(corpus[:1][0][:30])\n```\n\n![](../images/body-2939703f24bd76d8b8a9.png)\nGensim creates a unique id for each word in the document. The produced corpus shown above is a mapping of (word_id, word_frequency).\nFor example, (0, 7) above implies, word id 0 occurs seven times in the first document. Likewise, word id 1 occurs thrice, and so on.\n## Base model\nWe have everything required to train the base LDA model. In addition to the corpus and dictionary, you need to provide the number of topics as well. Apart from that, alpha and eta are hyperparameters that affect sparsity of the topics. According to the Gensim docs, both defaults to 1.0/num_topics prior (we’ll use default for the base model).\n> **chunksize** controls how many documents are processed at a time in the training algorithm. Increasing chunksize will speed up training, at least as long as the chunk of documents easily fit into memory.\n> **passes** controls how often we train the model on the entire corpus (set to 10). Another word for passes might be “epochs”. iterations is somewhat technical, but essentially it controls how often we repeat a particular loop over each document. It is important to set the number of “passes” and “iterations” high enough.\npython\n\n```\n# Build LDA model\nlda_model = gensim.models.LdaMulticore(corpus=corpus,\n                                       id2word=id2word,\n                                       num_topics=10, \n                                       random_state=100,\n                                       chunksize=100,\n                                       passes=10,\n                                       per_word_topics=True)\n```\n\n**View the topics in LDA model**\nThe above LDA model is built with 10 different topics where each topic is a combination of keywords and each keyword contributes a certain weightage to the topic.\nYou can see the keywords for each topic and the weightage(importance) of each keyword using  _lda_model.print_topics()\\_\npython\n\n```\nfrom pprint import pprint\n\n# Print the Keyword in the 10 topics\npprint(lda_model.print_topics())\ndoc_lda = lda_model[corpus]\n```\n\n![](../images/body-1380dec579e8446f3164.png)\n**Compute model perplexity and coherence score**\nLet’s calculate the baseline coherence score:\npython\n\n```\nfrom gensim.models import CoherenceModel\n\n# Compute Coherence Score\ncoherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')\ncoherence_lda = coherence_model_lda.get_coherence()\nprint('Coherence Score: ', coherence_lda)\n```\n\n_**Coherence Score: 0.301**_\n## Hyperparameter tuning\nFirst, let’s differentiate between model hyperparameters and model parameters:\n> **Model hyperparameters** can be thought of as settings for a machine learning algorithm that are tuned by the data scientist before training. Examples would be the number of trees in the random forest, or in our case, number of topics K\n> **Model parameters** can be thought of as what the model learns during training, such as the weights for each word in a given topic\nNow that we have the baseline coherence score for the default LDA model, let’s perform a series of sensitivity tests to help determine the following model hyperparameters:\n  1. Number of topics (K)\n  2. Dirichlet hyperparameter alpha: Document-topic density\n  3. Dirichlet hyperparameter beta: Word-topic density\n\n\nWe’ll perform these tests in sequence, one parameter at a time by keeping others constant and run them over the two different validation corpus sets. We’ll use  _**C_v**_ as our choice of metric for performance comparison.\npython\n\n```\n# supporting function\ndef compute_coherence_values(corpus, dictionary, k, a, b):\n    \n    lda_model = gensim.models.LdaMulticore(corpus=corpus,\n                                           id2word=dictionary,\n                                           num_topics=k, \n                                           random_state=100,\n                                           chunksize=100,\n                                           passes=10,\n                                           alpha=a,\n                                           eta=b)\n    \n    coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')\n    \n    return coherence_model_lda.get_coherence()\n```\n\nLet’s call the function, and iterate it over the range of topics, alpha, and beta parameter values:\npython\n\n```\nimport numpy as np\nimport tqdm\n\ngrid = {}\ngrid['Validation_Set'] = {}\n\n# Topics range\nmin_topics = 2\nmax_topics = 11\nstep_size = 1\ntopics_range = range(min_topics, max_topics, step_size)\n\n# Alpha parameter\nalpha = list(np.arange(0.01, 1, 0.3))\nalpha.append('symmetric')\nalpha.append('asymmetric')\n\n# Beta parameter\nbeta = list(np.arange(0.01, 1, 0.3))\nbeta.append('symmetric')\n\n# Validation sets\nnum_of_docs = len(corpus)\ncorpus_sets = [gensim.utils.ClippedCorpus(corpus, int(num_of_docs*0.75)), \n               corpus]\n\ncorpus_title = ['75% Corpus', '100% Corpus']\n\nmodel_results = {'Validation_Set': [],\n                 'Topics': [],\n                 'Alpha': [],\n                 'Beta': [],\n                 'Coherence': []\n                }\n\n# Can take a long time to run\nif 1 == 1:\n    pbar = tqdm.tqdm(total=(len(beta)*len(alpha)*len(topics_range)*len(corpus_title)))\n    \n    # iterate through validation corpuses\n    for i in range(len(corpus_sets)):\n        # iterate through number of topics\n        for k in topics_range:\n            # iterate through alpha values\n            for a in alpha:\n                # iterare through beta values\n                for b in beta:\n                    # get the coherence score for the given parameters\n                    cv = compute_coherence_values(corpus=corpus_sets[i], dictionary=id2word, \n                                                  k=k, a=a, b=b)\n                    # Save the model results\n                    model_results['Validation_Set'].append(corpus_title[i])\n                    model_results['Topics'].append(k)\n                    model_results['Alpha'].append(a)\n                    model_results['Beta'].append(b)\n                    model_results['Coherence'].append(cv)\n                    \n                    pbar.update(1)\n    pd.DataFrame(model_results).to_csv('./results/lda_tuning_results.csv', index=False)\n    pbar.close()\n```\n\n## Investigate results\nLet’s start by determining the optimal number of topics. The chart below outlines the coherence score, C_v, for the number of topics across two validation sets, and a fixed alpha = 0.01 and beta = 0.1.\n![](../images/body-4e5ad81b5ea8443f265b.png)\nWith the coherence score seems to keep increasing with the number of topics, it may make better sense to pick the model that gave the highest CV before flattening out or a major drop. In this case, we picked K=8.\nNext, we want to select the optimal alpha and beta parameters. While there are other sophisticated approaches to tackle the selection process, for this tutorial, we choose the values that yielded maximum C_v score for K=8.\n![](../images/body-29bcf0b108abc6fa5b91.png)\n> alpha=0.01\n> beta=0.9\n> K=8\nThat yields approx. 17% improvement over the baseline score.\n## Final model\nLet’s train the final model using the above selected parameters:\npython\n\n```\nnum_topics = 8\n\nlda_model = gensim.models.LdaMulticore(corpus=corpus,\n                                           id2word=id2word,\n                                           num_topics=num_topics, \n                                           random_state=100,\n                                           chunksize=100,\n                                           passes=10,\n                                           alpha=0.01,\n                                           eta=0.9)\n```\n\n## Visualize topics\npython\n\n```\nimport pyLDAvis.gensim_models as gensimvis\nimport pickle \nimport pyLDAvis\n\n# Visualize the topics\npyLDAvis.enable_notebook()\n\nLDAvis_data_filepath = os.path.join('./results/ldavis_tuned_'+str(num_topics))\n\n# # this is a bit time consuming - make the if statement True\n# # if you want to execute visualization prep yourself\nif 1 == 1:\n    LDAvis_prepared = gensimvis.prepare(lda_model, corpus, id2word)\n    with open(LDAvis_data_filepath, 'wb') as f:\n        pickle.dump(LDAvis_prepared, f)\n\n# load the pre-prepared pyLDAvis data from disk\nwith open(LDAvis_data_filepath, 'rb') as f:\n    LDAvis_prepared = pickle.load(f)\n\npyLDAvis.save_html(LDAvis_prepared, './results/ldavis_tuned_'+ str(num_topics) +'.html')\n\nLDAvis_prepared\n```\n\n![](../images/body-bcf394b61f9db9552276.png)\n## Closing notes\nWe started with understanding why evaluating the topic model is essential. Next, we reviewed existing methods and scratched the surface of topic coherence, along with the available coherence measures. Then we built a default LDA model using Gensim implementation to establish the baseline coherence score and reviewed practical ways to optimize the LDA hyperparameters.\nHopefully, this article has managed to shed light on the underlying topic evaluation strategies, and intuitions behind it.\n**References:**\n  1. <http://qpleple.com/perplexity-to-evaluate-topic-models/>\n  2. <https://www.amazon.com/Machine-Learning-Probabilistic-Perspective-Computation/dp/0262018020>\n  3. <https://papers.nips.cc/paper/3700-reading-tea-leaves-how-humans-interpret-topic-models.pdf>\n  4. <https://github.com/mattilyra/pydataberlin-2017/blob/master/notebook/EvaluatingUnsupervisedModels.ipynb>\n  5. <https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/>\n  6. <http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf>\n  7. <http://palmetto.aksw.org/palmetto-webapp/>\n\n\nThanks for reading.  _If you have any feedback, please feel free to reach out by messaging me on_[ _LinkedIn_](https://www.linkedin.com/in/shashankkapadia/) _or shooting me an email (shmkapadia[at]gmail.com)_\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\nSK\nWritten By\n## [Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[See all from Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Model Evaluation](https://towardsdatascience.com/tag/model-evaluation/)[NLP](https://towardsdatascience.com/tag/nlp/)[topic model](https://towardsdatascience.com/tag/topic-model/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F&title=Evaluate%20Topic%20Models%3A%20Latent%20Dirichlet%20Allocation%20\\(LDA\\))\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F&title=Evaluate%20Topic%20Models%3A%20Latent%20Dirichlet%20Allocation%20\\(LDA\\))\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F&text=Evaluate%20Topic%20Models%3A%20Latent%20Dirichlet%20Allocation%20\\(LDA\\))\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/002.jpg)](https://towardsdatascience.com/google-data-studio-its-free-but-is-it-any-good-debf5d11bbbd/)\n## [Google Data Studio. It's Free But Is It Any Good?](https://towardsdatascience.com/google-data-studio-its-free-but-is-it-any-good-debf5d11bbbd/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA product review based on my 6 major differentiators of BI tools.\n[Adam Finer](https://towardsdatascience.com/author/adamfiner/)\nNovember 26, 202010 min read\n  * [![](../images/003.jpg)](https://towardsdatascience.com/googles-minerva-solving-math-problems-with-ai-4f0a6aaabaf1/)\n## [Google's Minerva, solving math problems with AI](https://towardsdatascience.com/googles-minerva-solving-math-problems-with-ai-4f0a6aaabaf1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nQuantitative reasoning is hard for humans and it is hard for computers. Minerva just got astonishing results in solving math problems\n[Salvatore Raieli](https://towardsdatascience.com/author/salvatore-raieli/)\nJuly 8, 20226 min read\n  * [![](../images/004.png)](https://towardsdatascience.com/gaussian-processes-from-scratch-cfc11715730c/)\n## [Gaussian Processes from Scratch](https://towardsdatascience.com/gaussian-processes-from-scratch-cfc11715730c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nGain a deeper understanding of Gaussian processes by implementing them with only NumPy\n[Theo Wolf](https://towardsdatascience.com/author/theo.wolf/)\nJanuary 6, 20245 min read\n  * [![](../images/005.jpeg)](https://towardsdatascience.com/how-to-fix-kernel-error-in-jupyter-notebook-81619e195703/)\n## [How to Fix Kernel Error in Jupyter Notebook](https://towardsdatascience.com/how-to-fix-kernel-error-in-jupyter-notebook-81619e195703/)\n[Programming](https://towardsdatascience.com/category/programming/)\nMake your python codes run smoothly\n[Benjamin Nweke](https://towardsdatascience.com/author/benjaminnweke/)\nMay 26, 20224 min read\n  * [![](../images/006.jpg)](https://towardsdatascience.com/a-brief-introduction-to-neural-networks-a-classification-problem-43e68c770081/)\n## [A Brief Introduction to Neural Networks : a Classification Problem](https://towardsdatascience.com/a-brief-introduction-to-neural-networks-a-classification-problem-43e68c770081/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA practical beginner guide to Neural Networks in Python\n[Chayma Zatout](https://towardsdatascience.com/author/chim-so/)\nJanuary 24, 202319 min read\n  * [![](../images/007.jpg)](https://towardsdatascience.com/design-patterns-with-python-for-machine-learning-engineers-builder-45b8e749f134/)\n## [Design Patterns with Python for Machine Learning Engineers: Builder](https://towardsdatascience.com/design-patterns-with-python-for-machine-learning-engineers-builder-45b8e749f134/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nLearn how to use the Builder design pattern to enhance your code\n[Marcello Politi](https://towardsdatascience.com/author/marcellopoliti/)\nOctober 12, 20236 min read\n  * [![](../images/008.jpeg)](https://towardsdatascience.com/battling-open-book-exams-with-open-source-llms-c2225f3002d0/)\n## [Battling Open Book Exams with Open Source LLMs](https://towardsdatascience.com/battling-open-book-exams-with-open-source-llms-c2225f3002d0/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nIn the age where everyone uses ChatGPT for work and school, I am taking advantage of that to help me study in my university course\n[Jubayer Hossain Ahad](https://towardsdatascience.com/author/jubayerhossainahad/)\nJuly 19, 20249 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/intro-to-docker-containers-for-data-scientists-dda9f2cfe66e/)\n## [Intro to Docker Containers for Data Scientists](https://towardsdatascience.com/intro-to-docker-containers-for-data-scientists-dda9f2cfe66e/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA practical tutorial for setting up a local dev environment using Docker Container\n[Ido Leshem](https://towardsdatascience.com/author/leshem-ido/)\nDecember 20, 20236 min read\n  * [![](../images/010.png)](https://towardsdatascience.com/create-a-bar-chart-race-animation-app-using-streamlit-and-raceplotly-e44495249f11/)\n## [Create a Bar Chart Race Animation App Using Streamlit and Raceplotly](https://towardsdatascience.com/create-a-bar-chart-race-animation-app-using-streamlit-and-raceplotly-e44495249f11/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nLearn How to Use Streamlit to Build an App that Generates Bar Chart Race Animations within Seconds and No Coding\n[My Data Talk](https://towardsdatascience.com/author/insightsbees/)\nFebruary 22, 20228 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "Evaluate Topic Models: Latent Dirichlet Allocation (LDA) | Towards Data Science",
    "description": "A step-by-step guide to building interpretable topic models",
    "keywords": null,
    "author": "Shashank Kapadia",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Evaluate Topic Models: Latent Dirichlet Allocation (LDA)",
    "og:description": "A step-by-step guide to building interpretable topic models",
    "og:url": "https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA.webp",
    "og:image:width": "1400",
    "og:image:height": "907",
    "og:image:type": "image/webp",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Shashank Kapadia",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "12 min read",
    "article:published_time": "2019-08-19T17:03:05.000Z",
    "article:modified_time": "2019-08-19T17:03:05.000Z",
    "article:author": "https://towardsdatascience.com/author/shashank kapadia/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_000.txt",
      "chars": 334
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_001.txt",
      "chars": 258
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_002.txt",
      "chars": 364
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_003.txt",
      "chars": 349
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_004.txt",
      "chars": 376
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_005.txt",
      "chars": 858
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_006.txt",
      "chars": 524
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_007.txt",
      "chars": 253
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_008.txt",
      "chars": 405
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_009.txt",
      "chars": 125
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_010.txt",
      "chars": 276
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_011.txt",
      "chars": 715
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_012.txt",
      "chars": 1912
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_013.txt",
      "chars": 477
    },
    {
      "language": "txt",
      "file": "attachments/536288d74c9e/code/block_014.txt",
      "chars": 727
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:58:21Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:58:21Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:58:21Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:58:21Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/shashank kapadia/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/end-to-end-topic-modeling-in-python-latent-dirichlet-allocation-lda-35ce4ed6b3e0"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/model-evaluation/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/nlp/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/topic-model/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/google-data-studio-its-free-but-is-it-any-good-debf5d11bbbd/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/adamfiner/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/googles-minerva-solving-math-problems-with-ai-4f0a6aaabaf1/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/salvatore-raieli/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/gaussian-processes-from-scratch-cfc11715730c/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://github.com/kapadias/medium-articles/blob/master/natural-language-processing/topic-modeling/Evaluate%20Topic%20Models.ipynb"
    },
    {
      "type": "external",
      "href": "https://radimrehurek.com/gensim/models/phrases.html"
    },
    {
      "type": "external",
      "href": "http://qpleple.com/perplexity-to-evaluate-topic-models/"
    },
    {
      "type": "external",
      "href": "https://www.amazon.com/Machine-Learning-Probabilistic-Perspective-Computation/dp/0262018020"
    },
    {
      "type": "external",
      "href": "https://papers.nips.cc/paper/3700-reading-tea-leaves-how-humans-interpret-topic-models.pdf"
    },
    {
      "type": "external",
      "href": "https://github.com/mattilyra/pydataberlin-2017/blob/master/notebook/EvaluatingUnsupervisedModels.ipynb"
    },
    {
      "type": "external",
      "href": "https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/"
    },
    {
      "type": "external",
      "href": "http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf"
    },
    {
      "type": "external",
      "href": "http://palmetto.aksw.org/palmetto-webapp/"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/shashankkapadia/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Evaluate+Topic+Models%3A+Latent+Dirichlet+Allocation+%28LDA%29&u=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Evaluate+Topic+Models%3A+Latent+Dirichlet+Allocation+%28LDA%29&url=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Evaluate+Topic+Models%3A+Latent+Dirichlet+Allocation+%28LDA%29&url=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:29:27Z",
  "source_url": "https://towardsdatascience.com/evaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\n# Evaluate Topic Models: Latent Dirichlet Allocation (LDA)\nA step-by-step guide to building interpretable topic models\n[Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\nAugust 19, 201912 min read\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA.webp)\n**Preface:** This article aims to provide consolidated information on the underlying topic and is not to be considered as the original work. The information and the code are repurposed through several online articles, research papers, books, and open-source code.\nIn the previous [article](https://towardsdatascience.com/end-to-end-topic-modeling-in-python-latent-dirichlet-allocation-lda-35ce4ed6b3e0), I introduced the concept of topic modeling and walked through the code for developing your first topic model using Latent Dirichlet Allocation (LDA) method in Python using  _Gensim_ implementation.\nPursuing that understanding, in this article, we’ll go a few steps deeper by outlining the framework to quantitatively evaluate topic models through the measure of topic coherence and share the code template in Python using  _Gensim_ implementation to allow for end-to-end model development.\n## Why evaluate topic models?\nWe know probabilistic topic models, such as LDA, are popular tools for text analysis, providing both a predictive and latent topic representation of the corpus. However, there is a longstanding assumption that the latent space discovered by these models is generally meaningful and useful, and that evaluating such assumptions is challenging due to its unsupervised training process. Besides, there is a no-gold standard list of topics to compare against every corpus.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\nNevertheless, it is equally important to identify if a trained model is objectively good or bad, as well have an ability to compare different models/methods. To do so, one would require an objective measure for the quality. Traditionally, and still for many practical applications, to evaluate if “the correct thing” has been learned about the corpus, an implicit knowledge and “eyeballing” approaches are used. Ideally, we’d like to capture this information in a single metric that can be maximized, and compared.\nLet’s take a look at roughly what approaches are commonly used for the evaluation:\n**Eyeballing Models**\n  * Top N words\n  * Topics/documents\n\n\n**Intrinsic evaluation metrics**\n  * Capturing model semantics\n  * Topics interpretability\n\n\n**Human judgements**\n  * What is a topic?\n\n\n**Extrinsic evaluation metrics/evaluation at task**\n  * Is the model good at performing predefined tasks, such as classification?\n\n\nNatural language is messy, ambiguous and full of subjective interpretation, and sometimes, trying to cleanse ambiguity reduces the language to an unnatural form. In this article, we’ll explore more about topic coherence, an intrinsic evaluation metric, and how you can use it to quantitatively justify the model selection.\n## What is topic coherence?\nBefore we understand topic coherence, let’s briefly look at the perplexity measure. Perplexity as well is one of the intrinsic evaluation metric, and is widely used for language model evaluation. It captures how surprised a model is by new data it has not seen before and is measured as the normalized log-likelihood of a held-out test set.\nFocussing on the log-likelihood part, you can think of the perplexity metric as measuring how probable some new unseen data is given the model that was learned earlier. That is to say, how well does the model represent or reproduce the statistics of the held-out data?\nHowever, recent studies have shown that predictive likelihood (or equivalently, perplexity) and human judgment are often not correlated, and even sometimes slightly anti-correlated.\n> Optimizing for perplexity may not yield human-interpretable topics.\nThis limitation of perplexity measure served as a motivation for more work trying to model the human judgment and, thus,  _Topic Coherence._\nThe concept of topic coherence combines a number of measures into a framework to evaluate the coherence between topics inferred by a model. But before that…\n**What is topic coherence?**\nTopic Coherence measures score a single topic by measuring the degree of semantic similarity between high scoring words in the topic. These measurements help distinguish between topics that are semantically interpretable topics and topics that are artifacts of statistical inference. But …\n**What is coherence?**\nA set of statements or facts is said to be coherent, if they support each other. Thus, a coherent fact set can be interpreted in a context that covers all or most of the facts. An example of a coherent fact set is “the game is a team sport”, “the game is played with a ball”, “the game demands great physical efforts.”\n## Coherence measures\nLet’s take quick look at different coherence measures, and how they are calculated:\n  1. _**C_v**_ measure is based on a sliding window, one-set segmentation of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity\n  2. _**C_p**_ is based on a sliding window, one-preceding segmentation of the top words and the confirmation measure of Fitelson’s coherence\n  3. _**C_uci**_ measure is based on a sliding window and the pointwise mutual information (PMI) of all word pairs of the given top words\n  4. _**C_umass**_ is based on document cooccurrence counts, a one-preceding segmentation and a logarithmic conditional probability as confirmation measure\n  5. _**C_npmi**_ is an enhanced version of the C_uci coherence using the normalized pointwise mutual information (NPMI)\n  6. _**C_a**_ is baseed on a context window, a pairwise comparison of the top words and an indirect confirmation measure that uses normalized pointwise mutual information (NPMI) and the cosine similarity\n\n\nThere is, of course, a lot more to the concept of topic model evaluation, and the coherence measure. However, keeping in mind the length, and purpose of this article, let’s apply these concepts into developing a model that is at least better than with the default parameters. Also, we’ll be re-purposing already available online pieces of code to support this exercise instead of re-inventing the wheel.\n## Model implementation\nThe complete code is available as a [Jupyter Notebook on GitHub](https://github.com/kapadias/medium-articles/blob/master/natural-language-processing/topic-modeling/Evaluate%20Topic%20Models.ipynb).\n  1. Loading data\n  2. Data cleaning\n  3. Phrase modeling: Bi-grams and tri-grams\n  4. Data transformation: Corpus and dictionary\n  5. Base model\n  6. Hyperparameter tuning\n  7. Final model\n  8. Visualize results\n\n\n## **Loading data**\n![](https://assets.insightmediagroup.io/media/v2/resize:fit:408/1*TW24U1lZ3CaVc6jGzZ9yzA.png)\nFor this tutorial, we’ll use the dataset of papers published in NIPS conference. The NIPS conference (Neural Information Processing Systems) is one of the most prestigious yearly events in the machine learning community. The CSV data file contains information on the different NIPS papers that were published from 1987 until 2016 (29 years!). These papers discuss a wide variety of topics in machine learning, from neural networks to optimization methods, and many more.\nLet’s start by looking at the content of the file:\npython\n\n```\nimport zipfile\nimport pandas as pd\nimport os\n\n# Open the zip file\nwith zipfile.ZipFile(\"./data/NIPS Papers.zip\", \"r\") as zip_ref:\n    # Extract the file to a temporary directory\n    zip_ref.extractall(\"temp\")\n\n# Read the CSV file into a pandas DataFrame\npapers = pd.read_csv(\"temp/NIPS Papers/papers.csv\")\n\n# Print head\npapers.head()\n```\n\n![](https://assets.insightmediagroup.io/media/v2/resize:fit:1400/1*q4CFMVFEqS1gDt_A3e-gmg.png)\n## Data cleaning\nSince the goal of this analysis is to perform topic modeling, we will solely focus on the text data from each paper, and drop other metadata columns.\npython\n\n```\n# Remove the columns\npapers = papers.drop(columns=['id', 'title', 'abstract', \n                              'event_type', 'pdf_name', 'year'], axis=1)\n\n# sample only 100 papers\npapers = papers.sample(100)\n\n# Print out the first rows of papers\npapers.head()\n```\n\n**Remove punctuation/lower casing**\nNext, let’s perform a simple preprocessing on the content of paper_text column to make them more amenable for analysis, and reliable results. To do that, we’ll use a regular expression to remove any punctuation, and then lowercase the text.\npython\n\n```\n# Load the regular expression library\nimport re\n\n# Remove punctuation\npapers['paper_text_processed'] = papers['paper_text'].map(lambda x: re.sub('[,\\.!?]', '', x))\n\n# Convert the titles to lowercase\npapers['paper_text_processed'] = papers['paper_text_processed'].map(lambda x: x.lower())\n\n# Print out the first rows of papers\npapers['paper_text_processed'].head()\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA-2-1024x131.png)\n**Tokenize words and further clean-up text**\nLet’s tokenize each sentence into a list of words, removing punctuations and unnecessary characters altogether.\npython\n\n```\nimport gensim\nfrom gensim.utils import simple_preprocess\n\ndef sent_to_words(sentences):\n    for sentence in sentences:\n        yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))  # deacc=True removes punctuations\n\ndata = papers.paper_text_processed.values.tolist()\ndata_words = list(sent_to_words(data))\n\nprint(data_words[:1][0][:30])\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA-3-1024x177.png)\n## Phrase modeling: Bigram and trigram models\nBigrams are two words frequently occurring together in the document. Trigrams are 3 words frequently occurring. Some examples in our example are: ‘back_bumper’, ‘oil_leakage’, ‘maryland_college_park’ etc.\n[Gensim’s Phrases model](https://radimrehurek.com/gensim/models/phrases.html) can build and implement the bigrams, trigrams, quadgrams and more. The two important arguments to Phrases are min_count and threshold.\n> The higher the values of these param, the harder it is for words to be combined.\npython\n\n```\n# Build the bigram and trigram models\nbigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases.\ntrigram = gensim.models.Phrases(bigram[data_words], threshold=100)  \n\n# Faster way to get a sentence clubbed as a trigram/bigram\nbigram_mod = gensim.models.phrases.Phraser(bigram)\ntrigram_mod = gensim.models.phrases.Phraser(trigram)\n```\n\n**Remove stopwords, make bigrams and lemmatize**\nThe phrase models are ready. Let’s define the functions to remove the stopwords, make trigrams and lemmatization, and call them sequentially.\npython\n\n```\n# NLTK Stop words\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords\n\nstop_words = stopwords.words('english')\nstop_words.extend(['from', 'subject', 're', 'edu', 'use'])\n\n# Define functions for stopwords, bigrams, trigrams and lemmatization\ndef remove_stopwords(texts):\n    return [[word for word in simple_preprocess(str(doc)) if word not in stop_words] for doc in texts]\n\ndef make_bigrams(texts):\n    return [bigram_mod[doc] for doc in texts]\n\ndef make_trigrams(texts):\n    return [trigram_mod[bigram_mod[doc]] for doc in texts]\n\ndef lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):\n    \"\"\"https://spacy.io/api/annotation\"\"\"\n    texts_out = []\n    for sent in texts:\n        doc = nlp(\" \".join(sent)) \n        texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])\n    return texts_out\n```\n\nLet’s call the functions in order.\npython\n\n```\n!python -m spacy download en_core_web_sm\nimport spacy\n\n# Remove Stop Words\ndata_words_nostops = remove_stopwords(data_words)\n\n# Form Bigrams\ndata_words_bigrams = make_bigrams(data_words_nostops)\n\n# Initialize spacy 'en' model, keeping only tagger component (for efficiency)\nnlp = spacy.load(\"en_core_web_sm\", disable=['parser', 'ner'])\n\n# Do lemmatization keeping only noun, adj, vb, adv\ndata_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])\n\nprint(data_lemmatized[:1][0][:30])\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA-4-1024x175.png)\n## Data transformation: Corpus and dictionary\nThe two main inputs to the LDA topic model are the dictionary(id2word) and the corpus. Let’s create them.\npython\n\n```\nimport gensim.corpora as corpora\n\n# Create Dictionary\nid2word = corpora.Dictionary(data_lemmatized)\n\n# Create Corpus\ntexts = data_lemmatized\n\n# Term Document Frequency\ncorpus = [id2word.doc2bow(text) for text in texts]\n\n# View\nprint(corpus[:1][0][:30])\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA-5-1024x175.png)\nGensim creates a unique id for each word in the document. The produced corpus shown above is a mapping of (word_id, word_frequency).\nFor example, (0, 7) above implies, word id 0 occurs seven times in the first document. Likewise, word id 1 occurs thrice, and so on.\n## Base model\nWe have everything required to train the base LDA model. In addition to the corpus and dictionary, you need to provide the number of topics as well. Apart from that, alpha and eta are hyperparameters that affect sparsity of the topics. According to the Gensim docs, both defaults to 1.0/num_topics prior (we’ll use default for the base model).\n> **chunksize** controls how many documents are processed at a time in the training algorithm. Increasing chunksize will speed up training, at least as long as the chunk of documents easily fit into memory.\n> **passes** controls how often we train the model on the entire corpus (set to 10). Another word for passes might be “epochs”. iterations is somewhat technical, but essentially it controls how often we repeat a particular loop over each document. It is important to set the number of “passes” and “iterations” high enough.\npython\n\n```\n# Build LDA model\nlda_model = gensim.models.LdaMulticore(corpus=corpus,\n                                       id2word=id2word,\n                                       num_topics=10, \n                                       random_state=100,\n                                       chunksize=100,\n                                       passes=10,\n                                       per_word_topics=True)\n```\n\n**View the topics in LDA model**\nThe above LDA model is built with 10 different topics where each topic is a combination of keywords and each keyword contributes a certain weightage to the topic.\nYou can see the keywords for each topic and the weightage(importance) of each keyword using  _lda_model.print_topics()\\_\npython\n\n```\nfrom pprint import pprint\n\n# Print the Keyword in the 10 topics\npprint(lda_model.print_topics())\ndoc_lda = lda_model[corpus]\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA-6-1024x233.png)\n**Compute model perplexity and coherence score**\nLet’s calculate the baseline coherence score:\npython\n\n```\nfrom gensim.models import CoherenceModel\n\n# Compute Coherence Score\ncoherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')\ncoherence_lda = coherence_model_lda.get_coherence()\nprint('Coherence Score: ', coherence_lda)\n```\n\n_**Coherence Score: 0.301**_\n## Hyperparameter tuning\nFirst, let’s differentiate between model hyperparameters and model parameters:\n> **Model hyperparameters** can be thought of as settings for a machine learning algorithm that are tuned by the data scientist before training. Examples would be the number of trees in the random forest, or in our case, number of topics K\n> **Model parameters** can be thought of as what the model learns during training, such as the weights for each word in a given topic\nNow that we have the baseline coherence score for the default LDA model, let’s perform a series of sensitivity tests to help determine the following model hyperparameters:\n  1. Number of topics (K)\n  2. Dirichlet hyperparameter alpha: Document-topic density\n  3. Dirichlet hyperparameter beta: Word-topic density\n\n\nWe’ll perform these tests in sequence, one parameter at a time by keeping others constant and run them over the two different validation corpus sets. We’ll use  _**C_v**_ as our choice of metric for performance comparison.\npython\n\n```\n# supporting function\ndef compute_coherence_values(corpus, dictionary, k, a, b):\n    \n    lda_model = gensim.models.LdaMulticore(corpus=corpus,\n                                           id2word=dictionary,\n                                           num_topics=k, \n                                           random_state=100,\n                                           chunksize=100,\n                                           passes=10,\n                                           alpha=a,\n                                           eta=b)\n    \n    coherence_model_lda = CoherenceModel(model=lda_model, texts=data_lemmatized, dictionary=id2word, coherence='c_v')\n    \n    return coherence_model_lda.get_coherence()\n```\n\nLet’s call the function, and iterate it over the range of topics, alpha, and beta parameter values:\npython\n\n```\nimport numpy as np\nimport tqdm\n\ngrid = {}\ngrid['Validation_Set'] = {}\n\n# Topics range\nmin_topics = 2\nmax_topics = 11\nstep_size = 1\ntopics_range = range(min_topics, max_topics, step_size)\n\n# Alpha parameter\nalpha = list(np.arange(0.01, 1, 0.3))\nalpha.append('symmetric')\nalpha.append('asymmetric')\n\n# Beta parameter\nbeta = list(np.arange(0.01, 1, 0.3))\nbeta.append('symmetric')\n\n# Validation sets\nnum_of_docs = len(corpus)\ncorpus_sets = [gensim.utils.ClippedCorpus(corpus, int(num_of_docs*0.75)), \n               corpus]\n\ncorpus_title = ['75% Corpus', '100% Corpus']\n\nmodel_results = {'Validation_Set': [],\n                 'Topics': [],\n                 'Alpha': [],\n                 'Beta': [],\n                 'Coherence': []\n                }\n\n# Can take a long time to run\nif 1 == 1:\n    pbar = tqdm.tqdm(total=(len(beta)*len(alpha)*len(topics_range)*len(corpus_title)))\n    \n    # iterate through validation corpuses\n    for i in range(len(corpus_sets)):\n        # iterate through number of topics\n        for k in topics_range:\n            # iterate through alpha values\n            for a in alpha:\n                # iterare through beta values\n                for b in beta:\n                    # get the coherence score for the given parameters\n                    cv = compute_coherence_values(corpus=corpus_sets[i], dictionary=id2word, \n                                                  k=k, a=a, b=b)\n                    # Save the model results\n                    model_results['Validation_Set'].append(corpus_title[i])\n                    model_results['Topics'].append(k)\n                    model_results['Alpha'].append(a)\n                    model_results['Beta'].append(b)\n                    model_results['Coherence'].append(cv)\n                    \n                    pbar.update(1)\n    pd.DataFrame(model_results).to_csv('./results/lda_tuning_results.csv', index=False)\n    pbar.close()\n```\n\n## Investigate results\nLet’s start by determining the optimal number of topics. The chart below outlines the coherence score, C_v, for the number of topics across two validation sets, and a fixed alpha = 0.01 and beta = 0.1.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA-7-1024x554.png)\nWith the coherence score seems to keep increasing with the number of topics, it may make better sense to pick the model that gave the highest CV before flattening out or a major drop. In this case, we picked K=8.\nNext, we want to select the optimal alpha and beta parameters. While there are other sophisticated approaches to tackle the selection process, for this tutorial, we choose the values that yielded maximum C_v score for K=8.\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA-8.png)\n> alpha=0.01\n> beta=0.9\n> K=8\nThat yields approx. 17% improvement over the baseline score.\n## Final model\nLet’s train the final model using the above selected parameters:\npython\n\n```\nnum_topics = 8\n\nlda_model = gensim.models.LdaMulticore(corpus=corpus,\n                                           id2word=id2word,\n                                           num_topics=num_topics, \n                                           random_state=100,\n                                           chunksize=100,\n                                           passes=10,\n                                           alpha=0.01,\n                                           eta=0.9)\n```\n\n## Visualize topics\npython\n\n```\nimport pyLDAvis.gensim_models as gensimvis\nimport pickle \nimport pyLDAvis\n\n# Visualize the topics\npyLDAvis.enable_notebook()\n\nLDAvis_data_filepath = os.path.join('./results/ldavis_tuned_'+str(num_topics))\n\n# # this is a bit time consuming - make the if statement True\n# # if you want to execute visualization prep yourself\nif 1 == 1:\n    LDAvis_prepared = gensimvis.prepare(lda_model, corpus, id2word)\n    with open(LDAvis_data_filepath, 'wb') as f:\n        pickle.dump(LDAvis_prepared, f)\n\n# load the pre-prepared pyLDAvis data from disk\nwith open(LDAvis_data_filepath, 'rb') as f:\n    LDAvis_prepared = pickle.load(f)\n\npyLDAvis.save_html(LDAvis_prepared, './results/ldavis_tuned_'+ str(num_topics) +'.html')\n\nLDAvis_prepared\n```\n\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/03/LDA-9-1024x663.png)\n## Closing notes\nWe started with understanding why evaluating the topic model is essential. Next, we reviewed existing methods and scratched the surface of topic coherence, along with the available coherence measures. Then we built a default LDA model using Gensim implementation to establish the baseline coherence score and reviewed practical ways to optimize the LDA hyperparameters.\nHopefully, this article has managed to shed light on the underlying topic evaluation strategies, and intuitions behind it.\n**References:**\n  1. <http://qpleple.com/perplexity-to-evaluate-topic-models/>\n  2. <https://www.amazon.com/Machine-Learning-Probabilistic-Perspective-Computation/dp/0262018020>\n  3. <https://papers.nips.cc/paper/3700-reading-tea-leaves-how-humans-interpret-topic-models.pdf>\n  4. <https://github.com/mattilyra/pydataberlin-2017/blob/master/notebook/EvaluatingUnsupervisedModels.ipynb>\n  5. <https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/>\n  6. <http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf>\n  7. <http://palmetto.aksw.org/palmetto-webapp/>\n\n\nThanks for reading.  _If you have any feedback, please feel free to reach out by messaging me on_[ _LinkedIn_](https://www.linkedin.com/in/shashankkapadia/) _or shooting me an email (shmkapadia[at]gmail.com)_\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\nSK\nWritten By\n## [Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[See all from Shashank Kapadia](https://towardsdatascience.com/author/shashank%20kapadia/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[Model Evaluation](https://towardsdatascience.com/tag/model-evaluation/)[NLP](https://towardsdatascience.com/tag/nlp/)[topic model](https://towardsdatascience.com/tag/topic-model/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F&title=Evaluate%20Topic%20Models%3A%20Latent%20Dirichlet%20Allocation%20\\(LDA\\))\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F&title=Evaluate%20Topic%20Models%3A%20Latent%20Dirichlet%20Allocation%20\\(LDA\\))\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fevaluate-topic-model-in-python-latent-dirichlet-allocation-lda-7d57484bb5d0%2F&text=Evaluate%20Topic%20Models%3A%20Latent%20Dirichlet%20Allocation%20\\(LDA\\))\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/0zvNg_iyZONAMUL9c-scaled.jpg)](https://towardsdatascience.com/google-data-studio-its-free-but-is-it-any-good-debf5d11bbbd/)\n## [Google Data Studio. It's Free But Is It Any Good?](https://towardsdatascience.com/google-data-studio-its-free-but-is-it-any-good-debf5d11bbbd/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA product review based on my 6 major differentiators of BI tools.\n[Adam Finer](https://towardsdatascience.com/author/adamfiner/)\nNovember 26, 202010 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/07/08UaaBJJSfvxllIhM.jpg)](https://towardsdatascience.com/googles-minerva-solving-math-problems-with-ai-4f0a6aaabaf1/)\n## [Google's Minerva, solving math problems with AI](https://towardsdatascience.com/googles-minerva-solving-math-problems-with-ai-4f0a6aaabaf1/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nQuantitative reasoning is hard for humans and it is hard for computers. Minerva just got astonishing results in solving math problems\n[Salvatore Raieli](https://towardsdatascience.com/author/salvatore-raieli/)\nJuly 8, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/01/1DFrIIA5ob2dgtWKLk3gMaw.png)](https://towardsdatascience.com/gaussian-processes-from-scratch-cfc11715730c/)\n## [Gaussian Processes from Scratch](https://towardsdatascience.com/gaussian-processes-from-scratch-cfc11715730c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nGain a deeper understanding of Gaussian processes by implementing them with only NumPy\n[Theo Wolf](https://towardsdatascience.com/author/theo.wolf/)\nJanuary 6, 20245 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/05/1Cryf7iCXZ6d2N7oeYm1SVA-scaled.jpeg)](https://towardsdatascience.com/how-to-fix-kernel-error-in-jupyter-notebook-81619e195703/)\n## [How to Fix Kernel Error in Jupyter Notebook](https://towardsdatascience.com/how-to-fix-kernel-error-in-jupyter-notebook-81619e195703/)\n[Programming](https://towardsdatascience.com/category/programming/)\nMake your python codes run smoothly\n[Benjamin Nweke](https://towardsdatascience.com/author/benjaminnweke/)\nMay 26, 20224 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/09Lw8N9PftdLbO8Y4-scaled.jpg)](https://towardsdatascience.com/a-brief-introduction-to-neural-networks-a-classification-problem-43e68c770081/)\n## [A Brief Introduction to Neural Networks : a Classification Problem](https://towardsdatascience.com/a-brief-introduction-to-neural-networks-a-classification-problem-43e68c770081/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA practical beginner guide to Neural Networks in Python\n[Chayma Zatout](https://towardsdatascience.com/author/chim-so/)\nJanuary 24, 202319 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/10/0_43R9Srwce_5mtsG-scaled.jpg)](https://towardsdatascience.com/design-patterns-with-python-for-machine-learning-engineers-builder-45b8e749f134/)\n## [Design Patterns with Python for Machine Learning Engineers: Builder](https://towardsdatascience.com/design-patterns-with-python-for-machine-learning-engineers-builder-45b8e749f134/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nLearn how to use the Builder design pattern to enhance your code\n[Marcello Politi](https://towardsdatascience.com/author/marcellopoliti/)\nOctober 12, 20236 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/1KscTCCkFc73YMq4kdW9aGw.jpeg)](https://towardsdatascience.com/battling-open-book-exams-with-open-source-llms-c2225f3002d0/)\n## [Battling Open Book Exams with Open Source LLMs](https://towardsdatascience.com/battling-open-book-exams-with-open-source-llms-c2225f3002d0/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nIn the age where everyone uses ChatGPT for work and school, I am taking advantage of that to help me study in my university course\n[Jubayer Hossain Ahad](https://towardsdatascience.com/author/jubayerhossainahad/)\nJuly 19, 20249 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/12/0Nz1hCMhfgtWtTxu1.jpg)](https://towardsdatascience.com/intro-to-docker-containers-for-data-scientists-dda9f2cfe66e/)\n## [Intro to Docker Containers for Data Scientists](https://towardsdatascience.com/intro-to-docker-containers-for-data-scientists-dda9f2cfe66e/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA practical tutorial for setting up a local dev environment using Docker Container\n[Ido Leshem](https://towardsdatascience.com/author/leshem-ido/)\nDecember 20, 20236 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/02/1m-rEoJwi9xLRcrHTHlzyug.png)](https://towardsdatascience.com/create-a-bar-chart-race-animation-app-using-streamlit-and-raceplotly-e44495249f11/)\n## [Create a Bar Chart Race Animation App Using Streamlit and Raceplotly](https://towardsdatascience.com/create-a-bar-chart-race-animation-app-using-streamlit-and-raceplotly-e44495249f11/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nLearn How to Use Streamlit to Build an App that Generates Bar Chart Race Animations within Seconds and No Coding\n[My Data Talk](https://towardsdatascience.com/author/insightsbees/)\nFebruary 22, 20228 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/536288d74c9e/pages/",
  "body_markdown_path": "attachments/536288d74c9e/pages/archived-body.md",
  "local_html": "attachments/536288d74c9e/pages/archived-body.html",
  "body_source": "prior_capture"
}