<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tim Denzler on Medium]]></title>
        <description><![CDATA[Stories by Tim Denzler on Medium]]></description>
        <link>https://medium.com/@tim-denzler?source=rss-232837455caa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UeISvXSMvfqRMrBrLPxM6g.jpeg</url>
            <title>Stories by Tim Denzler on Medium</title>
            <link>https://medium.com/@tim-denzler?source=rss-232837455caa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:43:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tim-denzler/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Beating the Octopus? — Predicting Football Matches using Elo, Linear Regression, and CNNs]]></title>
            <link>https://tim-denzler.medium.com/beating-the-octopus-predicting-football-matches-using-elo-linear-regression-and-cnns-c8eba8921cd7?source=rss-232837455caa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8eba8921cd7</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Tim Denzler]]></dc:creator>
            <pubDate>Sat, 10 Feb 2024 11:08:16 GMT</pubDate>
            <atom:updated>2024-02-10T11:19:50.985Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beating the Octopus? — Predicting Football Matches using Elo, Linear Regression, and CNNs</h3><p>In the summer of 2010, Paul the Octopus kept a whole nation one edge after correctly predicting all matches of the German national team, as well as the final of the FIFA World Cup in South Africa. Paul communicated his predictions by choosing food from boxes decorated with each contender‘s national flag. To put this into context: the chances of predicting the correct outcome for all these matches are approximately <strong>0.4%</strong> (in other words <strong>1:256</strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHRIJ4FuaF1QlIlkEs6e6Q.jpeg" /></figure><p>In the spirit of this incredible and (arguably) lucky achievement, I was wondering if it might be possible to replicate these seemingly supernatural abilities with modern Machine Learning (ML) methods rather than random guessing and thus disembarked on this little side-project.</p><h4>Data scraping and scope</h4><p>Similar to my previous project (Bundesliga Streamlit dashboard BuLiAn: <a href="https://tim-denzler.medium.com/is-bayern-m%C3%BCnchen-the-laziest-team-in-the-german-bundesliga-770cfbd989c7">Article</a> | <a href="https://github.com/tdenzl/BuLiAn/tree/main">Repo</a> | <a href="https://bulian-tdenzl.streamlit.app/">Dashboard</a>), data was scraped from a popular football news portal using the Python library BeautifulSoup in combination with multiprocessing to speed up the whole process. As this time more data was required to train an actual model, the scope was extended to include data from several football leagues:</p><ul><li><strong>Germany (1. &amp; 2. Bundesliga):</strong> Season 2013/14 until 2023/24</li><li><strong>Spain (La Liga):</strong> Season 2018/19 until 2023/24</li><li><strong>Austria (1. Bundesliga):</strong> Season 2018/19 until 2023/24</li><li><strong>Switzerland (Super League):</strong> Season 2022/23 until 2023/24</li><li><strong>Brazil (Campeonato Serie A):</strong> Season 2013/14 until 2023/24</li><li><strong>Netherlands (Eredivisie):</strong> Season 2018/19 until 2023/24</li><li><strong>France (Ligue 1):</strong> Season 2018/19 until 2023/24</li><li><strong>England (Premier League):</strong> Season 2018/19 until 2023/24</li><li><strong>Italy (Seria A):</strong> Season 2018/19 until 2023/24</li><li><strong>Portugal (Primeira Liga):</strong> Season 2018/19 until 2023/24</li><li><strong>Turkey (Süper Lig):</strong> Season 2018/19 until 2023/24</li><li><strong>Greece (Super League):</strong> Season 2022/23 until 2023/24</li></ul><p>Inspired by Stübinger et al. [1], there was an attempt to include player ratings from EA SPORTS FIFA in the prediction model. However, this idea was discontinued after linking the virtual players with their counterparts from the real line-ups using the Levenshtein distance [2] leading to only about half of all line-ups ending up with more than 8 correctly matched players.</p><p>In total, <strong>12,637 matches</strong> in <strong>13 leagues</strong> were captured with their respective statistics in several tables including:</p><ul><li><strong>General match info:</strong> kick-off date, kick-off time, weekday, match day, season, referee, coaches</li><li><strong>Player Line-Ups &amp; Events: </strong>players in the starting formation, cards, cumulative yellow cards, substitutions</li><li><strong>Team stats:</strong> home indicator, air tackles, corners, crosses, distance covered, dribblings, fouls, goals, offsides, passes, possession, shots on goal, tackles, passes, and their respective success ratio if applicable</li></ul><h4>General Data Preprocessing</h4><p>Before doing any advanced data processing, each table was assigned a game_id (md5 hash over league, season, match day, and team names) to make it easier to join them later on. In addition, strings were cleaned by replacing left-over elements from the HTML pages, as well as converting them to lowercase and data type casting where necessary. The data was structured in a bronze (raw), silver (preprocessed), and gold (ingestion) layer.</p><h4>Calculating Elo Scores for Teams, Coaches and Players</h4><p>Intuitively, when thinking about a team’s performance winning against a team that is considered “better” should be weighted more than obliterating the underdog. After all, you would be more likely to brag to your friends about that time you nutmegged Messi, but less likely to tell them the same when your opponent that 12-year-old kid from down the street. In addition, winning with a 3-goal difference should also affect your perceived rating more than winning with fewer goals.</p><p>This is where the <strong>elo-system </strong>comes in place, which is commonly used to rate chess players but can also be applied in other sports like football [3]. In the elo-system, a team’s new rating <em>Rn </em>is calculated by adding its old rating <em>Ro</em> and the change in points <em>P</em> for the currently observed match:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/0*I2xApCdGwSgzf8f8" /></figure><p>To calculate the change in points <em>P</em>, the weight index <em>K</em> (commonly set to 20) is multiplied by the goal difference index <em>G</em> and the difference between the actual result (mapping 0 to a loss, 0.5 to a draw, and 1 to a win) and the expected result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/0*2uvjI28cTO8m3979" /></figure><p>The goal difference index <em>G</em> itself however is not just the difference in goals. For a goal difference of 0 or 1, it is set to 1; for a goal difference of 2, it is set to 1.5; and for a difference larger than 2, it follows the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/0*UBDcs1flKpBP6aVi" /></figure><p>The expected result <em>We</em> is calculated using the following formula, where <em>dr</em> is the difference in elo-ratings between the teams:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/0*Lm_aqMcLnZZMxVkG" /></figure><p>For this ML model, the weight index <em>K</em> was set to 20, and the starting elo-score of each team, player, and coach was set to 1300 before finally calculating each of their respective elo-scores prior to each kick-off.</p><h4>Predicting Playing Style with Linear Regression</h4><p>As the goal of the model is to predict the outcome of a game based on data that is known <strong>prior to the kick-off</strong>, it is essential to try to predict the playing style of each team. A suitable model to predict this kind of values is <strong>linear regression</strong> [4]. Of course, your playing style will differ drastically when facing a higher rating elo-team (e.g. Liverpool), as compared to a lower elo-rating team (e.g. Fürth).</p><p>The x-axis of our linear regression model should therefore be the elo-difference and the y-axis the observed stat. As more recent events (i.e. the current trend of a team) are more significant, weights are calculated based on a time dimension using a quadratic function and assigned to each data point. Below is a schematic depiction of a linear regression model for a team’s passes, where each data point is shown in different shades of blue (depicting their weight or “freshness”) and the red line depicting the curve fit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fykqnQ2xdWX6jeY7n1_6jA.png" /><figcaption>Schematic depiction of a team’s linear regression for passes</figcaption></figure><p>Based on this linear graph, we can now calculate the expected stats per game for each team by simply following the formula y = m*x + c, where <em>y</em> is the expected value, <em>m</em> is the coefficient of the graph, <em>x</em> is the elo-difference between the team and its opponent and <em>c</em> is the intercept of the graph.</p><h4>Training and Evaluating Convolutional Neuronal Networks</h4><p>Several <strong>Convolutional Neural Networks</strong> (CNNs) were trained using the TensorFlow library, each trying to predict a different target value. The neural networks were ingested with <strong>56 features:</strong> match day, weekday, kick-off time, elo-ratings of each team, coach, average player elo-rating and respective standard deviation, average cards given by the referee, and finally the expected stats of each team based on the linear-regression model.</p><p>Matches with missing data were removed, as well as the first 5 match days of each season, as the extended break in between seasons leads to uncertainty. In total, <strong>7,855 matches</strong> were eligible to be used for training and testing the model. Each model iterated <strong>100 epochs</strong> and the data was split into a <strong>training dataset (70%</strong>) and a <strong>test dataset (30%)</strong>. Even though several different layer combinations and unit amounts were tried, all three models showed the best performance with below similar hyperparameters.</p><p><strong>CNN-Model 1: Predicting the outcome (win_home, draw, win_away)</strong></p><p>The first model was trained to predict the <strong>outcome of a game</strong>, with the target being three classification labels. The first model had two intermediate layers (48 and 24 units), each with a dropout rate of 0.5.</p><pre>model = tf.keras.Sequential([<br>            normalizer,<br>            tf.keras.layers.Dense(48, activation=&#39;relu&#39;),<br>            tf.keras.layers.Dropout(0.5),<br>            tf.keras.layers.Dense(24, activation=&#39;relu&#39;),<br>            tf.keras.layers.Dropout(0.5),<br>            tf.keras.layers.Dense(N_CLASS, activation=&quot;softmax&quot;)<br>        ])<br><br>model.compile(optimizer=&#39;adam&#39;,<br>              loss=&quot;categorical_crossentropy&quot;,<br>              metrics=[&#39;accuracy&#39;])</pre><p>This model was able to predict the outcome of a match with an <strong>accuracy of 48.24%</strong> when evaluated against the test dataset.</p><p><strong>CNN-Model 2: Predicting a win of the home team</strong></p><p>The second model was trained to predict a <strong>home win</strong>, with the target being binary classification labels. The second model also had two intermediate layers (48 and 24 units), each with a dropout rate of 0.5.</p><pre>model = tf.keras.Sequential([<br>            normalizer,<br>            tf.keras.layers.Dense(48, activation=&#39;relu&#39;),<br>            tf.keras.layers.Dropout(0.5),<br>            tf.keras.layers.Dense(24, activation=&#39;relu&#39;),<br>            tf.keras.layers.Dropout(0.5),<br>            tf.keras.layers.Dense(N_CLASS, activation=&quot;softmax&quot;)<br>        ])<br><br>  model.compile(optimizer=&#39;adam&#39;,<br>                loss=&quot;binary_crossentropy&quot;,<br>                metrics=[&#39;accuracy&#39;])</pre><p>This model was able to predict the outcome of a home win with an <strong>accuracy of 62.35%</strong> when evaluated against the test dataset.</p><p><strong>CNN-Model 3: Predicting an over/ under 10.5 of corners</strong></p><p>The last model was trained to predict whether there will be <strong>more or less than 10.5 corners</strong> in a match, which is a popular prediction in sports betting with binary classification labels. The second model also had two intermediate layers (48 and 24 units), each with a dropout rate of 0.5.</p><pre>model = tf.keras.Sequential([<br>            normalizer,<br>            tf.keras.layers.Dense(48, activation=&#39;relu&#39;),<br>            tf.keras.layers.Dropout(0.5),<br>            tf.keras.layers.Dense(24, activation=&#39;relu&#39;),<br>            tf.keras.layers.Dropout(0.5),<br>            tf.keras.layers.Dense(N_CLASS, activation=&quot;softmax&quot;)<br>        ])<br><br>  model.compile(optimizer=&#39;adam&#39;,<br>                loss=&quot;binary_crossentropy&quot;,<br>                metrics=[&#39;accuracy&#39;])</pre><p>This model was able to predict the outcome of over or under 10.5 corners in a match with an <strong>accuracy of 58.89%</strong> when evaluated against the test dataset.</p><h4>Conclusion</h4><p>While certainly not as good as Paul the Octopus, the three different CNNs in combination with the elo-rating and linear regressions were able to predict different target outcomes of football matches to some extent. An interesting use case to follow up would be to evaluate how these CNNs fare against <strong>betting quotas from bookmakers</strong> and whether <strong>arbitrage</strong> is possible through this advantage.</p><p>Maybe there will be some simulation done on my blog in the future, so stay tuned and subscribe for updates!</p><h4>Links</h4><p>Github Repository: <a href="https://github.com/tdenzl/krake-paul">tdenzl/krake-paul (github.com)</a></p><h4>Sources</h4><p>[1] Stübinger, Johannes &amp; Mangold, Benedikt &amp; Knoll, Julian. (2019). <em>Machine Learning in Football Betting: Prediction of Match Results Based on Player Characteristics</em>. Applied Sciences. 10. 46. 10.3390/app10010046. <a href="https://www.researchgate.net/publication/338090323_Machine_Learning_in_Football_Betting_Prediction_of_Match_Results_Based_on_Player_Characteristics">(PDF) Machine Learning in Football Betting: Prediction of Match Results Based on Player Characteristics (researchgate.net)</a></p><p>[2] <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance — Wikipedia</a></p><p>[3] <a href="https://en.wikipedia.org/wiki/World_Football_Elo_Ratings">World Football Elo Ratings — Wikipedia</a></p><p>[4] <a href="https://en.wikipedia.org/wiki/Linear_regression">Linear regression — Wikipedia</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8eba8921cd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s in a song? Using LDA to find topics in over 120,000 songs]]></title>
            <link>https://tim-denzler.medium.com/whats-in-a-song-using-lda-to-find-topics-in-over-120-000-songs-53785767b692?source=rss-232837455caa------2</link>
            <guid isPermaLink="false">https://medium.com/p/53785767b692</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[music]]></category>
            <dc:creator><![CDATA[Tim Denzler]]></dc:creator>
            <pubDate>Fri, 14 May 2021 14:10:42 GMT</pubDate>
            <atom:updated>2021-05-16T11:28:01.032Z</atom:updated>
            <content:encoded><![CDATA[<h3>What’s in a Song? LDA Topic Modeling of over 120,000 Lyrics</h3><h4>How to find underlying topics in song lyrics by implementing Latent Dirichlet Allocation in Python using gensim, NLTK, and pyLDAvis</h4><p>Have you ever had the feeling that most popular songs on the radio or on the charts cover the same topics? Well…I did, which is why applied Topic Modeling to a corpus containing lyrics of over 120,000 songs in order to discover underlying themes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BpYJ1TRFupbMbslq" /><figcaption>Photo by <a href="https://unsplash.com/@cdx2?utm_source=medium&amp;utm_medium=referral">C D-X</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here are the main Python libraries used for this project:</p><ul><li><a href="https://pypi.org/project/langdetect/">langdetect</a> for filtering songs that are not primarily in English</li><li><a href="https://www.nltk.org/">NLTK</a> for preprocessing our song lyrics</li><li><a href="https://radimrehurek.com/gensim/">gensim</a> for generating our topic model</li><li><a href="https://github.com/bmabey/pyLDAvis">pyLDAvis</a> for visualizing our topic model</li></ul><p><strong>Dataset</strong></p><p>The main source of our topic model is the AZLyrics dataset from Kaggle [<a href="https://www.kaggle.com/albertsuarez/azlyrics">1</a>]. It contains approximately 147,000 songs scraped from AZ Lyrics available in multiple CSV files and includes artist names, artist URLs, song names, song URLs, and lyrics. If you want, you can also rerun the code provided by the dataset’s author to scrape your own data [<a href="https://github.com/AlbertSuarez/azlyrics-scraper">2</a>].</p><p><strong>Topic Modeling and Latent Dirichlet Allocation</strong></p><p>A topic model is a generative model that intends to discover underlying topics in a collection of documents and each documents’ assumed closeness to this topic. A popular and well-established Topic Modeling algorithm is Latent Dirichlet Allocation (LDA), which is a probabilistic generative model that builds on the assumption that every document in a literature corpus is a mixture of latent topics and each of these topics themselves is a probability distribution over words. For more information, you can check out the original paper by Blei et al. [<a href="https://www.jmlr.org/papers/volume3/blei03a/blei03a.pdf">3</a>], or these blog posts [<a href="https://towardsdatascience.com/light-on-math-machine-learning-intuitive-guide-to-latent-dirichlet-allocation-437c81220158">4</a>],[<a href="https://towardsdatascience.com/latent-dirichlet-allocation-lda-9d1cd064ffa2">5</a>].</p><p><strong>Step 1: Reading the CSV Files and language-based Filtering</strong></p><p>We start by importing the <em>csv</em> library to read our csv files, the <em>os</em> library for interacting with the operating system, and the <em>nltk</em> library for preprocessing. Optionally, you can import <a href="https://docs.python.org/3/library/pickle.html"><em>pickle</em></a><em> </em>to store interim results and <a href="https://github.com/tqdm/tqdm"><em>tqdm</em></a><em> </em>to track progress in your script.</p><p>As our data is stored in separate csv files, we go through each file and append each song’s lyrics to our <em>lyric_corpus</em> list. In addition, we use this opportunity to skip instances of songs that miss lyrics, or which are not primarily in English. We leverage the Python library <em>langdetect</em>,<em> </em>which<em> </em>utilizes a Naïve Bayes Classifier pre-trained on Wikipedia data, and set its probability threshold to 0.95.</p><pre>import csv<br>import os<br>import nltk<br>import pickle<br>from langdetect import detect_langs<br>from langdetect.lang_detect_exception import LangDetectException</pre><pre>lyric_corpus = []<br>lang_filtered = 0<br>for filename in os.listdir(&#39;azlyrics-scraper&#39;):<br>    path = &#39;./azlyrics-scraper/&#39;+filename<br>    with open(path, &#39;r&#39;) as f:<br>        data = csv.reader(f)<br>        headers = next(data)<br>        for row in data:<br>            if len(row)&lt; 5:<br>                continue<br>            if not row[4]:<br>                continue<br>            try:<br>                langlist = detect_langs(row[4])<br>                for l in langlist:<br>                    if l.prob &lt; 0.95 or l.lang != &#39;en&#39;:<br>                        lang_filtered += 1<br>                        continue<br>                    else:<br>                        lyric_corpus.append(row[4])<br>            except LangDetectException:<br>                continue</pre><p><strong>Step 2: Lyric Tokenization</strong></p><p>Next, we tokenize our lyrics using <em>NLTK’s RegexpTokenizer. </em>After doing this, our lyrics previously stored as a single String for each song are now a list of Strings of single words, also referred to as tokens.</p><pre>from nltk.tokenize import RegexpTokenizer</pre><pre>lyric_corpus_tokenized = []<br>tokenizer = RegexpTokenizer(r&#39;\w+&#39;)<br>for lyric in lyric_corpus:<br>    tokenized_lyric = tokenizer.tokenize(lyric.lower())<br>    lyric_corpus_tokenized.append(tokenized_lyric)</pre><p><strong>Step 3: Removing Numeric Tokens or Tokens with less than 3 Characters</strong></p><p>We then remove numeric tokens as well as tokens containing less than 3 characters (melodic sounds such as ‘oh’, ‘na’, ‘la’, ‘da’ distorted the topic model in previous iterations).</p><pre>for s,song in enumerate(lyric_corpus_tokenized):<br>    filtered_song = []    <br>    for token in song:<br>        if len(token) &gt; 2 and not token.isnumeric():<br>            filtered_song.append(token)<br>    lyric_corpus_tokenized[s] = filtered_song</pre><p><strong>Step 4: Token Lemmatization</strong></p><p>To further improve comparability, we use <em>NLTK’s WordNetLemmatizer</em>, which groups together inflected forms of words [<a href="https://www.datacamp.com/community/tutorials/stemming-lemmatization-python">6</a>],[<a href="https://queryunderstanding.com/stemming-and-lemmatization-6c086742fe45">7</a>].</p><pre>from nltk.stem.wordnet import WordNetLemmatizer</pre><pre>lemmatizer = WordNetLemmatizer()</pre><pre>for s,song in enumerate(lyric_corpus_tokenized):<br>    lemmatized_tokens = []<br>    for token in song:<br>        lemmatized_tokens.append(lemmatizer.lemmatize(token))<br>    lyric_corpus_tokenized[s] = lemmatized_tokens</pre><p><strong>Step 5: Removing Stop Words and Profanities</strong></p><p>In the final preprocessing step, all words holding little to no additional information for Topic Modeling are removed in order to further reduce dimensionality. As such, <em>NLTK’s stopwords</em>, a list of common stop words in the English language is imported and extended specifically for song lyrics.</p><pre>from nltk.corpus import stopwords</pre><pre>stop_words = stopwords.words(&#39;english&#39;)<br>new_stop_words = [&#39;ooh&#39;,&#39;yeah&#39;,&#39;hey&#39;,&#39;whoa&#39;,&#39;woah&#39;, &#39;ohh&#39;, &#39;was&#39;, &#39;mmm&#39;, &#39;oooh&#39;,&#39;yah&#39;,&#39;yeh&#39;,&#39;mmm&#39;, &#39;hmm&#39;,&#39;deh&#39;,&#39;doh&#39;,&#39;jah&#39;,&#39;wa&#39;]<br>stop_words.extend(new_stop_words)</pre><pre>for s,song in enumerate(lyric_corpus_tokenized):<br>    filtered_text = []    <br>    for token in song:<br>        if token not in stop_words:<br>            filtered_text.append(token)<br>    lyric_corpus_tokenized[s] = filtered_text</pre><p>In addition, I decided to filter out profanities for the purpose of our article using a <a href="https://www.freewebheaders.com/youtube-blacklist-words-list-youtube-comment-moderation/">curated list</a>. As this may distort the results, feel free to skip this step.</p><pre>profanities = []<br>with open(&#39;profanity.txt&#39;, &#39;r&#39;) as file:<br>    prof_string = file.read().replace(&#39;\n&#39;, &#39;&#39;)<br>    prof_tokens = prof_string.split(&quot;, &quot;)<br>    for token in prof_tokens:<br>        profanities.append(token)</pre><pre>for s,song in enumerate(lyric_corpus_tokenized):<br>    filtered_text = []    <br>    for token in song:<br>        if token not in profanities:<br>            filtered_text.append(token)<br>    lyric_corpus_tokenized[s] = filtered_text</pre><p><strong>Step 6: Dictionary Creation and occurrence-based Filtering</strong></p><p>In order to perform Latent Dirichlet Allocation, we use the popular and well-established Python library <em>gensim, </em>which<em> </em>requires a dictionary representation of the documents. This means all tokens are mapped to a unique ID, which reduces the overall dimensionality of a literature corpus. In addition, we filter out tokens that occur in less than 100 songs, as well as tokens that occur in more than 80% of songs.</p><pre>from gensim.corpora import Dictionary</pre><pre>dictionary = Dictionary(lyric_corpus_tokenized)<br>dictionary.filter_extremes(no_below = 100, no_above = 0.8)</pre><p><strong>Step 7: Bag-of-Words and Index to Dictionary Conversion</strong></p><p>Each song (as of now a list of tokens) is converted into the bag-of-words format, which only stores the unique token ID and its count for each song.</p><pre>from gensim.corpora import MmCorpus</pre><pre>gensim_corpus = [dictionary.doc2bow(song) for song in lyric_corpus_tokenized]<br>temp = dictionary[0]<br>id2word = dictionary.id2token</pre><p><strong>Step 8: Setting the Model Parameters</strong></p><p>Latent Dirichlet Allocation in gensim allows for setting several modeling parameters: (1) number of topics k, (2) chunk size, (3) number of passes through the literature corpus during training, (4) maximum number of iterations, (5) <em>alpha</em> hyperparameter, and (6) <em>eta</em> hyperparameter.</p><ul><li><em>number of topics k = d</em>escribes how many topics should be discovered and has to be set by us. We decide on 6 topics to be identified.</li><li><em>chunksize</em> = the number of documents considered in each training cycle</li><li><em>passes</em> = number of passes through the corpus during training</li><li><em>iterations</em> = maximum number of iterations</li><li><em>alpha</em> and <em>eta</em> hyperparameter = influence the Dirichlet distribution. A lower <em>alpha </em>value increases the importance of having documents composed of a few dominant topics, while a lower <em>eta (or beta) </em>value increases the importance of having topics composed of a few dominant words.</li></ul><pre>chunksize = 2000<br>passes = 20<br>iterations = 400<br>num_topics = 6</pre><p><strong>Step 9: Execute Model Training</strong></p><p>Finally, we train a LDA topic model for 6 topics. Due to the large corpus this may take some time (up to half an hour).</p><pre>from gensim.models import LdaModel<br>lda_model = LdaModel(<br>corpus=gensim_corpus,<br>id2word=id2word,<br>chunksize=chunksize,<br>alpha=&#39;auto&#39;,<br>eta=&#39;auto&#39;,<br>iterations=iterations,<br>num_topics=num_topics,<br>passes=passes<br>)</pre><p>Optionally, we can calculate a coherence score of our model, which is a measure to assess model quality, something that is quite difficult to evaluate in the Topic Modeling domain. Topic coherence indicates whether different terms within a topic belong together. The gensim library offers four different measures to calculate topic coherence: (1) <em>UMass</em>, (2) <em>UCI</em>, (3) <em>NPMI</em>, and (4) <em>Cv</em>. As demonstrated by Röder et al. [<a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.662.7267&amp;rep=rep1&amp;type=pdf">8</a>], <em>𝐶v</em> is the measure with the best performance in terms of quality when comparing correlation with human ratings, despite being outperformed by other measures in terms of runtime. <em>Cv</em> coherence measures topic coherence in the range [0; 1], with lower scores implying less coherence within a topic.</p><pre>from gensim.models.coherencemodel import CoherenceModel</pre><pre>coherencemodel = CoherenceModel(model=lda_model, texts=lyric_corpus_tokenized, dictionary=dictionary, coherence=&#39;c_v&#39;)<br>print(coherencemodel.get_coherence())</pre><p><strong>Step 10: Visualizing the LDA Model using pyLDAvis</strong></p><p>As we would like to visualize our generated topic model, we use <em>pyLDAvis.</em> <em>pyLDAvis</em> is the Python implementation of the LDAvis method proposed by Sievert &amp; Shelley [<a href="https://www.researchgate.net/publication/265784473_LDAvis_A_method_for_visualizing_and_interpreting_topics">9</a>].</p><pre>import pyLDAvis<br>import pyLDAvis.gensim_models as gensimvis</pre><pre>vis_data = gensimvis.prepare(lda_model, gensim_corpus, dictionary)<br>#pyLDAvis.display(vis_data)<br>pyLDAvis.save_html(vis_data, &#39;./Lyrics_LDA_k_&#39;+ str(num_topics) +&#39;.html&#39;)</pre><p>Saliency describes the information a word provides about topic association. In <em>pyLDAvis</em>, the displayed relevance of a word relies on the factor 𝜆. A value of 𝜆=1 implies a ranking based exclusively on topic-specific probability, while a value of 𝜆=0 implies a ranking based exclusively on each term’s lift and decreases the weight of terms with high global frequency throughout the literature corpus. Even though Sievert &amp; Shelley [<a href="https://www.researchgate.net/publication/265784473_LDAvis_A_method_for_visualizing_and_interpreting_topics">9</a>] suggest a default value of 𝜆=0.6 based on a performed user study, different 𝜆 values may help to narrow down and label a suggested topic’s true theme.</p><p><strong>The Final Result</strong></p><p>You can find an interactive visualization of our generated <a href="https://tdenzl.github.io/LyricsLDA/Lyrics_LDA_k_6.html#topic=0&amp;lambda=1&amp;term=">Song Lyrics Topic Model</a> on GitHub Pages. In addition, the figure below may give you an idea of the six topics prominent in our song lyric corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wz1kAJ5xK6dycU-_vkBUxg.gif" /><figcaption>Interactive Topic Model Visualization of Song Lyrics</figcaption></figure><p>If we examine our six topics, we can label them based on relevant keywords as follows:</p><ul><li>Topic 1: <strong>Obstacles &amp; Time</strong> (e.g., ’never’, ’could’, ’time’)</li><li>Topic 2: <strong>Religion</strong> (e.g., ’heaven’, ’lord’, ’heart’)</li><li>Topic 3: <strong>Romance</strong> (e.g., ’love’, ’baby’, ’want’)</li><li>Topic 4: <strong>Wealth &amp; Flexing</strong> (e.g., ’money’, ’check’, ’club’)</li><li>Topic 5: <strong>Home &amp; Nature</strong> (e.g., ’home’, ’town’, ’road’)</li><li>Topic 6: <strong>Violence</strong> (e.g., ’kill’, ’dead’, ’war’)</li></ul><p>Of course, this labeling is subjective and there may be more distinct topics when changing the granularity and increasing the number of topics to be modeled. However, this project and article may provide a first glimpse of the main topics covered in songwriting.</p><p>If you want to rerun the code or generate your own topic model, check out my <a href="https://github.com/tdenzl/LyricsLDA">GitHub repository</a>.</p><p><strong>References</strong></p><p>[1] A. Suarez, <a href="https://www.kaggle.com/albertsuarez/azlyrics">AZLyrics song lyrics</a> (2021)</p><p>[2] A. Suarez, <a href="https://github.com/AlbertSuarez/azlyrics-scraper">azlyrics-scraper</a> (2021)</p><p>[3] D. M. Blei, A. Y. Ng and M. I. Jordan, <a href="https://www.jmlr.org/papers/volume3/blei03a/blei03a.pdf">Latent Dirichlet Allocation</a> (2003)</p><p>[4] T. Ganegedara, <a href="https://towardsdatascience.com/light-on-math-machine-learning-intuitive-guide-to-latent-dirichlet-allocation-437c81220158">Intuitive Guide to Latent Dirichlet Allocation</a> (2018)</p><p>[5] R. Kulshrestha, <a href="https://towardsdatascience.com/latent-dirichlet-allocation-lda-9d1cd064ffa2">A Beginner’s Guide to Latent Dirichlet Allocation(LDA)</a> (2019)</p><p>[6] H. Jabeen, <a href="https://www.datacamp.com/community/tutorials/stemming-lemmatization-python">Stemming and Lemmatization in Python</a> (2018)</p><p>[7] D. Tunkelang, <a href="https://queryunderstanding.com/stemming-and-lemmatization-6c086742fe45">Stemming and Lemmatization</a> (2017)</p><p>[8] M. Röder, A. Both and A. Hinneburg, <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.662.7267&amp;rep=rep1&amp;type=pdf">Exploring the Space of Topic Coherence Measures</a> (2015)</p><p>[9] Sievert, C., and Shirley, K.; <a href="https://www.researchgate.net/publication/265784473_LDAvis_A_method_for_visualizing_and_interpreting_topics">LDAvis: A Method for Visualizing and Interpreting Topics</a> (2014)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53785767b692" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From CSV to GitHub Pages in 5 Steps: Publishing an Interactive Social Network of the Marvel…]]></title>
            <link>https://medium.com/data-science/from-csv-to-github-pages-in-5-steps-publishing-an-interactive-social-network-of-the-marvel-7b8374bf44fb?source=rss-232837455caa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b8374bf44fb</guid>
            <category><![CDATA[network]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[marvel]]></category>
            <dc:creator><![CDATA[Tim Denzler]]></dc:creator>
            <pubDate>Wed, 12 May 2021 15:39:17 GMT</pubDate>
            <atom:updated>2021-05-14T19:55:26.962Z</atom:updated>
            <content:encoded><![CDATA[<h3>From CSV to GitHub Pages in 5 Steps: Publishing an Interactive Social Network of the Marvel Universe</h3><h4>How to easily create an awesome graph visualization using Python, Gephi, and GitHub Pages</h4><p>In this article, I will provide a step-by-step guide on how you can create, publish, and share interactive network graph visualizations in 5 simple steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h7fwMuQRFPciWhMD" /><figcaption>Photo by <a href="https://unsplash.com/@colorflores?utm_source=medium&amp;utm_medium=referral">Omar Flores</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before we get started, here are the three things we need:</p><ul><li>Python &amp; NetworkX library [<a href="https://networkx.org/">1</a>]</li><li>Gephi [<a href="https://gephi.org/">2</a>] &amp; SigmaExporter package</li><li>GitHub account &amp; a public GitHub repository</li></ul><p><strong>Step 1: Import the CSV file and create a NetworkX graph</strong></p><p>Our data source really can be any data format (e.g. TSV, pandas data frame, or array), but in this article, we will focus on CSV (<strong>C</strong>omma-<strong>S</strong>eparated <strong>V</strong>alues) format. In this tutorial, I will use the Marvel Universe Social Network dataset from Kaggle [<a href="https://www.kaggle.com/csanhueza/the-marvel-universe-social-network">3</a>] to create an interactive graph of relationships between heroes. The dataset describes co-occurrences of Marvel heroes in comic books, so each row describes an instance in which <em>hero1</em> (in column 1) appeared in the same comic as <em>hero2 </em>(in column 2).</p><p>We start by importing three Python libraries: (1) <em>csv</em> for reading CSV files, (2) <em>tqdm</em> for displaying progress bars (optional), and (3) <em>NetworkX</em> for creating and modifying graphs.</p><pre>import csv<br>from tqdm import tqdm<br>import networkx as nx</pre><p>We then create an empty NetworkX graph…</p><pre>import networkx as nx <strong><br></strong>G = nx.DiGraph()</pre><p>…and add nodes and edges based on our CSV file. We iterate over each row adding nodes for <em>hero1</em> (first column) and <em>hero2</em> (second column). There is no need to worry about adding duplicate nodes, as the name/label serves as unique IDs, and nodes that are already in the graph are skipped. If the edge from <em>hero1</em> to <em>hero2 </em>does not exist in our graph yet, we add it<em> </em>and set its weight value to 1 (meaning they appeared together in a comic book once)<em>. </em>If the edge already exists we just increment the existing edge’s weight by one.</p><pre><strong>with</strong> open(&#39;./data/hero-network.csv&#39;, &#39;r&#39;) <strong>as</strong> f:<br>    data = csv.reader(f)<br>    headers = next(data)<br>    <strong>for</strong> row <strong>in</strong> tqdm(data):<br>        G.add_node(row[0]) <em>#superhero in first column</em><br>        G.add_node(row[1]) <em>#superhero in second column</em><br>        <strong>if</strong> G.has_edge(row[0], row[1]):<br>            <em># edge already exists, increase weight by one</em><br>            G[row[0]][row[1]][&#39;weight&#39;] += 1<br>        <strong>else</strong>:<br>            <em># add new edge with weight 1</em><br>            G.add_edge(row[0], row[1], weight = 1)</pre><p>In order to receive first information on our graph, we print out its node and edge count.</p><pre>G_nodes = G.number_of_nodes()<br>G_edges = G.number_of_edges()<br>print(&quot;Nodes = &quot;, G_nodes, &quot; Edges = &quot;,G_edges)</pre><p>In total, our graph has <strong>6,426 nodes</strong> and <strong>224,181 edges</strong>.</p><p><strong>Step 2: Export the NetworkX graph as gexf file</strong></p><p>In the next step, we convert the NetworkX graph to a gexf file (<strong>G</strong>raph <strong>E</strong>xchange <strong>X</strong>ML <strong>F</strong>ormat) and store it in our file directory.</p><pre>nx.write_gexf(G, &quot;./data/hero-network.gexf&quot;)</pre><p><strong>Step 3: Import and modify the graph in Gephi</strong></p><p>As our graph is stored as a gexf file, we can import, modify, and visualize it using the open-source application Gephi (available for Windows, MacOS, and Linux), which offers a variety of functionalities.</p><p>First, we import our gexf file as undirected graph and install the SigmaExporter JS package (Tools &gt; Plugins &gt; Available Plugins) to leverage Sigma JS [<a href="http://sigmajs.org/">4</a>]. If you want, you can choose to install and use additional layout algorithms as well.</p><p>In the next step, we want to make more relevant nodes (e.g., Tony Stark, Captain America) that are well-connected appear larger. For this we calculate the average weighted degree in the statistics tab (for directed graphs I can recommend using PageRank), and set the node sizes accordingly in the appearance tab, with 8 being the minimum and 48 being the maximum node size.</p><p>Finally, we run a modularity algorithm [<a href="https://parklize.blogspot.com/2014/12/gephi-clustering-layout-by-modularity.html#:~:text=Modularity%20is%20one%20measure%20of,groups%2C%20clusters%20or%20communities).&amp;text=Biological%20networks%2C%20including%20animal%20brains,a%20high%20degree%20of%20modularity">5</a>] to cluster our graph and assign nodes to a module. We then assign our node colors based on module affiliation and run a graph layout algorithm of our choice (in our case Force Atlas 2). Keep in mind that Gephi provides a variety of ways to personalize our graph [<a href="http://gephi.michalnovak.eu/Mastering%20Gephi%20Network%20Visualization.pdf">6</a>].</p><p><strong>Step 4: Export the graph as Sigma JS</strong></p><p>If we like the layout and visualization of the graph, we can now export it as a Sigma JS template (File &gt; Export &gt; Sigma JS template). Gephi will ask us to provide some basic information on the graph (e.g., title, author, legend, and descriptions). I would recommend to check the search option, as it will enable looking up nodes in the final graph visualization. In addition, setting the hover behavior to dim provides an improved interactive experience. Finally, we select the target directory and click export. We should now have a network folder in the target directory.</p><p><strong>Step 5: Publish the graph visualization on GitHub pages</strong></p><p>We can test our graph locally by opening navigating to the network folder and opening a Python http server with the following command.</p><pre>python -m http.server</pre><pre>python -m SimpleHTTPServer (<em>for earlier Python versions)</em></pre><p>We should now be able to see our graph in our web browser at the URL: <a href="http://localhost:8000/">http://localhost:8000/</a>. However, if we want to publish our graph online and share the link with others, we can do so by leveraging GitHub Pages. First, we create a new (public) GitHub Repository and upload the network folder. We then go to our repository settings and select the GitHub Pages tab. Once there, we set the main branch as our source. The graph should now be available at the following URL:</p><pre><a href="https://tdenzl.github.io/MarvelNetwork/network/"><strong>https://</strong>[YourGitHubName]<strong>.github.io/</strong>[YourRepositoryName]<strong>/network/</strong></a></pre><p>We can now explore the graph by selecting and searching nodes. In addition, we can further adjust the graph’s visuals [<a href="https://github.com/jacomyal/sigma.js/wiki/Settings">7</a>].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K_DPV-O7VGVTpWE_Gl7qqA.gif" /><figcaption>A sneak peek of our interactive Marvel Universe Co-Occurrence graph visualization</figcaption></figure><p>Here you can find the final <a href="https://tdenzl.github.io/MarvelNetwork/network/#">Marvel Universe Co-Occurrence Network</a> hosted by GitHub Pages.</p><p>If you want to create your very own network visualization, check out my <a href="https://github.com/tdenzl/MarvelNetwork">GitHub Repository</a> containing the Jupyter Notebook script.</p><p><strong>References:</strong></p><p>[1] NetworkX, <a href="https://networkx.org/">Homepage</a> (2021)</p><p>[2] Gephi, <a href="https://gephi.org/">Homepage</a> (2021)</p><p>[3] C. Sanhueza, <a href="https://www.kaggle.com/csanhueza/the-marvel-universe-social-network">The Marvel Universe Social Network</a> (2017)</p><p>[4] Sigma JS, <a href="http://sigmajs.org/">Homepage</a> (2021)</p><p>[5] Parklize, <a href="https://parklize.blogspot.com/2014/12/gephi-clustering-layout-by-modularity.html#:~:text=Modularity%20is%20one%20measure%20of,groups%2C%20clusters%20or%20communities).&amp;text=Biological%20networks%2C%20including%20animal%20brains,a%20high%20degree%20of%20modularity">Gephi - Clustering layout by modularity</a> (2014)</p><p>[6] K. Cherven, <a href="http://gephi.michalnovak.eu/Mastering%20Gephi%20Network%20Visualization.pdf">Mastering Gephi Network Visualization</a> (2015)</p><p>[7] Sigma JS, <a href="https://github.com/jacomyal/sigma.js/wiki/Settings">Documentation</a> (2021)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b8374bf44fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-csv-to-github-pages-in-5-steps-publishing-an-interactive-social-network-of-the-marvel-7b8374bf44fb">From CSV to GitHub Pages in 5 Steps: Publishing an Interactive Social Network of the Marvel…</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Bayern München the laziest team in the German Bundesliga?]]></title>
            <link>https://tim-denzler.medium.com/is-bayern-m%C3%BCnchen-the-laziest-team-in-the-german-bundesliga-770cfbd989c7?source=rss-232837455caa------2</link>
            <guid isPermaLink="false">https://medium.com/p/770cfbd989c7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bundesliga]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[football]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Tim Denzler]]></dc:creator>
            <pubDate>Fri, 07 May 2021 12:42:43 GMT</pubDate>
            <atom:updated>2021-05-07T12:42:43.687Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building an easy-to-use Bundesliga data analysis app with Python and Streamlit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GzyZIIBBaaGuNqk56srI-g.jpeg" /><figcaption>Veltins Arena in Gelsenkirchen by Dominik Kuhn on <a href="https://unsplash.com/photos/kEHp1gUJNO8">Unsplash</a></figcaption></figure><p>As the latest Bundesliga season is coming to an end and Bayern München is close to winning its 9th consecutive championship, I was wondering recently if football in Germany has changed at all in the last few years. I often spend my Saturdays watching Bundesliga matches and think to myself: “I could swear matches were more interesting last season”. More goals, more shots on the goal, more fouls. However, I am never able to find adequate data or analyses that may confirm my gut feeling. This seems to be quite a paradox, as we live in a time where every move by a football player on the field is tracked, remote AWS servers calculate obscure match stats in real-time (I am looking at you xGoals), and commentators seem to fill the void caused by the 100th pass to the goalie by rambling about how this is the third match in a row that Lewandowski wears blue boxer shorts.</p><p>Obviously, I am exaggerating. Nevertheless, popular sports websites oftentimes only provide single match facts without any possibility for comprehensive analysis. As someone passionate about all things football and data, I decided to tackle this problem by leveraging <em>Python</em> and <em>Streamlit </em>[<a href="https://streamlit.io/">1</a>] to build an easy-to-use and intuitive <strong>Bu</strong>ndes<strong>li</strong>ga <strong>An</strong>alysis (BuLiAn) web application.</p><p>In this article, I will try to provide a top-level overview of the application and touch upon the following aspects:</p><ol><li><strong>Extracting the data</strong></li><li><strong>Cleaning the data</strong></li><li><strong>Building and deploying the Streamlit application</strong></li><li><strong>Generating interesting Bundesliga insights</strong></li></ol><p>If you want to jump right in and explore Bundesliga data yourself, click right here: <a href="https://share.streamlit.io/tdenzl/bulian/main/BuLiAn.py">BuLiAn web application hosted by Streamlit</a></p><p>For more details on the actual implementation, make sure to take a look at the GitHub repository: <a href="https://github.com/tdenzl/BuLiAn">BuLiAn GitHub repository</a></p><h4><strong>1. Extracting the data</strong></h4><p>The first step is to gather as many relevant match facts as possible: goals, shots, fouls, corners, offsides…you name it. All this information is available on the internet and can be extracted for analysis purposes. My primary source of information was the website of a popular German football website. Using the <em>BeautifulSoup</em> library [<a href="https://pypi.org/project/beautifulsoup4/">2</a>] and Jupyter Notebooks, the website was scraped for data ranging from <strong>Season 2013/2014 to Season 2019/2020</strong>. This seems to be a reasonable range, as Season 2013/2014 is the first season with data on the distance covered by teams being published. Furthermore, Season 2019/2020 is the most recent completed season. In total, <strong>2,142 matches were scraped</strong> and subsequently stored in CSV format.</p><h4>2. <strong>Cleaning the data</strong></h4><p>As is the case with most data analysis projects, the next step is to examine the data and find potential irregularities. As the German Bundesliga has a relatively low number of 18 teams when compared to other European leagues, only 9 matches take place on each of the 34 matchdays. In total, each season should therefore consist of <strong>306 matches</strong>. However, when grouping our matches by season, we see that Season 2013/2014 (307 matches) and 2019/2020 (308 matches) seem to have some irregularities in their data.</p><p>Upon closer investigation of Season 2013/2014, we see that VfB Stuttgart had two home matches against Bayern Munich according to our data. While I am sure VfB Stuttgart would have been more than happy to get a second chance that season, a quick Google search reveals: Bayern München won the Champions League in the previous season and as such was participating in the FIFA Club World Cup. As a consequence, their match against VfB Stuttgart had to be postponed. I guess that is what you call suffering from success! When looking at Season 2018/2019, we see that Werder Bremen and Borussia Mönch…en…glad…that German team had similar issues. Therefore, all duplicate instances are removed. Et voilà, the number of matches per season is correct.</p><p>After some more data cleaning (such as removing spaces in strings, and converting strings to numerical data types), we can further check the data quality. It seems like there is an issue with three matches from Season 13/14, as the distance covered during the match was not captured. This leads to three potential options:</p><ul><li>Manually search and enter the correct values</li><li>Remove complete rows (matches)</li><li>Estimate the values based on previous data</li></ul><p>The first strategy did not succeed, as the data was nowhere to be found on the internet (it seems the data for these three matches is forever lost in the void). Removing complete matches seems to be a radical approach, as it would lead to a lack of comparability when looking at absolute values. As such, the most elegant way to solve this issue was to <strong>calculate the average distance covered per match</strong> by each team and fill the empty cells accordingly.</p><p>A quick fun fact (or sad, depending on your team affiliation): While checking the data, it came to my attention that on Matchday 8 of Season 2014/2015 <strong>Werder Bremen had 0 recorded shots on Bayern München’s goal</strong>. However, I quickly realized that this was not an error in the data, but rather a really really bad day for Werder Bremen.</p><h4><strong>3. Building and deploying the Streamlit application</strong></h4><p>In order to enable football fans to interact and quickly perform their very own Bundesliga analysis, I decided to develop my application using the <em>Streamlit</em> library. <em>Streamlit</em> not only allows for easy development and sharing of web applications but also provides a variety of well-designed and customizable widgets. In addition, I used the <em>pandas</em> library’s data frames [<a href="https://pandas.pydata.org/">3</a>] to manipulate the data, and the <em>seaborn</em> library [<a href="https://seaborn.pydata.org/">4</a>] to plot appealing visualizations. In order to improve code readability and minimize the lines of code required, I leveraged <em>Python</em> dictionaries, for example to link labels (selection options displayed by the widgets) with column names.</p><p><strong>The filtering sidebar</strong> is essential, as it allows for selecting seasons, matchdays, and teams to be included in the analysis. Triggering new filter selections will modify the <em>pandas</em> data frame accordingly. If you want to see the data that is used for the analysis, you can either take a look at the quick fact section on top or unhide the complete data frame.</p><p><strong>The match finder</strong> enables users to investigate interesting match facts. As can be seen in the screenshot below, three selection widgets can be modified to form a sentence and search a match with corresponding attributes. In addition, match data for both teams is provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LPTm3I0Nl2yOsWB3ar0Lvg.png" /><figcaption>The match finder allows for finding trivia based on sentences posed in natural language.</figcaption></figure><p><strong>The analysis per team</strong> <strong>section</strong> allows for analyzing various aspects on a team level. For this purpose, the data is grouped by teams and aggregated based on five different measures: <strong>mean</strong> (or average) values, <strong>absolute</strong> values (may lack comparability due to some teams being relegated), <strong>median</strong> values (ideal for removing outliers), <strong>maximum</strong> values, and <strong>minimum</strong> values. In addition, a team-specific color scheme may be toggled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDFW_CwLk8w8YBWZKfvBZw.png" /><figcaption>BuLiAn allows for analyzing team-level data</figcaption></figure><p><strong>The analysis per season section</strong> and <strong>analysis per matchday section </strong>are developed similarly. First, the data is grouped by season or matchday and then aggregated based on one of the five previously mentioned measures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmwL7kIfdQBxNZ2FDk9nQA.png" /><figcaption>The season analysis section allows for observing trends and developments in recent years</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DBLmAu7KtcIJ_BKce4Ohmg.png" /><figcaption>The matchday analysis sectionallows for analyzing the course of one or multiple seasons</figcaption></figure><p><strong>The correlation of game stats section</strong> enables users to investigate and visualize correlation between different match aspects. However, it is important to keep in mind: <strong>correlation does not imply causation!</strong> What the data does say is that teams that have more passes in a match than their opponents tend to also shoot more goals (hence winning). What it does not say is that an increase in passes will lead to a team shooting more goals (sorry Pep).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QbNPi97AwiLyEs5SJno3WA.png" /><figcaption>Dive deep into Bundesliga data with a correlation analysis</figcaption></figure><p>Finally, deploying and hosting an application with <em>Streamlit</em> is as easy as it gets. All you need to do is sign-up for <em>Streamlit sharing</em> and upload your application in a public GitHub repository. For more information check out the official <a href="https://docs.streamlit.io/en/stable/deploy_streamlit_app.html"><em>Streamlit</em> documentation</a> on deployment.</p><h4><strong>4. Generating interesting Bundesliga insights</strong></h4><p>Now let’s get down to business. What exciting facts and entertaining trivia can actually be discovered with the application? Below you can find some of my personal highlights:</p><ul><li><strong>Lazy Bayern München:</strong> While arguably being the best team in recent years, the Bavarians are third last when it comes to <strong>distance covered</strong> during games with an average of <strong>113.68 km</strong>. A possible explanation: Bayern far exceeds their competition when it comes to <strong>passing</strong>, with an average of <strong>695.07 passes per game</strong>. Second-place Borussia Dortmund does not even come close <strong>(581.85 passes per game)</strong>. Hence, Bayern München prefers to let the opposing team do the running.</li><li><strong>Don’t mess with the “Dino”:</strong> You do not want to play against the <strong>Hamburger SV</strong>. Not because chances are you may lose, but rather because it will most likely hurt. With an average of <strong>16.46 fouls per game</strong>, HSV is leading in this category. On the other hand, it seems that more successful teams (e.g., Bayern München and Borussia Dortmund) tend to foul less.</li><li><strong>The “Christkind” is not the only one handing out presents:</strong> While Bayern München receives an average of 8.31 shots on their own goal during a game, <strong>1.FC Nürnberg</strong> almost doubles this number with a staggering <strong>16.43 shots on their own goal</strong>. No wonder each of their two seasons in the Bundesliga ended after just one year.</li><li><strong>Bayer Leverkusen’s turbo halftime:</strong> In Season 2018/2019, Bayer 04 Leverkusen’s match against Eintracht Frankfurt and resulted in a 6:1 (6:1) win for <strong>Bayer 04 Leverkusen</strong>. During the match, Bayer 04 Leverkusen scored <strong>6 halftime goals</strong>, which is the maximum value for any team in the available data. Frankfurt certainly needed an Aspirin after that first half.</li><li><strong>Harbor brawl: </strong>In Season 2014/2015 <strong>Hamburger SV</strong> won 1:0 (1:0) against <strong>Bayer 04 Leverkusen</strong>. However, it seems football was of minor importance that day, as both teams committed a <strong>total of 54 fouls</strong>.</li><li><strong>Could you please pass the ball to me at least once?</strong> In Season 2015/2016 Eintracht Frankfurt’s match against Borussia Dortmund seemed terribly one-sided. Over the course of the match, Eintracht Frankfurt recorded a mere <strong>16% ball possession ratio</strong>. More surprisingly, the match resulted in a <strong>1:0 (1:0) win for Eintracht Frankfurt</strong>!</li><li><strong>More passing, fewer fouls:</strong> When looking at past seasons, a clear and steady trend towards a more passing dominated game can be observed, with an average of <strong>436.43 passes per game</strong> in Season 2013/2014 and an average of <strong>455.33 passes per game </strong>in<strong> </strong>Season 2019/2020. In addition, there seems to be a trend towards<strong> fewer and fewer fouls committed </strong>per season.</li><li><strong>Performing under pressure:</strong> While the <strong>number of shots on goals remains steady</strong>, there is a significant <strong>increase in goals scored on the last matchday</strong>. Whether this has to do with the potentially increased relevance of goal differences or opposing defenders’ minds slowly moving towards summer vacation is up for discussion.</li><li><strong>Fair teams that tend to win:</strong> It seems that <strong>teams with a higher pass success ratio tend to score more goals </strong>than opposing teams. In addition, passes, distance covered, and ball possession seems to be higher for successful teams. On the contrary, <strong>teams that lose tend to foul more frequently than their counterparts</strong> (not a big surprise there).</li></ul><p>What are your thoughts on these insights? Make sure to try out the app and leave your personal favorite facts or insights in the comments below. If you have any suggestions for improvement or extensions of the app, feel free to reach out to me!</p><p>Web Application: <a href="https://share.streamlit.io/tdenzl/bulian/main/BuLiAn.py">https://share.streamlit.io/tdenzl/bulian/main/BuLiAn.py</a></p><p>GitHub Repository: <a href="https://github.com/tdenzl/BuLiAn">https://github.com/tdenzl/BuLiAn</a></p><p>Libraries:</p><p>[1] <a href="https://streamlit.io/">Streamlit</a></p><p>[2] <a href="https://pypi.org/project/beautifulsoup4/">BeautifulSoup</a></p><p>[3] <a href="https://pandas.pydata.org/">pandas</a></p><p>[4] <a href="https://seaborn.pydata.org/">seaborn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=770cfbd989c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>