{ "cells": [ { "cell_type": "markdown", "id": "1178c7d5", "metadata": {}, "source": [ "# Topic Modeling (Gensim Library)\n", "\n", "\n", "**Topic Modeling** - hier auch als “Themenanalyse” bezeichnet - beschreibt ein Verfahren des unüberwachten maschinellen Lernens, bei dem latente Themen auf Basis häufig gemeinsam auftretender Wörter explorativ identifiziert werden. Wir versuchen also durch das gemeinsame Auftreten von Wörtern auf latente Themen, die dieses Vorkommen erklären, zu schliessen." ] }, { "cell_type": "markdown", "id": "cf625cbd", "metadata": {}, "source": [ "## Ablauf...\n", "\n", "* [Run Code](#1-bullet)\n", "* [Tabelle mit Texten importieren](#2-bullet)\n", "* [Den Text \"reinigen\" und Stop-Wörter entfernen](#3-bullet)\n", "* [Lemmatisierung von Wörtern](#4-bullet)\n", "* [Part of Speech Tagging ](#5-bullet)\n", "* [Topic Modell trainieren](6#-bullet)\n", "* [Topics visualisieren](#7-bullet)\n", "* [Im Originaltext recherchieren](#8-bullet)\n" ] }, { "attachments": {}, "cell_type": "markdown", "id": "bfc8fc5c", "metadata": {}, "source": [ "## Run Code \n", "\n", "Um Code in *Jupyter Notebooks* auszühren, müssen Sie auf **Run** klicken, das sich in der Menüleiste befindet. Klicken Sie dafür zunächst auf das Feld, das Sie ausführen möchten und anschließend auf **Run**. Sie können auch 'Shift' und 'Enter' verwenden. Wird das Feld gerade ausgeführt, erscheint links im Kästchen ein Sternchen. Dies bedeutet, dass das Programm gerade arbeitet. Wurde das Feld erfolgreich ausgeführt, erscheint eine Nummer im selben Kästchen. Gibt es einen Fehler, erscheint eine Fehlermeldung." ] }, { "cell_type": "code", "execution_count": null, "id": "4ba3ea08", "metadata": {}, "outputs": [], "source": [ "#languange processing imports\n", "import gensim\n", "from gensim.models import LdaModel\n", "from gensim import models, corpora, similarities\n", "import gensim, spacy, logging, warnings\n", "import matplotlib.pyplot as plt\n", "import nltk\n", "from nltk.corpus import stopwords\n", "import sys\n", "import re, numpy as np, pandas as pd\n", "from pprint import pprint\n", "import spacy\n", "from openpyxl import Workbook\n", "\n", "#For the text overview\n", "from nltk import FreqDist\n", "\n", "#Word Cloud and Visualization\n", "\n", "from wordcloud import WordCloud, STOPWORDS\n", "from sklearn.feature_extraction.text import CountVectorizer\n", "import matplotlib.ticker as mtick\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "id": "799ce53b", "metadata": {}, "source": [ "## Tabelle mit Texten importieren \n", "\n", "Hier sehen Sie die importierte Excel-Tabelle" ] }, { "cell_type": "code", "execution_count": null, "id": "21e0aa3c", "metadata": { "scrolled": false }, "outputs": [], "source": [ "df = pd.read_excel(('Data/spanische_grippe.xlsx'), engine='openpyxl',) \n", "df.head()" ] }, { "cell_type": "markdown", "id": "8a67f077", "metadata": {}, "source": [ "## Den Text \"reinigen\" und Stop-Wörter entfernen \n", "\n", "Nun wird der Text gereinigt, das heißt, es werden Satzzeichen entfernt, alle Wörter werden einheitlich klein geschrieben und Stop-Wörter werden entfernt. Stop-Wörter sind Wörter, die häufig vorkommen und haben für gewöhnlich keine Relevanz für weitere Analysen. Hierzu gehören Wörter wie \"und\", \"auf\", \"mit\" usw. " ] }, { "cell_type": "code", "execution_count": null, "id": "6c143851", "metadata": { "scrolled": true }, "outputs": [], "source": [ "#Functions to clean, tokenize, and stem the data\n", "import nltk\n", "nltk.download('stopwords')\n", "nltk.download('punkt')\n", "\n", "def initial_clean(text):\n", " text = re.sub(r'[^\\w\\s]','',text)\n", " text = text.lower() \n", " text = nltk.word_tokenize(text, language = 'german')\n", " return text\n", "\n", "stop_words = stopwords.words('german')#change the language here\n", "\n", "stop_words.extend([]) #add additional words here\n", "def remove_stop_words(text):\n", " return [word for word in text if word not in stop_words]\n", "\n", "def apply_all(text):\n", " return remove_stop_words(initial_clean(text))\n", "df['tokenized'] = df['Text'].apply(apply_all) \n", "df.head()" ] }, { "cell_type": "markdown", "id": "cdf4637e", "metadata": {}, "source": [ "## Lemmatisierung " ] }, { "cell_type": "code", "execution_count": null, "id": "2cac143a", "metadata": { "scrolled": true }, "outputs": [], "source": [ "def process_words(texts):\n", " texts_out = []\n", " \n", " nlp = spacy.load('de_core_news_sm') #disable functions here\n", " for sent in texts:\n", " doc = nlp(\" \".join(sent)) \n", " texts_out.append([token.lemma_ for token in doc])\n", " return texts_out\n", "\n", "df['final'] = process_words(df['tokenized'])" ] }, { "cell_type": "markdown", "id": "3641f8b6", "metadata": {}, "source": [ "## Topic Modell trainieren\n", "\n", "Die Gensim Bibliothek stellt eine Reihe an Parameter zur Verfügung. Um z. B. das Modell zu speichern, kann diese Funktion verwendet werden \"random_state = 1\". Probieren Sie weitere Funktionen aus, wie \"per_word_topics=True\" oder \"chunksize = 300\". " ] }, { "cell_type": "code", "execution_count": null, "id": "858caed5", "metadata": {}, "outputs": [], "source": [ "def train_lda(data):\n", " num_topics = 20\n", " dictionary = corpora.Dictionary(data)\n", " corpus = [dictionary.doc2bow(doc) for doc in data]\n", " lda = LdaModel(corpus=corpus, num_topics=num_topics, id2word=dictionary,\n", " minimum_probability=0.0, passes=20, iterations=200)\n", " return dictionary,corpus,lda\n", "\n", "dictionary,corpus,lda = train_lda(df['final'])" ] }, { "cell_type": "code", "execution_count": null, "id": "bd6b0d51", "metadata": { "scrolled": true }, "outputs": [], "source": [ "lda.show_topic(topicid=1, topn=20)" ] }, { "cell_type": "markdown", "id": "04c54c6c", "metadata": {}, "source": [ "## Topics visualisieren " ] }, { "cell_type": "code", "execution_count": null, "id": "181c0665", "metadata": {}, "outputs": [], "source": [ "import pyLDAvis\n", "import pyLDAvis.gensim \n", "import matplotlib.pyplot as plt\n", "%matplotlib inline\n", "pyLDAvis.enable_notebook()\n", "vis = pyLDAvis.gensim.prepare(lda, corpus, dictionary)\n", "vis" ] }, { "cell_type": "markdown", "id": "7f3a3043", "metadata": {}, "source": [ "## Im Originaltext recherchieren " ] }, { "cell_type": "code", "execution_count": null, "id": "1ee5a411", "metadata": { "scrolled": false }, "outputs": [], "source": [ "pd.set_option('display.max_colwidth', -1)\n", "df_text = df['Text']\n", "\n", "\n", "lines_ = ['unit']\n", "for line in df_text:\n", " if 'krank' in line: #insert here the word you are looking for\n", " lines_.append(line)\n", " \n", "lines_ = pd.DataFrame(lines_, columns =['Text'])\n", "df_select = pd.DataFrame(lines_['Text'])\n", "df_select[0:10] " ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" } }, "nbformat": 4, "nbformat_minor": 5 }