{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Alexander Davis",
  "title_listed": "Topic Modeling Open-Source Research with the OpenAlex API",
  "keywords": "",
  "domain": "文本处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/topic-modeling-open-source-research-with-the-openalex-api-5191c7db9156/",
  "publish_date": "2024-07-16",
  "corpus_stage": "",
  "notes": "",
  "id": "7864c272c798",
  "collected_at": "2026-10-02T02:06:42",
  "title": "Topic Modeling Open-Source Research with the OpenAlex API | 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[Data Science](https://towardsdatascience.com/category/data-science/)\n# Topic Modeling Open-Source Research with the OpenAlex API\nAn overview of topic modeling global research through the OpenAlex API and visualizing results\n[Alex Davis](https://towardsdatascience.com/author/adavis08/)\nJuly 15, 20249 min read\n### Open-source intelligence (OSINT) is something that can add tremendous value to organizations. Insight gained from analyzing social media data, web data, or global research, can be great in supporting all kinds of analyses. This article will give an overview of using topic modeling to help us make sense of thousands of pieces of open-source research.\n![&quot;resorting to paper... #research# #proposal&quot; by catherinecronin is licensed under CC BY-SA 2.0. To view a copy of this license, visit https://creativecommons.org/licenses/by-sa/2.0/?ref=openverse.](../images/000.jpeg)\n\"resorting to paper... #research# #proposal\" by [catherinecronin](https://www.flickr.com/photos/catherinecronin/14326101068) is licensed under CC BY-SA 2.0. To view a copy of this license, visit <https://creativecommons.org/licenses/by-sa/2.0/?ref=openverse.>\n* * *\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n## **What is Topic Modeling?**\nTopic modeling is an unsupervised machine learning technique used to analyze documents and identity 'topics' using semantic similarity. This is similar to clustering, but not every document is exclusive to one topic. It is more about grouping the content found in a corpus. Topic modeling has many different applications but is mainly used to better understand large amounts of text data.\n![Image by Author](../images/001.png)\nImage by Author\nFor example, a retail chain may model customer surveys and reviews to identify negative reviews and drill down into the key issues outlined by their customers. In this case, we will import a large amount of articles and abstracts to understand the key topics in our dataset.\n_Note: Topic modeling can be computationally expensive at scale. In this example, I used the Amazon Sagemaker environment to take advantage of their CPU._\n* * *\n## OpenAlex\nOpenAlex is a free to use catalogue system of global research. They have indexed over 250 million pieces of news, articles, abstracts, and more.\n> [**OpenAlex**](https://openalex.org/)\nLuckily for us, they have a free (but limited) and flexible API that will allow us to quickly ingest tens of thousands of articles while also applying filters, such as year, type of media, keywords, etc.\n* * *\n## Creating a Data Pipeline\nWhile we ingest the data from the API, we will apply some criteria. First, we will only ingest documents where the year is between 2016 and 2022. We want fairly recent language as terms and taxonomy of certain subjects can change over long periods of time.\nWe will also add key terms and conduct multiple searches. While normally we would likely ingest random subject areas, we will use key terms to narrow our search. This way, we will have an idea of how may high-level topics we have, and can compare that to the output of the model. Below, we create a function where we can add key terms and conduct searches through the API.\npython\n\n```\nimport pandas as pd\nimport requests\n```\n\npython\n\n```\ndef import_data(pages, start_year, end_year, search_terms):\n\n    \"\"\"\n    This function is used to use the OpenAlex API, conduct a search on works, a return a dataframe with associated works.\n\n    Inputs: \n        - pages: int, number of pages to loop through\n        - search_terms: str, keywords to search for (must be formatted according to OpenAlex standards)\n        - start_year and end_year: int, years to set as a range for filtering works\n    \"\"\"\n\n    #create an empty dataframe\n    search_results = pd.DataFrame()\n\n    for page in range(1, pages):\n\n        #use paramters to conduct request and format to a dataframe\n        response = requests.get(f'https://api.openalex.org/works?page={page}&amp;per-page=200&amp;filter=publication_year:{start_year}-{end_year},type:article&amp;search={search_terms}')\n        data = pd.DataFrame(response.json()['results'])\n\n        #append to empty dataframe\n        search_results = pd.concat([search_results, data])\n\n    #subset to relevant features\n    search_results = search_results[[\"id\", \"title\", \"display_name\", \"publication_year\", \"publication_date\",\n                                        \"type\", \"countries_distinct_count\",\"institutions_distinct_count\",\n                                        \"has_fulltext\", \"cited_by_count\", \"keywords\", \"referenced_works_count\", \"abstract_inverted_index\"]]\n\n    return(search_results)\n```\n\nWe conduct 5 different searches, each being a different technology area. These technology areas are inspired by the DoD \"Critical Technology Areas\". See more here:\n> [**USD(R &E) Strategic Vision and Critical Technology Areas - DoD Research & Engineering, OUSD(R&E)**](https://www.cto.mil/usdre-strat-vision-critical-tech-areas/)\nHere is an example of a search using the required OpenAlex syntax:\npython\n\n```\n#search for Trusted AI and Autonomy\nai_search = import_data(35, 2016, 2024, \"'artificial intelligence' OR 'deep learn' OR 'neural net' OR 'autonomous' OR drone\")\n```\n\nAfter compiling our searches and dropping duplicate documents, we must clean the data to prepare it for our topic model. There are 2 main issues with our current output.\n  1. The abstracts are returned as an inverted index (due to legal reasons). However, we can use these to return the original text.\n  2. Once we obtain the original text, it will be raw and unprocessed, creating noise and hurting our model. We will conduct traditional NLP preprocessing to get it ready for the model.\n\n\nBelow is a function to return original text from an inverted index.\npython\n\n```\ndef undo_inverted_index(inverted_index):\n\n    \"\"\"\n    The purpose of the function is to 'undo' and inverted index. It inputs an inverted index and\n    returns the original string.\n    \"\"\"\n\n    #create empty lists to store uninverted index\n    word_index = []\n    words_unindexed = []\n\n    #loop through index and return key-value pairs\n    for k,v in inverted_index.items(): \n        for index in v: word_index.append([k,index])\n\n    #sort by the index\n    word_index = sorted(word_index, key = lambda x : x[1])\n\n    #join only the values and flatten\n    for pair in word_index:\n        words_unindexed.append(pair[0])\n    words_unindexed = ' '.join(words_unindexed)\n\n    return(words_unindexed)\n```\n\nNow that we have the raw text, we can conduct our traditional preprocessing steps, such as standardization, removing stop words, lemmatization, etc. Below are functions that can be mapped to a list or series of documents.\npython\n\n```\ndef preprocess(text):\n\n    \"\"\"\n    This function takes in a string, coverts it to lowercase, cleans\n    it (remove special character and numbers), and tokenizes it.\n    \"\"\"\n\n    #convert to lowercase\n    text = text.lower()\n\n    #remove special character and digits\n    text = re.sub(r'd+', '', text)\n    text = re.sub(r'[^ws]', '', text)\n\n    #tokenize\n    tokens = nltk.word_tokenize(text)\n\n    return(tokens)\n```\n\npython\n\n```\ndef remove_stopwords(tokens):\n\n    \"\"\"\n    This function takes in a list of tokens (from the 'preprocess' function) and \n    removes a list of stopwords. Custom stopwords can be added to the 'custom_stopwords' list.\n    \"\"\"\n\n    #set default and custom stopwords\n    stop_words = nltk.corpus.stopwords.words('english')\n    custom_stopwords = []\n    stop_words.extend(custom_stopwords)\n\n    #filter out stopwords\n    filtered_tokens = [word for word in tokens if word not in stop_words]\n\n    return(filtered_tokens)\n```\n\npython\n\n```\ndef lemmatize(tokens):\n\n    \"\"\"\n    This function conducts lemmatization on a list of tokens (from the 'remove_stopwords' function).\n    This shortens each word down to its root form to improve modeling results.\n    \"\"\"\n\n    #initalize lemmatizer and lemmatize\n    lemmatizer = nltk.WordNetLemmatizer()\n    lemmatized_tokens = [lemmatizer.lemmatize(token) for token in tokens]\n\n    return(lemmatized_tokens)\n```\n\npython\n\n```\ndef clean_text(text):\n\n    \"\"\"\n    This function uses the previously defined functions to take a string and\n    run it through the entire data preprocessing process.\n    \"\"\"\n\n    #clean, tokenize, and lemmatize a string\n    tokens = preprocess(text)\n    filtered_tokens = remove_stopwords(tokens)\n    lemmatized_tokens = lemmatize(filtered_tokens)\n    clean_text = ' '.join(lemmatized_tokens)\n\n    return(clean_text)\n```\n\nNow that we have a preprocessed series of documents, we can create our first topic model!\n* * *\n## Creating a Topic Model\nFor our topic model, we will use gensim to create a Latent Dirichlet Allocation (LDA) model. LDA is the most common model for topic modeling, as it is very effective in identifying high-level themes within a corpus. Below are the packages used to create the model.\npython\n\n```\nimport gensim.corpora as corpora\nfrom gensim.corpora import Dictionary\nfrom gensim.models.coherencemodel import CoherenceModel\nfrom gensim.models.ldamodel import LdaModel\n```\n\nBefore we create our model, we must prepare our corpus and ID mappings. This can be done with just a few lines of code.\npython\n\n```\n#convert the preprocessed text to a list\ndocuments = list(data[\"clean_text\"])\n\n#seperate by ' ' to tokenize each article\ntexts = [x.split(' ') for x in documents]\n\n#construct word ID mappings\nid2word = Dictionary(texts)\n\n#use word ID mappings to build corpus\ncorpus = [id2word.doc2bow(text) for text in texts]\n```\n\nNow we can create a topic model. As you will see below, there are many different parameters that will affect the model's performance. You can read about the many parameters in gensim's documentation.\npython\n\n```\n#build LDA model\nlda_model = LdaModel(corpus = corpus, id2word = id2word, num_topics = 10, decay = 0.5,\n                     random_state = 0, chunksize = 100, alpha = 'auto', per_word_topics = True)\n```\n\nThe most import parameter will be the number of topics. Here, we set an arbitrary 10. Since we don't know how many topics there _should_ be, this parameter should definitely be optimized. But how do we measure the quality of our model?\nThis is where coherence scores come in. The coherence score is a measure from 0–1. Coherence scores measure the quality of our topics by making sure they are sound and distinct. We want clear boundaries between well-defined topics. While this is a bit subjective in the end, it gives us a great idea of the quality of our results.\npython\n\n```\n#compute coherence score\ncoherence_model_lda = CoherenceModel(model = lda_model, texts = texts, dictionary = id2word, coherence = 'c_v')\ncoherence_score = coherence_model_lda.get_coherence()\nprint(coherence_score)\n```\n\nHere, we get a coherence score of about 0.48, which isn't too bad! But not ready for production.\n* * *\n## Visualize Our Topic Model\nTopic models can be difficult to visualize. Lucky for us, there is a great module 'pyLDAvis' that can automatically produce an interactive visualization that allows us to view our topics in a vector space and drill down into each topic.\npython\n\n```\nimport pyLDAvis\n\n#create Topic Distance Visualization \npyLDAvis.enable_notebook()\nlda_viz = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)\nlda_viz\n```\n\nAs you can see below, this produces a great visualization where we can get a quick idea of how our model performed. By looking into the vector space, we see some topics are distinct and well-defined. However, we also have some overlapping topics.\n![Image by Author](../images/002.gif)\nImage by Author\nWe can click on a topic to few the most relevant tokens. As we adjust the relevance metric (lambda), we can see topic-specific tokens by sliding it left, and seeing relevant but less topic-specific tokens by sliding it to the right.\nWhen clicking into each topic, I can vaguely see the topics that I originally searched for. For example, topic 5 seems to align with my 'human-machine interfaces' search. There is also a cluster of topics that seem to be related to biotechnology, but some are more clear than others.\n* * *\n## Optimize the Topic Model\nFrom the pyLDAvis interface and our coherence score of 0.48, there is definitely room for improvement. For our final step, lets write a function where we can loop through values for different parameters and try to optimize our coherence score. Below, is a function that tests different values of the number of topics and the decay rate. The function computes the coherence score for every combination of parameters and saves them in a data frame.\npython\n\n```\ndef lda_model_evaluation():\n\n    \"\"\"\n    This function loops through a number of parameters for an LDA model, creates the model,\n    computes the coherenece score, and saves the results in a pandas dataframe. The outputed dataframe\n    contains the values of the parameters tested and the resulting coherence score.\n    \"\"\"\n\n    #define empty lists to save results\n    topic_number, decay_rate_list, score  = [], [], []\n\n    #loop through a number of parameters\n    for topics in range(5,12):\n        for decay_rate in [0.5, 0.6, 0.7]:\n\n                #build LDA model\n                lda_model = LdaModel(corpus = corpus, id2word = id2word, num_topics = topics, decay = decay_rate,\n                               random_state = 0, chunksize = 100, alpha = 'auto', per_word_topics = True)\n\n                #compute coherence score\n                coherence_model_lda = CoherenceModel(model = lda_model, texts = texts, dictionary = id2word, coherence = 'c_v')\n                coherence_score = coherence_model_lda.get_coherence()\n\n                #append parameters to lists\n                topic_number.append(topics)\n                decay_rate_list.append(decay_rate)\n                score.append(coherence_score)\n\n                print(\"Model Saved\")\n\n    #gather result into a dataframe\n    results = {\"Number of Topics\": topic_number,\n                \"Decay Rate\": decay_rate_list,\n                \"Score\": score}\n\n    results = pd.DataFrame(results)\n\n    return(results) \n```\n\nJust by passing a couple of small ranges through two parameters, we identified parameters that increased our coherence score from 0.48 to 0.55, a sizable improvement.\n## Next Steps\nTo continue to build a production-level model, there is plenty of experimentation to be had with the parameters. Because LDA is so computationally expensive, I kept the experiment above limited and only compared about 20 different models. But with more time and power, we can compare hundreds of models.\nAs well, there are improvements to be made with our data pipeline. I noticed several words that may need to be added to our stop word list. Words like 'use' and 'department' are not adding any semantic value, especially for documents about different technologies. As well, there are technical terms that do not get processed correctly, resulting in a single letter or a group of letters. We could spend some time doing a bag-of-words analysis to identify those stop word opportunities. This would eliminate noise in our dataset.\n## Conclusion\nIn this article, we:\n  1. Got an introduction to topic modeling and the OpenAlex data source\n  2. Built a data pipeline to ingest data from an API and prepare it for an NLP model\n  3. Constructed an LDA model and visualized the results using pyLDAvis\n  4. Wrote code to help us find the optimal parameters\n  5. Discussed next steps for model improvement\n\n\n_This is my first Medium article, so I hope you enjoyed it. Please feel free to leave feedback, ask questions, or request other topics!_\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* * *\n![](../images/body-d879ad8ec57b4f95a4cd.jpeg)\nWritten By\n## [Alex Davis](https://towardsdatascience.com/author/adavis08/)\n[See all from Alex Davis](https://towardsdatascience.com/author/adavis08/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[NLP](https://towardsdatascience.com/tag/nlp/)[Research](https://towardsdatascience.com/tag/research/)[Topic Modeling](https://towardsdatascience.com/tag/topic-modeling/)[Visualization](https://towardsdatascience.com/tag/visualization/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%2F&title=Topic%20Modeling%20Open-Source%20Research%20with%20the%20OpenAlex%20API)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%2F&title=Topic%20Modeling%20Open-Source%20Research%20with%20the%20OpenAlex%20API)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%2F&text=Topic%20Modeling%20Open-Source%20Research%20with%20the%20OpenAlex%20API)\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/003.png)](https://towardsdatascience.com/twitter-political-compass-machine-a-nature-language-processing-approach-and-analysis-7e8152033495/)\n## [Twitter Political Compass Machine: A Nature Language Processing Approach and Analysis](https://towardsdatascience.com/twitter-political-compass-machine-a-nature-language-processing-approach-and-analysis-7e8152033495/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nWith the 2020 election going on, it is more important that we understand a politician's affiliation. Today, we will use ML to do that.\n[Ming Lun Wu](https://towardsdatascience.com/author/minglwu427/)\nOctober 26, 20207 min read\n  * [![](../images/004.jpeg)](https://towardsdatascience.com/show-streamlit-apps-in-your-medium-blog-520e98c7d51d/)\n## [Show Streamlit Apps in your Medium Blog](https://towardsdatascience.com/show-streamlit-apps-in-your-medium-blog-520e98c7d51d/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nFollow this tutorial to put your apps online in Medium posts.\n[Gustavo Santos](https://towardsdatascience.com/author/gustavorsantos/)\nMay 30, 20235 min read\n  * [![](../images/005.png)](https://towardsdatascience.com/getting-started-with-r-shiny-821eb0328e73/)\n## [Getting Started with R Shiny](https://towardsdatascience.com/getting-started-with-r-shiny-821eb0328e73/)\n[Programming](https://towardsdatascience.com/category/programming/)\nTake the first steps towards becoming an R shiny expert\n[Sheenal Srivastava](https://towardsdatascience.com/author/sheenalsrivastava/)\nOctober 15, 202110 min read\n  * [![](../images/006.gif)](https://towardsdatascience.com/predicting-a-ball-trajectory-4dbd9a1693ad/)\n## [Predicting a Ball Trajectory](https://towardsdatascience.com/predicting-a-ball-trajectory-4dbd9a1693ad/)\n[Programming](https://towardsdatascience.com/category/programming/)\nPolynomial Fit in Python with NumPy\n[Florian Trautweiler](https://towardsdatascience.com/author/florian-trautweiler/)\nJanuary 5, 20256 min read\n  * [![](../images/007.png)](https://towardsdatascience.com/using-a-transition-matrix-to-generate-text-in-python-c5e78495b09b/)\n## [Using a transition matrix to generate text in Python](https://towardsdatascience.com/using-a-transition-matrix-to-generate-text-in-python-c5e78495b09b/)\n[Programming](https://towardsdatascience.com/category/programming/)\nA simpler (and less efficient) way to create text than use neural nets.\n[Dimitris Panagopoulos](https://towardsdatascience.com/author/dpanagop-53386/)\nDecember 6, 20204 min read\n  * [![](../images/008.png)](https://towardsdatascience.com/a-framework-to-understand-how-low-quality-data-hurts-business-performance-386c10c4fe1e/)\n## [A Framework to Understand How Low-Quality Data Hurts Business Performance](https://towardsdatascience.com/a-framework-to-understand-how-low-quality-data-hurts-business-performance-386c10c4fe1e/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow should we reason about the importance and impact of data quality to the businesses we support as data practitioners?\n[Kevin Hu, PhD](https://towardsdatascience.com/author/kevinzenghu/)\nJuly 28, 20227 min read\n  * [![](../images/009.jpeg)](https://towardsdatascience.com/a-corporate-job-could-give-you-a-stronger-career-launch-in-data-science-875e6b6d392d/)\n## [A Corporate Job Could Give You a Stronger Career Launch in Data Science](https://towardsdatascience.com/a-corporate-job-could-give-you-a-stronger-career-launch-in-data-science-875e6b6d392d/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFrom someone who hated corporates for so long\n[Arunn Thevapalan](https://towardsdatascience.com/author/arunnthevapalan/)\nApril 14, 20225 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/5-nlp-models-that-you-need-to-know-about-754594a3225b/)\n## [5 NLP Models That You Need to Know About](https://towardsdatascience.com/5-nlp-models-that-you-need-to-know-about-754594a3225b/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA big part of data science is keeping up to date with new techniques and models.\n[Sara A. Metwalli](https://towardsdatascience.com/author/saraametwalli/)\nJanuary 26, 20217 min read\n  * [![](../images/011.png)](https://towardsdatascience.com/whats-inside-a-neural-network-799daf235463/)\n## [What's Inside a Neural Network?](https://towardsdatascience.com/whats-inside-a-neural-network-799daf235463/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nPlotting surface of error in 3D using PyTorch🔥\n[Aleksei Rozanov](https://towardsdatascience.com/author/alexroz/)\nSeptember 29, 20245 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/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\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\n\n",
  "metadata": {
    "title": "Topic Modeling Open-Source Research with the OpenAlex API | Towards Data Science",
    "description": "An overview of topic modeling global research through the OpenAlex API and visualizing results",
    "keywords": null,
    "author": "Alex Davis",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Topic Modeling Open-Source Research with the OpenAlex API",
    "og:description": "An overview of topic modeling global research through the OpenAlex API and visualizing results",
    "og:url": "https://towardsdatascience.com/topic-modeling-open-source-research-with-the-openalex-api-5191c7db9156/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/10Ij2ZNwGNOMufJDLgPagOw.jpeg",
    "og:image:width": "1024",
    "og:image:height": "768",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Alex Davis",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "9 min read",
    "article:published_time": "2024-07-15T21:59:37.000Z",
    "article:modified_time": "2024-07-15T21:59:37.000Z",
    "article:author": "https://towardsdatascience.com/author/adavis08/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_000.txt",
      "chars": 36
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_001.txt",
      "chars": 1380
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_002.txt",
      "chars": 162
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_003.txt",
      "chars": 696
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_004.txt",
      "chars": 412
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_005.txt",
      "chars": 515
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_006.txt",
      "chars": 408
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_007.txt",
      "chars": 417
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_008.txt",
      "chars": 171
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_009.txt",
      "chars": 310
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_010.txt",
      "chars": 200
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_011.txt",
      "chars": 214
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_012.txt",
      "chars": 152
    },
    {
      "language": "txt",
      "file": "attachments/7864c272c798/code/block_013.txt",
      "chars": 1478
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:39:19Z"
    },
    {
      "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:39:19Z"
    },
    {
      "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:39:19Z"
    },
    {
      "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:39:19Z"
    }
  ],
  "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/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/adavis08/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/nlp/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/research/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/topic-modeling/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/visualization/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/twitter-political-compass-machine-a-nature-language-processing-approach-and-analysis-7e8152033495/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/minglwu427/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/show-streamlit-apps-in-your-medium-blog-520e98c7d51d/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/gustavorsantos/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/getting-started-with-r-shiny-821eb0328e73/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/"
    },
    {
      "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://www.flickr.com/photos/catherinecronin/14326101068"
    },
    {
      "type": "external",
      "href": "https://creativecommons.org/licenses/by-sa/2.0/"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://openalex.org/"
    },
    {
      "type": "external",
      "href": "https://www.cto.mil/usdre-strat-vision-critical-tech-areas/"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=Topic+Modeling+Open-Source+Research+with+the+OpenAlex+API&u=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=Topic+Modeling+Open-Source+Research+with+the+OpenAlex+API&url=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=Topic+Modeling+Open-Source+Research+with+the+OpenAlex+API&url=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%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"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:24:03Z",
  "source_url": "https://towardsdatascience.com/topic-modeling-open-source-research-with-the-openalex-api-5191c7db9156/",
  "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[Data Science](https://towardsdatascience.com/category/data-science/)\n# Topic Modeling Open-Source Research with the OpenAlex API\nAn overview of topic modeling global research through the OpenAlex API and visualizing results\n[Alex Davis](https://towardsdatascience.com/author/adavis08/)\nJuly 15, 20249 min read\n### Open-source intelligence (OSINT) is something that can add tremendous value to organizations. Insight gained from analyzing social media data, web data, or global research, can be great in supporting all kinds of analyses. This article will give an overview of using topic modeling to help us make sense of thousands of pieces of open-source research.\n![&quot;resorting to paper... #research# #proposal&quot; by catherinecronin is licensed under CC BY-SA 2.0. To view a copy of this license, visit https://creativecommons.org/licenses/by-sa/2.0/?ref=openverse.](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/10Ij2ZNwGNOMufJDLgPagOw.jpeg)\n\"resorting to paper... #research# #proposal\" by [catherinecronin](https://www.flickr.com/photos/catherinecronin/14326101068) is licensed under CC BY-SA 2.0. To view a copy of this license, visit <https://creativecommons.org/licenses/by-sa/2.0/?ref=openverse.>\n* * *\nLearn this step by step with the interactive [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n## **What is Topic Modeling?**\nTopic modeling is an unsupervised machine learning technique used to analyze documents and identity 'topics' using semantic similarity. This is similar to clustering, but not every document is exclusive to one topic. It is more about grouping the content found in a corpus. Topic modeling has many different applications but is mainly used to better understand large amounts of text data.\n![Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/1NLnpzhcaVq4UqZAw_BF5LQ.png)\nImage by Author\nFor example, a retail chain may model customer surveys and reviews to identify negative reviews and drill down into the key issues outlined by their customers. In this case, we will import a large amount of articles and abstracts to understand the key topics in our dataset.\n_Note: Topic modeling can be computationally expensive at scale. In this example, I used the Amazon Sagemaker environment to take advantage of their CPU._\n* * *\n## OpenAlex\nOpenAlex is a free to use catalogue system of global research. They have indexed over 250 million pieces of news, articles, abstracts, and more.\n> [**OpenAlex**](https://openalex.org/)\nLuckily for us, they have a free (but limited) and flexible API that will allow us to quickly ingest tens of thousands of articles while also applying filters, such as year, type of media, keywords, etc.\n* * *\n## Creating a Data Pipeline\nWhile we ingest the data from the API, we will apply some criteria. First, we will only ingest documents where the year is between 2016 and 2022. We want fairly recent language as terms and taxonomy of certain subjects can change over long periods of time.\nWe will also add key terms and conduct multiple searches. While normally we would likely ingest random subject areas, we will use key terms to narrow our search. This way, we will have an idea of how may high-level topics we have, and can compare that to the output of the model. Below, we create a function where we can add key terms and conduct searches through the API.\npython\n\n```\nimport pandas as pd\nimport requests\n```\n\npython\n\n```\ndef import_data(pages, start_year, end_year, search_terms):\n\n    \"\"\"\n    This function is used to use the OpenAlex API, conduct a search on works, a return a dataframe with associated works.\n\n    Inputs: \n        - pages: int, number of pages to loop through\n        - search_terms: str, keywords to search for (must be formatted according to OpenAlex standards)\n        - start_year and end_year: int, years to set as a range for filtering works\n    \"\"\"\n\n    #create an empty dataframe\n    search_results = pd.DataFrame()\n\n    for page in range(1, pages):\n\n        #use paramters to conduct request and format to a dataframe\n        response = requests.get(f'https://api.openalex.org/works?page={page}&amp;per-page=200&amp;filter=publication_year:{start_year}-{end_year},type:article&amp;search={search_terms}')\n        data = pd.DataFrame(response.json()['results'])\n\n        #append to empty dataframe\n        search_results = pd.concat([search_results, data])\n\n    #subset to relevant features\n    search_results = search_results[[\"id\", \"title\", \"display_name\", \"publication_year\", \"publication_date\",\n                                        \"type\", \"countries_distinct_count\",\"institutions_distinct_count\",\n                                        \"has_fulltext\", \"cited_by_count\", \"keywords\", \"referenced_works_count\", \"abstract_inverted_index\"]]\n\n    return(search_results)\n```\n\nWe conduct 5 different searches, each being a different technology area. These technology areas are inspired by the DoD \"Critical Technology Areas\". See more here:\n> [**USD(R &E) Strategic Vision and Critical Technology Areas - DoD Research & Engineering, OUSD(R&E)**](https://www.cto.mil/usdre-strat-vision-critical-tech-areas/)\nHere is an example of a search using the required OpenAlex syntax:\npython\n\n```\n#search for Trusted AI and Autonomy\nai_search = import_data(35, 2016, 2024, \"'artificial intelligence' OR 'deep learn' OR 'neural net' OR 'autonomous' OR drone\")\n```\n\nAfter compiling our searches and dropping duplicate documents, we must clean the data to prepare it for our topic model. There are 2 main issues with our current output.\n  1. The abstracts are returned as an inverted index (due to legal reasons). However, we can use these to return the original text.\n  2. Once we obtain the original text, it will be raw and unprocessed, creating noise and hurting our model. We will conduct traditional NLP preprocessing to get it ready for the model.\n\n\nBelow is a function to return original text from an inverted index.\npython\n\n```\ndef undo_inverted_index(inverted_index):\n\n    \"\"\"\n    The purpose of the function is to 'undo' and inverted index. It inputs an inverted index and\n    returns the original string.\n    \"\"\"\n\n    #create empty lists to store uninverted index\n    word_index = []\n    words_unindexed = []\n\n    #loop through index and return key-value pairs\n    for k,v in inverted_index.items(): \n        for index in v: word_index.append([k,index])\n\n    #sort by the index\n    word_index = sorted(word_index, key = lambda x : x[1])\n\n    #join only the values and flatten\n    for pair in word_index:\n        words_unindexed.append(pair[0])\n    words_unindexed = ' '.join(words_unindexed)\n\n    return(words_unindexed)\n```\n\nNow that we have the raw text, we can conduct our traditional preprocessing steps, such as standardization, removing stop words, lemmatization, etc. Below are functions that can be mapped to a list or series of documents.\npython\n\n```\ndef preprocess(text):\n\n    \"\"\"\n    This function takes in a string, coverts it to lowercase, cleans\n    it (remove special character and numbers), and tokenizes it.\n    \"\"\"\n\n    #convert to lowercase\n    text = text.lower()\n\n    #remove special character and digits\n    text = re.sub(r'd+', '', text)\n    text = re.sub(r'[^ws]', '', text)\n\n    #tokenize\n    tokens = nltk.word_tokenize(text)\n\n    return(tokens)\n```\n\npython\n\n```\ndef remove_stopwords(tokens):\n\n    \"\"\"\n    This function takes in a list of tokens (from the 'preprocess' function) and \n    removes a list of stopwords. Custom stopwords can be added to the 'custom_stopwords' list.\n    \"\"\"\n\n    #set default and custom stopwords\n    stop_words = nltk.corpus.stopwords.words('english')\n    custom_stopwords = []\n    stop_words.extend(custom_stopwords)\n\n    #filter out stopwords\n    filtered_tokens = [word for word in tokens if word not in stop_words]\n\n    return(filtered_tokens)\n```\n\npython\n\n```\ndef lemmatize(tokens):\n\n    \"\"\"\n    This function conducts lemmatization on a list of tokens (from the 'remove_stopwords' function).\n    This shortens each word down to its root form to improve modeling results.\n    \"\"\"\n\n    #initalize lemmatizer and lemmatize\n    lemmatizer = nltk.WordNetLemmatizer()\n    lemmatized_tokens = [lemmatizer.lemmatize(token) for token in tokens]\n\n    return(lemmatized_tokens)\n```\n\npython\n\n```\ndef clean_text(text):\n\n    \"\"\"\n    This function uses the previously defined functions to take a string and\n    run it through the entire data preprocessing process.\n    \"\"\"\n\n    #clean, tokenize, and lemmatize a string\n    tokens = preprocess(text)\n    filtered_tokens = remove_stopwords(tokens)\n    lemmatized_tokens = lemmatize(filtered_tokens)\n    clean_text = ' '.join(lemmatized_tokens)\n\n    return(clean_text)\n```\n\nNow that we have a preprocessed series of documents, we can create our first topic model!\n* * *\n## Creating a Topic Model\nFor our topic model, we will use gensim to create a Latent Dirichlet Allocation (LDA) model. LDA is the most common model for topic modeling, as it is very effective in identifying high-level themes within a corpus. Below are the packages used to create the model.\npython\n\n```\nimport gensim.corpora as corpora\nfrom gensim.corpora import Dictionary\nfrom gensim.models.coherencemodel import CoherenceModel\nfrom gensim.models.ldamodel import LdaModel\n```\n\nBefore we create our model, we must prepare our corpus and ID mappings. This can be done with just a few lines of code.\npython\n\n```\n#convert the preprocessed text to a list\ndocuments = list(data[\"clean_text\"])\n\n#seperate by ' ' to tokenize each article\ntexts = [x.split(' ') for x in documents]\n\n#construct word ID mappings\nid2word = Dictionary(texts)\n\n#use word ID mappings to build corpus\ncorpus = [id2word.doc2bow(text) for text in texts]\n```\n\nNow we can create a topic model. As you will see below, there are many different parameters that will affect the model's performance. You can read about the many parameters in gensim's documentation.\npython\n\n```\n#build LDA model\nlda_model = LdaModel(corpus = corpus, id2word = id2word, num_topics = 10, decay = 0.5,\n                     random_state = 0, chunksize = 100, alpha = 'auto', per_word_topics = True)\n```\n\nThe most import parameter will be the number of topics. Here, we set an arbitrary 10. Since we don't know how many topics there _should_ be, this parameter should definitely be optimized. But how do we measure the quality of our model?\nThis is where coherence scores come in. The coherence score is a measure from 0–1. Coherence scores measure the quality of our topics by making sure they are sound and distinct. We want clear boundaries between well-defined topics. While this is a bit subjective in the end, it gives us a great idea of the quality of our results.\npython\n\n```\n#compute coherence score\ncoherence_model_lda = CoherenceModel(model = lda_model, texts = texts, dictionary = id2word, coherence = 'c_v')\ncoherence_score = coherence_model_lda.get_coherence()\nprint(coherence_score)\n```\n\nHere, we get a coherence score of about 0.48, which isn't too bad! But not ready for production.\n* * *\n## Visualize Our Topic Model\nTopic models can be difficult to visualize. Lucky for us, there is a great module 'pyLDAvis' that can automatically produce an interactive visualization that allows us to view our topics in a vector space and drill down into each topic.\npython\n\n```\nimport pyLDAvis\n\n#create Topic Distance Visualization \npyLDAvis.enable_notebook()\nlda_viz = pyLDAvis.gensim.prepare(lda_model, corpus, id2word)\nlda_viz\n```\n\nAs you can see below, this produces a great visualization where we can get a quick idea of how our model performed. By looking into the vector space, we see some topics are distinct and well-defined. However, we also have some overlapping topics.\n![Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/07/15SW1vwUjhpwC1KkkQ1i8_Q.gif)\nImage by Author\nWe can click on a topic to few the most relevant tokens. As we adjust the relevance metric (lambda), we can see topic-specific tokens by sliding it left, and seeing relevant but less topic-specific tokens by sliding it to the right.\nWhen clicking into each topic, I can vaguely see the topics that I originally searched for. For example, topic 5 seems to align with my 'human-machine interfaces' search. There is also a cluster of topics that seem to be related to biotechnology, but some are more clear than others.\n* * *\n## Optimize the Topic Model\nFrom the pyLDAvis interface and our coherence score of 0.48, there is definitely room for improvement. For our final step, lets write a function where we can loop through values for different parameters and try to optimize our coherence score. Below, is a function that tests different values of the number of topics and the decay rate. The function computes the coherence score for every combination of parameters and saves them in a data frame.\npython\n\n```\ndef lda_model_evaluation():\n\n    \"\"\"\n    This function loops through a number of parameters for an LDA model, creates the model,\n    computes the coherenece score, and saves the results in a pandas dataframe. The outputed dataframe\n    contains the values of the parameters tested and the resulting coherence score.\n    \"\"\"\n\n    #define empty lists to save results\n    topic_number, decay_rate_list, score  = [], [], []\n\n    #loop through a number of parameters\n    for topics in range(5,12):\n        for decay_rate in [0.5, 0.6, 0.7]:\n\n                #build LDA model\n                lda_model = LdaModel(corpus = corpus, id2word = id2word, num_topics = topics, decay = decay_rate,\n                               random_state = 0, chunksize = 100, alpha = 'auto', per_word_topics = True)\n\n                #compute coherence score\n                coherence_model_lda = CoherenceModel(model = lda_model, texts = texts, dictionary = id2word, coherence = 'c_v')\n                coherence_score = coherence_model_lda.get_coherence()\n\n                #append parameters to lists\n                topic_number.append(topics)\n                decay_rate_list.append(decay_rate)\n                score.append(coherence_score)\n\n                print(\"Model Saved\")\n\n    #gather result into a dataframe\n    results = {\"Number of Topics\": topic_number,\n                \"Decay Rate\": decay_rate_list,\n                \"Score\": score}\n\n    results = pd.DataFrame(results)\n\n    return(results) \n```\n\nJust by passing a couple of small ranges through two parameters, we identified parameters that increased our coherence score from 0.48 to 0.55, a sizable improvement.\n## Next Steps\nTo continue to build a production-level model, there is plenty of experimentation to be had with the parameters. Because LDA is so computationally expensive, I kept the experiment above limited and only compared about 20 different models. But with more time and power, we can compare hundreds of models.\nAs well, there are improvements to be made with our data pipeline. I noticed several words that may need to be added to our stop word list. Words like 'use' and 'department' are not adding any semantic value, especially for documents about different technologies. As well, there are technical terms that do not get processed correctly, resulting in a single letter or a group of letters. We could spend some time doing a bag-of-words analysis to identify those stop word opportunities. This would eliminate noise in our dataset.\n## Conclusion\nIn this article, we:\n  1. Got an introduction to topic modeling and the OpenAlex data source\n  2. Built a data pipeline to ingest data from an API and prepare it for an NLP model\n  3. Constructed an LDA model and visualized the results using pyLDAvis\n  4. Wrote code to help us find the optimal parameters\n  5. Discussed next steps for model improvement\n\n\n_This is my first Medium article, so I hope you enjoyed it. Please feel free to leave feedback, ask questions, or request other topics!_\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* * *\n![](https://assets.insightmediagroup.io/media/1787657658380_gf1kgl.jpeg)\nWritten By\n## [Alex Davis](https://towardsdatascience.com/author/adavis08/)\n[See all from Alex Davis](https://towardsdatascience.com/author/adavis08/)\n[Data Science](https://towardsdatascience.com/tag/data-science/)[NLP](https://towardsdatascience.com/tag/nlp/)[Research](https://towardsdatascience.com/tag/research/)[Topic Modeling](https://towardsdatascience.com/tag/topic-modeling/)[Visualization](https://towardsdatascience.com/tag/visualization/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%2F&title=Topic%20Modeling%20Open-Source%20Research%20with%20the%20OpenAlex%20API)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%2F&title=Topic%20Modeling%20Open-Source%20Research%20with%20the%20OpenAlex%20API)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Ftopic-modeling-open-source-research-with-the-openalex-api-5191c7db9156%2F&text=Topic%20Modeling%20Open-Source%20Research%20with%20the%20OpenAlex%20API)\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/10/0vZGpGsQD1XQpzSjO.png)](https://towardsdatascience.com/twitter-political-compass-machine-a-nature-language-processing-approach-and-analysis-7e8152033495/)\n## [Twitter Political Compass Machine: A Nature Language Processing Approach and Analysis](https://towardsdatascience.com/twitter-political-compass-machine-a-nature-language-processing-approach-and-analysis-7e8152033495/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nWith the 2020 election going on, it is more important that we understand a politician's affiliation. Today, we will use ML to do that.\n[Ming Lun Wu](https://towardsdatascience.com/author/minglwu427/)\nOctober 26, 20207 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/05/1mLxYCGNIyY9NeOKn17G5pw-scaled.jpeg)](https://towardsdatascience.com/show-streamlit-apps-in-your-medium-blog-520e98c7d51d/)\n## [Show Streamlit Apps in your Medium Blog](https://towardsdatascience.com/show-streamlit-apps-in-your-medium-blog-520e98c7d51d/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nFollow this tutorial to put your apps online in Medium posts.\n[Gustavo Santos](https://towardsdatascience.com/author/gustavorsantos/)\nMay 30, 20235 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/10/1ccpzE1GVG7hgD3hAhTbD2A.png)](https://towardsdatascience.com/getting-started-with-r-shiny-821eb0328e73/)\n## [Getting Started with R Shiny](https://towardsdatascience.com/getting-started-with-r-shiny-821eb0328e73/)\n[Programming](https://towardsdatascience.com/category/programming/)\nTake the first steps towards becoming an R shiny expert\n[Sheenal Srivastava](https://towardsdatascience.com/author/sheenalsrivastava/)\nOctober 15, 202110 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/01/1mi713PTCu4Ghy679-qf0aQ.gif)](https://towardsdatascience.com/predicting-a-ball-trajectory-4dbd9a1693ad/)\n## [Predicting a Ball Trajectory](https://towardsdatascience.com/predicting-a-ball-trajectory-4dbd9a1693ad/)\n[Programming](https://towardsdatascience.com/category/programming/)\nPolynomial Fit in Python with NumPy\n[Florian Trautweiler](https://towardsdatascience.com/author/florian-trautweiler/)\nJanuary 5, 20256 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/1dQQliW3e1hIk7buYy171Ow.png)](https://towardsdatascience.com/using-a-transition-matrix-to-generate-text-in-python-c5e78495b09b/)\n## [Using a transition matrix to generate text in Python](https://towardsdatascience.com/using-a-transition-matrix-to-generate-text-in-python-c5e78495b09b/)\n[Programming](https://towardsdatascience.com/category/programming/)\nA simpler (and less efficient) way to create text than use neural nets.\n[Dimitris Panagopoulos](https://towardsdatascience.com/author/dpanagop-53386/)\nDecember 6, 20204 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/07/1vtS3GEkxsT_s1aTbRDs4Sg.png)](https://towardsdatascience.com/a-framework-to-understand-how-low-quality-data-hurts-business-performance-386c10c4fe1e/)\n## [A Framework to Understand How Low-Quality Data Hurts Business Performance](https://towardsdatascience.com/a-framework-to-understand-how-low-quality-data-hurts-business-performance-386c10c4fe1e/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nHow should we reason about the importance and impact of data quality to the businesses we support as data practitioners?\n[Kevin Hu, PhD](https://towardsdatascience.com/author/kevinzenghu/)\nJuly 28, 20227 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1-VJ2d9CTHIggYMahaQtzag-scaled.jpeg)](https://towardsdatascience.com/a-corporate-job-could-give-you-a-stronger-career-launch-in-data-science-875e6b6d392d/)\n## [A Corporate Job Could Give You a Stronger Career Launch in Data Science](https://towardsdatascience.com/a-corporate-job-could-give-you-a-stronger-career-launch-in-data-science-875e6b6d392d/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nFrom someone who hated corporates for so long\n[Arunn Thevapalan](https://towardsdatascience.com/author/arunnthevapalan/)\nApril 14, 20225 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/0PzR51o-4Or3ZcJOC-scaled.jpg)](https://towardsdatascience.com/5-nlp-models-that-you-need-to-know-about-754594a3225b/)\n## [5 NLP Models That You Need to Know About](https://towardsdatascience.com/5-nlp-models-that-you-need-to-know-about-754594a3225b/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA big part of data science is keeping up to date with new techniques and models.\n[Sara A. Metwalli](https://towardsdatascience.com/author/saraametwalli/)\nJanuary 26, 20217 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/09/1VtLefFL2ewkxRx1U0NegCw.png)](https://towardsdatascience.com/whats-inside-a-neural-network-799daf235463/)\n## [What's Inside a Neural Network?](https://towardsdatascience.com/whats-inside-a-neural-network-799daf235463/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nPlotting surface of error in 3D using PyTorch🔥\n[Aleksei Rozanov](https://towardsdatascience.com/author/alexroz/)\nSeptember 29, 20245 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/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\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\n\n",
  "body_base_path": "attachments/7864c272c798/pages/",
  "body_markdown_path": "attachments/7864c272c798/pages/archived-body.md",
  "local_html": "attachments/7864c272c798/pages/archived-body.html",
  "body_source": "prior_capture"
}