<?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 Miroslav Tushev on Medium]]></title>
        <description><![CDATA[Stories by Miroslav Tushev on Medium]]></description>
        <link>https://medium.com/@miroslavtushev?source=rss-7b877a036858------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j9KzEnFrEF0lLW3DJb_ffg.jpeg</url>
            <title>Stories by Miroslav Tushev on Medium</title>
            <link>https://medium.com/@miroslavtushev?source=rss-7b877a036858------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:51:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@miroslavtushev/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[Faster Word Co-Occurrence Calculation In Large Document Corpus]]></title>
            <link>https://miroslavtushev.medium.com/faster-word-co-occurrence-calculation-in-large-document-corpus-eeac86543d8a?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeac86543d8a</guid>
            <category><![CDATA[wikipedia]]></category>
            <category><![CDATA[nipm]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 17:39:26 GMT</pubDate>
            <atom:updated>2021-12-26T17:39:26.227Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*0U2lLkDn0R-hpR8i.png" /></figure><p>For one of my <a href="https://miroslavtushev.github.io/keyatm.html">research papers</a> I had to calculate co-occurrence information between pairs of words for a large number of topics in order to measure topic coherence. I soon realized that a straight-forward approach would take ages to complete. In this article I will explain how I was able to decrease the computation time from <strong>days </strong>to just under <strong>10 minutes</strong>. The complete code for this article can be found <a href="https://github.com/miroslavtushev/Faster-Word-Co-Occurrence-Calculation">here</a>.</p><p>In computational linguistics, word co-occurrence is a <a href="https://en.wikipedia.org/wiki/Co-occurrence">well-known concept</a>. It essentially expresses the idea that if two words occur close to each other (<em>e.g., in the same document</em>), they are most likely to be related. This information can then be used to draw some useful conclusions about the language and its structure.</p><p>In my particular case, I used word co-occurrence in <a href="https://miroslavtushev.github.io/keyatm.html">my research paper</a> to calculate topic coherence for my topic models I derived for user review corpora. This paper ended up being accepted for publication in ICSE’22, which I am extremely proud of (<em>for those who are interested, the code can be found </em><a href="https://github.com/miroslavtushev/Domain-Specific-Analysis-of-Mobile-App-Reviews-Using-Keyword-Assisted-Topic-Models"><em>here</em></a>). The point of this medium article is not to discuss that paper, but rather to compare different optimization strategies for calculating word co-occurrence I tried, to see what worked best.</p><h3>Topic Modeling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*uUwIvsEM1VkGaAHS.png" /></figure><p>Essentially, each topic model derives latent topics from a corpus of documents. Each topic is commonly represented by top-10 most “significant” words that are likely to describe a particular topic. Each document is then assigned a probability of each particular topic. For instance, if I try to model a corpus of user reviews for food delivery apps, I might produce a topic like this:</p><p>drive, driver, food, minute, around, house, away, street, go, car</p><p>This tells me that the topic is most likely to describe user reviews that complain about location and time of their delivery. We then can use this topic to list the reviews that have the highest probability of this topic to dive deep and analyze what problems related to that topic users experience.</p><h3>NPMI</h3><p>Not all topics are useful. LDA, in particular, is known to produce garbage topics for short, semantically-poor documents. How do we know if a topic is good or not? One way to tell is to calculate topic coherence. There are different coherence metrics out there, but in this article we will focus on one of the most used one: <a href="https://en.wikipedia.org/wiki/Pointwise_mutual_information"><strong>Normalized Pointwise Mutual Information</strong></a><strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*4XHMWVGu4lFFb5BLeTV4iA.png" /></figure><p>The deep meaning behind this formula is not important for now. What is important is that we have two words: wi and wj, and three pieces of information that we need to collect from a document corpus:</p><ol><li>How many documents wi occurs in;</li><li>How many documents wj occurs in;</li><li>How many documents both wi and wj occurs in.</li></ol><p>NPMI, for a specific topic, is calculated as a pairwise metric, that is between each pair of words. In total, we have 45 pairs for 10 words. These pairs are then averaged out to produce the final metric. The most straight-forward approach to calculate this can be implemented as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b820097130abe1c505b787ac86aa1590/href">https://medium.com/media/b820097130abe1c505b787ac86aa1590/href</a></iframe><p>Here we loop over our document corpus (<em>from now on we will use </em><a href="https://dumps.wikimedia.org/"><em>an official Wikipedia dump</em></a><em> as our document corpus, consisting of the first 100k articles</em>) and perform 3 if-tests. The time complexity of this approach is represented by a <a href="https://byjus.com/maths/triangular-numbers/#:~:text=The%20triangular%20number%20sequence%20is,pattern%20are%20represented%20by%20dots.">triangular sequence</a>, as we increase the number of words in our topics, because we have to recount the number of documents for a particular word every time it appears in a word pair. We can immediately notice that some of this is redundant and we can save time by using <strong>memoing</strong> like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d1fc392cdc9d9852a297b0109bf87b8/href">https://medium.com/media/0d1fc392cdc9d9852a297b0109bf87b8/href</a></iframe><p>We now have a dictionary keywords_countswhich calculates and stores the indices of documents that contain a particular word. Additionally, to count the documents that contain both words, we apply a <a href="https://www.programiz.com/python-programming/methods/set/intersection">intersection set operation</a> for two lists of indices. This approach essentially trades time complexity for space complexity, compared to the previous approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*LYYj1rY5pkZSTdPUpmItrw.png" /><figcaption>Notice how vanilla NPMI has a constant space complexity, while memoing uses approx. 80KB of space for 10 words.</figcaption></figure><p>Time is money, while memory is cheap for a modern computer (relatively speaking). The approach with memoing clearly is a better choice. But can we do even better?</p><h3>Introducing Matrices</h3><p>Matrices are everywhere. Modern hardware has become adapted to fast matrix manipulations and computations. We can exploit that to speed up our NPMI computation even more.</p><p>For starters, let’s transform our original Wikipedia document corpus into a matrix, where each row would represent a document and each column would represent a word. As we don’t need to know <strong><em>how many times</em></strong> a word occurs in a document, we can use a binary matrix for this task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb91457cee9dc5abececedcbd44cb5a1/href">https://medium.com/media/eb91457cee9dc5abececedcbd44cb5a1/href</a></iframe><p><em>Scikit-learn</em>’s implementation automatically constructs a <a href="https://en.wikipedia.org/wiki/Sparse_matrix#:~:text=The%20compressed%20sparse%20row%20(CSR,row%20indices%2C%20hence%20the%20name.">compressed matrix</a>, which saves a significant amount of space, but takes somewhat longer to retrieve individual rows or columns. We will test both compressed and uncompressed (called <strong>dense</strong>) formats. The new NPMI implementation looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d413ccca3c9445c4969429b8a534c69d/href">https://medium.com/media/d413ccca3c9445c4969429b8a534c69d/href</a></iframe><p>Because each column represents a word and each document represents a row with 1s denoting if a particular word is present, calculating how many documents a word is in is trivial: simply find the index of the word, extract the column and calculate the sum of 1s in that column. For calculating the documents that contain both words I used a similar idea from the previous implementation, that is, taking an intersection of both columns. We also use memoing to avoid finding the index for a word every time. Here are the results for both sparse and dense matrices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*UBlpbi8jbvUTxTBgBaFYvg.png" /></figure><p>We can see that dense implementation takes close to 0 seconds regardless of the number of word combinations, while sparse implementation’s time grows steadily to 3.5 seconds, as we need to convert sparse to dense format every time. However, look at the right y-axis: while sparse takes under 1 GB of space to store its matrix, <strong><em>dense uses 50 GB</em></strong>! Clearly, the speed penalty that the sparse matrix imposes does not outweigh the enormous space requirements to store a dense matrix in memory.</p><p>And here is how these approaches look in comparison to the vanilla implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*trFr2BrTvUULYI3KgQ_1EQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*CzJzmVv6QvOO23vyvgnE6w.png" /></figure><p>In this case, the obvious winner is the <strong><em>sparse matrix implementation</em></strong>, which provides excellent computation time with a small space penalty. When I computed NPMI for this article, I only used first 100k documents from the Wikipedia dump, simply because I couldn’t fit the whole dump in my memory (I have 64 GB of RAM). But now, thanks to the sparse implementation, I can calculate NPMI over the whole Wikipedia dump! In fact, that’s exactly what I did in my research paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*jP77N7IElb6Mc2vHlgMJ1g.png" /></figure><p>Even when increasing the size of the corpus document to incorporate all Wikipedia, the size grows to modest 12 GB, while the running time remains manageable.</p><p>In this article I introduced various optimization methods for calculating word co-occurrence information in a large document corpus. Check out my links for more info about me and my research!</p><p><a href="https://miroslavtushev.github.io/">Website</a>, <a href="https://github.com/miroslavtushev">Portfolio</a>, <a href="https://www.linkedin.com/in/miroslav-tushev/">LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeac86543d8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Intuition Behind The Normal Distribution Equation]]></title>
            <link>https://miroslavtushev.medium.com/a-simple-intuition-behind-the-normal-distribution-formula-91512fd81ae2?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/91512fd81ae2</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[gaussian-distribution]]></category>
            <category><![CDATA[normal-distribution]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Thu, 18 Nov 2021 20:30:54 GMT</pubDate>
            <atom:updated>2021-11-18T20:31:10.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*Rp8esepfJd7zFdrIQ8jkug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*xnTa5Vu1TIpoG1H_" /></figure><p>Ever since I learned about the Normal Distribution Equation in school it always looked menacing to me. I could not memorize it and I could not make any sense of it. I can kind of understand why the equation includes the sigma, mean, and the x’s. But where did e come from? Pi? And these strange fractions everywhere.</p><p>In this article we are going to derive the equation for the normal distribution (pdf) from scratch, step-by-step, using simple examples. I guarantee you by the end of this article you will be able to do it on your own with minimal algebra and probability knowledge required.</p><h4>Table of Contents:</h4><ul><li><a href="#0019">From Darts to Exponents</a></li><li><a href="#fa59">A “Normal Distribution” with Two Parameters</a></li><li><a href="#fbe4">From Two to One</a></li><li><a href="#ffa0">From One to Spread</a></li><li><a href="#9d3e">The Final Form: Spread and Mean</a></li></ul><p>The full code is available <a href="https://github.com/miroslavtushev/Medium-normal-distribution">on my GitHub</a>. The resources that were used in preparation for this article are: <a href="https://www.youtube.com/watch?v=cTyPuZ9-JZ0&amp;ab_channel=Mathoma">[1]</a>, <a href="https://www.amazon.com/Probability-Theory-Science-T-Jaynes/dp/0521592712">[2]</a>, <a href="https://www.alternatievewiskunde.nl/QED/normal.pdf">[3]</a>, <a href="http://matcmath.org/textbooks/engineeringstats/pdf-mean-variance/">[4]</a>.</p><h3>1. From Darts to Exponents</h3><p>Let’s imagine we are throwing darts at a dartboard. As we do this, we record each dart’s position on the board. Below is a scatter plot of the final result, where the bullseye is centered on the origin (0, 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*PiCHc8BedT1RyU5A3U56NQ.png" /><figcaption>The positions of darts after 50 throws</figcaption></figure><p>As we can expect, most of the darts on the board cluster in the close proximity to the desired target. As we move further away from the bullseye, fewer and fewer darts fall there. How can we come up with a function to calculate a probability of a dart in a particular location on the board? In other words, <strong><em>how can we define a pdf that would take a location on the board and produce a probability of a dart being there?</em></strong></p><p>Let’s define a pdf called <em>phi</em> that would take a point on the dartboard and produce a probability of finding a dart near that point. We are going to define a small box <em>dA</em> to describe how near to that point we want to find the darts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*WOcsg6ZP-NVvzZIZBnlLgg.png" /><figcaption>The point is the red dot, with the square dA surrounding it</figcaption></figure><p>Then, the probability of finding a dart inside that box can be described by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/45/1*49mw1B9gmpU27lTw2C-_YA.png" /><figcaption>The coordinates of the red dot plugged into phi multiplied by the area dA</figcaption></figure><p>Please note that boxes that lie closer to the origin will produce higher probability, as it naturally follows from our assumptions that there are more darts closer to the bullseye. Also, if two boxes are the same distance away from the origin, then the larger box will have a higher probability, since it has a larger area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*Tdl_knZLZFwQmtJk0TZ2Zw.png" /><figcaption>dB and dA are equally distant from the origin, but dB is larger</figcaption></figure><p>You might have noticed that I use the word <em>distance </em>as opposed to specific coordinates of <em>x </em>and <em>y</em>. This is because <em>y </em>and <em>x </em>are independent of each other: knowing one does not tell you anything about the other. If you aim your dart too high, say at <em>y=2.5</em>, then it does not tell you anything about which side of the board (i.e., <em>x</em>) you are going to hit. It follows that <strong>if you rotate a box <em>dA</em> preserving it’s distance <em>r </em>and its area <em>dA, </em>you will get the same value from <em>phi</em>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*0SwitoO0dbFY18j4Ufg3-Q.png" /><figcaption>phi is rotationally symmetric, with distance r</figcaption></figure><p>Let’s define a new pdf <em>f(x)</em> that would take a coordinate <em>x</em> and produce the probability of a dart at that coordinate. Rewriting the previous formula, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*OY6TJ6lS43-FI3aQzznPKg.png" /></figure><p>where <em>f</em> can be thought of some pdf independently operating on the <em>x</em> and <em>y</em> coordinates. Since <em>x</em> and <em>y</em> are independent, we can safely multiply them like this, following the probability independence rule. By cancelling out <em>dA</em>’s we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*3RJAq5Q63vnD7G4pNXITow.png" /></figure><p>Recall, that by <a href="https://en.wikipedia.org/wiki/Pythagorean_theorem">the Pythagorean theorem</a>, in the right triangle, the hypothenuse equals the squared root of the squared sum of two legs. Graphically, this can be depicted like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*F76_dC1qubuuc1BUVQ5CKA.png" /><figcaption>r is the hypothenuse, and (0,x1), (0,y1) are two legs of a right triangle</figcaption></figure><p>Using this information, we can rewrite the previous equation like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*e1V4igci_GV42UcRweSPWA.png" /><figcaption>r is replaced by the Pythagorean theorem</figcaption></figure><p>Let’s set <em>y=0</em> and plug it into our equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*SNZhDb_8gWM9HZnDeKYQxw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*t6IvPrDPy3Js5H4yNy9Djw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*6la-Xc1EEOEgI87LcwzlUQ.png" /></figure><p>Since<em> f(0)</em> is some unknown constant, let’s name it <em>lambda</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*9kw5gt9YtaOwGQ9aWbRllA.png" /></figure><p>The resultant equation tells us that <strong>the function phi operating on some input <em>x</em> is a scalar multiple of <em>f</em> operating on the same input</strong>. Using this property, let’s rewrite the previous equation like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*Q5zF_1UioS6yPjiK4VCWGw.png" /></figure><p>In other words,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*09M5R-6fWhXs5migE-UUvw.png" /></figure><p>Let’s divide both sides by <em>lambda </em>squared and simplify a bit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*09M5R-6fWhXs5migE-UUvw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*iS6RSs8F8Rm6Jt01i7yrXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*aNSltsNf1ZjopAZRq5vepA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*3VEaUsEtL1-uV52ooHLHTw.png" /></figure><p>Substitute</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*omCGY7TnQzJ9Tf_3lnV4sA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*PTjTQbxcMlbuXUZ-4EBiDA.png" /></figure><p>Our goal now is to find a certain function g that would satisfy the property above. That is, <strong>if we take a function g and apply it on the <em>x</em> input times the <em>y</em> input we should get a squared root of the sum of squares of those <em>x</em> and <em>y</em> inputs</strong>. To find such a function, let’s consider a simpler case</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*aUhNUH8IoELf3hvRRJ6mzA.png" /><figcaption>Notice the lack of the square root and the squared x and y</figcaption></figure><p>What kind of functions have this property? Recalling High School algebra, we can notice that exponentiation functions satisfy the property above. For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*7wOaPUfgmVv8lYqD4I_jug.png" /></figure><p>Although the function <em>h</em> looks similar to the function <em>g</em>, they are not exactly the same. The function <em>g</em> has a squared root in the right hand side of the equation. Therefore, to get rid of it, we can square our inputs of the function <em>g</em>. Squaring <em>x</em> gives us <em>x²</em>, squaring <em>y</em> gives us <em>y²</em>, and squaring <em>sqrt(x²+y²)</em> gives us <em>x²+y²</em>. We are ready to substitute these values back</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*js4gPNVy2kE_3JMMSA54eQ.png" /></figure><p>You might notice that we chose the base 5 for our formula. In fact, we can choose any base, like 1, 2 or <em>e</em>. To generalize over all the bases, let’s pick the base of <em>e^A</em>, where <em>A</em> is some unknown constant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*xpsCoStDgxw0VSoq3AVgSQ.png" /></figure><p>Substituting back into <em>g</em> we finally get the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*lDPsBptNcxvLVviWIH6KPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/125/1*ggivMzpOkR4tDKVhuQDW2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*a1x-5_usAcYcFTGrDXxKgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*AqO-_YDXV-vkSf97oOVviQ.png" /></figure><h3>2. A “Normal Distribution” with Two Parameters</h3><p>Let’s plot the resultant distribution using various values for the <em>lambda </em>and <em>A</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c95b97aba73d6911d99f53347af740f/href">https://medium.com/media/6c95b97aba73d6911d99f53347af740f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*fsDLfxfDZXhYKBBk96DYCQ.png" /><figcaption>lambda=1, A = 0.01</figcaption></figure><p>Oh no, our distribution is upside down. So let’s fix that by substituting <em>A</em> for the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*XURV1RXp3EitffZCcnALIA.png" /><figcaption>Notice how we square first and then apply the negative sign</figcaption></figure><p>We get the following equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*laeSriXizbRIsvYGc3aHPA.png" /><figcaption>The negative term h² mirrors the distribution</figcaption></figure><p>Now, by plotting our distributions with various parameters of <em>lambda </em>and <em>h</em> we can observe how to shape of the distribution changes depending on the values of <em>lambda </em>and <em>h</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c23101aeea51bed2bb600e54074fdd03/href">https://medium.com/media/c23101aeea51bed2bb600e54074fdd03/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*PHWSi4Z5nbO_213Nyr4YOw.png" /><figcaption>h=0.01, lambda=1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*R2rHt2fqWau6eT9iGy2gXA.png" /><figcaption>h=0.05, lambda=1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*fjPosRt8kdfvZlsVF6eVQQ.png" /><figcaption>h=0.3, lambda=1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*bSK6qL86sUCiwLcPGYwBJQ.png" /><figcaption>h=0.3, lambda=3. Notice how the lambda value corresponds to the peak of the distribution</figcaption></figure><h3>3. From Two to One</h3><p>So far so good, the curve looks like a normal distribution. However, one problem still persists: for this curve to be considered a true pdf, the area under our curve should be equal to 1. Mathematically,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*ZRfYH-wdibTv5gDwh0jmdw.png" /></figure><p>Let’s solve this integral. Substituting our equation we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*KxjjOek99zVpZhbWxyQAGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*TS2Omr_5nNi24XXnXAzR_g.png" /><figcaption>lambda is a constant</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/71/1*I0Oi304Nfnl3KqxGu5BUGw.png" /><figcaption>substitution term</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*7mUBxber__J0mVQ3XIQe1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/87/1*Y4KQ5iRxNdV7sEAKkPNHsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*Ez4uyadxK_jnTUQTABrsNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*9sbLkqX4T_c0C2K_oSXndw.png" /></figure><p>The resultant integral is called <a href="https://en.wikipedia.org/wiki/Gaussian_integral">Gaussian integral</a> and is equal to the square root of <em>pi</em>. I don’t know why that is, but the complete derivation can be looked up on the Wikipedia. So we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*ZbuYnFpEtjwU_DTXgQQwLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*NJ4FsOA8K22gNtMdum2vkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*reOxBry77ID72Io8DTJvkA.png" /><figcaption>squaring both sides</figcaption></figure><p>Let’s substitute<em> h²</em> in our original equation we derived earlier. We finally get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*tzp4OjAVnGMRyeikpAm2Rg.png" /></figure><p>There are 2 important things we did. <strong>First</strong>, we got rid of the unknown <em>h</em>, leaving only a single unknown — <em>lambda</em>. <strong>Second</strong>, since we computed the integral equals 1, we are now <strong>guaranteed </strong>to have the area under the curve equal to 1. By constraining ourselves with a single parameter <em>lambda</em>, we can see how, unlike our previous examples, the width of the distribution now depends on the value of <em>lambda.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87eb26389b448c4989d8aea2dbd6307f/href">https://medium.com/media/87eb26389b448c4989d8aea2dbd6307f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*MK0uuZz7Y6ZGPMSmZrqoYw.png" /><figcaption>lambda=0.5</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*Q5eRhZq8jw4ZarL5S5Qg5w.png" /><figcaption>lambda=3</figcaption></figure><h3>4. From One to Spread</h3><p>What <em>lambda </em>essentially controls is the <strong>spread </strong>of the values (variance- sigma²). The higher the value — the lower the spread — the narrower the distribution is. Let’s define that relationship between <em>lambda </em>and <em>sigma </em>mathematically.</p><p>We know that the variance of a pdf is calculated by <a href="http://matcmath.org/textbooks/engineeringstats/pdf-mean-variance/">the following formula</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*4gqTS0Y_PjtLYFVwTsih-Q.png" /></figure><p>Substituting for the <em>f(x)</em> gives us</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*iGhXOlifTzRk4pT7yiuNtw.png" /><figcaption>The mean is zero since the distribution is centered around 0</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*OPHSAsHkrlnZEWyXos7orA.png" /><figcaption>Notice x² is split into x times x to integrate by parts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*J59WdqOZGUmNiJXvfIiD9Q.png" /><figcaption>Left term goes to zero</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*1_WchArBMWbw2TD_5ir9mg.png" /><figcaption>Right term</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*qSvDZLzig_C30NUUhcOmqw.png" /><figcaption>The integral goes to 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*1RZcmZ7X4vJ3RHvJoI0AOw.png" /><figcaption>We are left with this</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*F-9iUdk6FIXfrFj8B7jvZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*JpH_EvQET9M54QkPYl6b8g.png" /><figcaption>Taking a square root</figcaption></figure><p><strong>Now we can clearly see that <em>lambda </em>and <em>sigma </em>are inversely proportional: the higher the <em>lambda </em>— the lower the <em>sigma</em>, and vice versa.</strong></p><p>Performing the final substitution for <em>lambda </em>we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*zDgoVI5jCROJ-Jukmk_oZQ.png" /><figcaption>Notice how it looks almost like the actual equation already</figcaption></figure><h3>5. The Final Form: Spread and Mean</h3><p>The formula above describes a normal distribution that is centered on 0. That is, the mean is 0. Suppose we want to be able to center it on different values. From the perspective of the distribution, it means shifting it along the x-axis to the right (positive mean) and to the left (negative mean).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*j-mlSer7GksGlY2IVqDOTw.png" /><figcaption>3 normal distributions with different means and the same variance</figcaption></figure><p>In other words, we need to add (substract) a constant value <em>mu </em>to (from) each of the <em>x</em>’s. As the previous equation shows, there is only one <em>x</em> in that equation, so we simply modify it like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*D1HrdoN0doMRForBIYI8bQ.png" /><figcaption>Notice the top right part where mu is applied to x</figcaption></figure><p>Recall that to move a curve on the x-axis to the <strong>right </strong>we need to <strong>subtract </strong>the constant, and to move it to the <strong>left</strong>, we need to <strong>add</strong> it. Since we want positive means to be on the right, we substract it from the <em>x</em>’s.</p><p>And this is it, we have finally arrived at the final equation for the normal distribution. I hope this article helped you to gain a bit of intuition behind the normal distribution formula!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91512fd81ae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A New Way to Think About the “Bias vs. Variance” tradeoff]]></title>
            <link>https://miroslavtushev.medium.com/a-new-way-to-think-about-the-bias-vs-variance-tradeoff-88713eaa08e5?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/88713eaa08e5</guid>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[variance]]></category>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[underfitting]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 20:20:20 GMT</pubDate>
            <atom:updated>2021-11-15T14:12:03.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*U0IZuWb3NgZyb4whKdXPVw.png" /></figure><p>In ML, the tradeoff between <strong>overfitting </strong>and <strong>underfitting </strong>is often depicted using a U-shape. Traditionally, we want our model to learn enough information from the <strong>train set</strong> to be able to generalize well over the unseen data (<strong>test set</strong>). At the same time we don’t want it to learn too much to capture the noise and spurious patterns that pertain to a specific dataset, which will result in poor generalization.</p><p>The tradeoff between overfitting and underfitting is particularly apparent in linear models. However, neural nets very often have near-perfect accuracy on the train and the test sets at the same time. Why does it happen? The reason is model complexity — neural nets are typically more complex, being able to learn thousands and millions of parameters. This added complexity yields an interesting effect where such models are able to minimize the test error even when the train error is already zero. Such effect can be graphically depicted as a “double descent” U-curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*ZqErc8Cw7FE22g1X" /></figure><p>This effect is described in the paper <a href="https://arxiv.org/pdf/1812.11118.pdf">Reconciling modern machine learning practice and the bias-variance trade-of by Belkin et al.</a> In this article I will empirically investigate and visualize the results of the paper.</p><p>For this task I picked a toy dataset from <a href="https://www.kaggle.com/c/house-prices-advanced-regression-techniques">Kaggle on housing prices</a>. The dataset contains various houses’ characteristics and their corresponding sale prices. The goal is to predict the price based on the characteristics. This dataset is traditionally used as a gateway into ML, as it is simple to understand and manipulate. The dataset contains 1168 observations and 78 variables.</p><p>I initially performed basic imputation and FE to prepare the data for the modeling. These manipulations are outside of the scope of this article, and the full code can be found on <a href="https://github.com/miroslavtushev/Medium-double-u-curve">my GitHub</a>. Although Belkin et al. only investigated classification tasks, I will also add regression into the bucket to see if the same relationship holds. As the predictor variable is originally continuous (sale price), I convert it into several equally-sized bins using pandas’s <em>qcut </em>method. Following the paper, I test the performance of the Random Forest Classifier (Regressor) by varying the <strong>number of leaves</strong> and the <strong>number of trees</strong>. The error is measured with Accuracy (classification) and Mean Absolute Error (regression).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*d12O27Gdvki28QsDEHCiMw.png" /><figcaption># of classes = 4</figcaption></figure><p>I initially investigate the double-descent relationship using 4 classes. I train a Random Forest Classifier without bootstrapping with 10–300 leaves and a single tree, and 1–100 trees with 300 leaves. The increase in the number of trees can be thought of increased complexity of the model. As the plot shows, <strong>train accuracy</strong> plateaus around 300 leaves and does not increase much with increased complexity. However, <strong>test accuracy</strong> jumps as the number of trees goes up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*TZj6qgF7qH8TMEtAssT95A.png" /><figcaption># of classes = 30</figcaption></figure><p>A similar relationship can be observed with a larger number of classes. Here I adjusted the number of leaves and the number of trees accordingly. As we can see, even when the train accuracy plateaus long before increasing the complexity, the jump in accuracy can still be observed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*ayh-0WwcXsbCDFjBrXiFFg.png" /><figcaption>Regression</figcaption></figure><p>Finally, I investigate this relationship for a regression task. We can see that the double U curve is not present in this case.</p><p>The takeaway message is that with increased complexity, the accuracy of the test set goes up when the number of classes is small. As we increase the number of classes, the jump becomes less and less pronounced. Regression can be considered as a special case of classification with <em>number of classes = number of observations</em> (at most). I believe this is the reason why we don’t see the double U curve in the regression task. The original paper has observed a similar relationship.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88713eaa08e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Trick to Understand the t-test]]></title>
            <link>https://miroslavtushev.medium.com/a-simple-trick-to-understand-the-t-test-2c2a9e7f1dc5?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c2a9e7f1dc5</guid>
            <category><![CDATA[t-test]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Thu, 04 Nov 2021 14:33:39 GMT</pubDate>
            <atom:updated>2021-11-07T17:40:06.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*665rU_oATAQ9P0QAd4KO1Q.png" /></figure><p>The t-test is a statistical test to compare the means of two groups. It is one of the most common techniques to check if two groups come from the same population. One of the most ubiquitous applications of the t-test in the industry is A/B testing, where two versions of UI are compared to determine which one generates more clicks or time spent on a page.</p><p>Unfortunately, understanding where the t-test’s equation comes from is a little bit tricky, especially given that there are many variants of the t-test out there, each serving its own purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXr3MuM8cUOYjoyBv9ocZg.png" /></figure><p>In this article, I will provide you with an intuition for the t-test’s equations using a simple signal-to-noise analogy.</p><p>If you look at the above variations of the t-test, first thing you’ll notice is that each formula is a fraction, with <strong>numerator</strong> being some sort of a difference between the two means. For example, one-sample t-test calculates the difference between the population’s mean (<em>mu</em>) and the sample’s mean (<em>x</em>). Independent two-sample t-test calculates the difference between two means of two samples — <em>X1</em> and <em>X2</em>. We will call this difference a <strong>signal</strong>.</p><p>The <strong>denominator</strong> of the t-test’s equations represents the level of <strong>noise</strong>. To simplify, we can think of it as a level of variance between our samples (or sample and population). Higher values will correspond to more variance, and, as a result, more noise. Each of the denominators contains the sample’s standard deviation (<em>s</em>) with some combination of <em>n. </em>Together they form the <strong>standard error</strong>, which represents how spread out the numerator (<strong>signal</strong>) is expected to be.</p><p>Taken together, the <strong>signal/noise </strong>ratio represent the strength of the signal (difference of means), when the <strong>noise</strong> is taken into account. As the <strong>noise </strong>goes up and the <strong>signal</strong> goes down, the ratio goes down. If you’ve ever tried to have a conversation with someone on a rock concert you will understand what I mean. On the flip side, even barely audible whisper will sound very clear in a complete silence.</p><p>With this analogy in mind, it is straightforward to see under which conditions we can expect significant results for a t-test. In general, the higher your <strong>signal</strong> and the lower your <strong>noise</strong> — the lower the p-value (higher the absolute value of t-statistic). To illustrate this, below I generated two pairs of normally distributed samples with the fixed means (12 and 14), but different sample sizes and standard deviations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6iDYSW6c_8aNjAzH_81Rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dVNlHuFCpUYLv0K2Yq3-Q.png" /></figure><p>I kept the <strong>signal </strong>constant at -2, however, the <strong>noise </strong>was set higher for the 2nd pair, as it depends on the sample size and standard deviation: smaller sample sizes and higher spread produce higher <strong>noise</strong>, which diminishes the <strong>signal</strong>. As a result, the t-statistic is significant for the 1st pair, but not significant for the 2nd pair.</p><p>Consider an extreme example of this relationship below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mKoWbcUuif3mm08i76T3Uw.png" /></figure><p>With large sample size and small standard deviation, the <strong>noise</strong> is almost nil. As a result, any tiny difference between the means will be detectable. Graphically, it looks like the two samples do not overlap much. The resultant t-statistic is highly statistically significant, meaning the probability that the two samples come from the same population is negligible.</p><p>In this article I provided a easy-to-understand analogy of signal to noise ratio applicable to gain an intuition about the t-test. The code for this article is available <a href="https://github.com/miroslavtushev/medium_4">on my github</a>. Let me know if you have any questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c2a9e7f1dc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does my sample have to be normally distributed for a t-test?]]></title>
            <link>https://miroslavtushev.medium.com/does-my-sample-have-to-be-normally-distributed-for-a-t-test-7ee91aaaca2a?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ee91aaaca2a</guid>
            <category><![CDATA[t-test]]></category>
            <category><![CDATA[assumptions]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[normal]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Tue, 26 Oct 2021 17:35:26 GMT</pubDate>
            <atom:updated>2021-10-26T17:35:26.398Z</atom:updated>
            <content:encoded><![CDATA[<p>While reading up on t-test’s normality assumption I came across a lot of conflicting information. Most of the resources online suggest that for the t-test to be valid, the samples have to be normally distributed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YT1Icj2_DjCNZNIkl-HdVw.png" /></figure><p>However, this does not have to be the case. The samples do not have to be normally distributed, given a sufficient sample size. In the t-test, our parameter of interest is the mean. According to the Central Limit Theorem, when repeatedly sampling from a population of any shape, if the sample size if sufficient,<strong> the sampling means</strong> will resemble the normal distribution:</p><blockquote>In small samples most statistical methods do require distributional assumptions, and the case for distribution-free rank-based tests is relatively strong. However, in the large data sets typical in public health research, most statistical methods rely on the Central Limit Theorem, which states that the average of a large number of independent random variables is approximately Normally distributed around the true population mean. It is this Normal distribution of an average that underlies the validity of the t-test.</blockquote><p>source: <a href="https://www.annualreviews.org/doi/pdf/10.1146/annurev.publhealth.23.100901.140546">https://www.annualreviews.org/doi/pdf/10.1146/annurev.publhealth.23.100901.140546</a></p><p>In this article, I will visually demonstrate why that is the case and why the normality of the sample is not required.</p><p>The <strong>central limit theorem</strong> (<strong>CLT</strong>) establishes that, in many situations, when <a href="https://en.wikipedia.org/wiki/Statistical_independence">independent random variables</a> are summed up, their properly <a href="https://en.wikipedia.org/wiki/Normalization_(statistics)">normalized</a> sum tends toward a <a href="https://en.wikipedia.org/wiki/Normal_distribution">normal distribution</a> (informally a <em>bell curve</em>) even if the original variables themselves are not normally distributed (Wikipedia)[1]. In other words, if we have a highly-skewed population and we repeatedly draw samples from it and calculate these samples’ means, the means, when plotted, will be normally distributed (called <em>sampling distribution of the mean</em>).</p><p>Imagine we have a large population and we need to draw a sample from it, like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*AchbZMhB5SOvhErovxU7Yg.png" /></figure><p>The shape of this distribution is highly skewed with many values concentrated around the origin. The Central Limit Theorem states that if we draw many samples from this population, the means of these samples will be normally distributed. The “normalness” of the sampling distribution is dependent on the the sample size.</p><p>Below are presented the results of a simulation of drawing 1000 sampling distributions with sample sizes (n)= 5, 10, 30, and 50.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*BwCjwO1-3aUgY80ouQWDOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*MHHjZXfqtyXtD9bTaUm8MQ.png" /><figcaption>n=5, n=10</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*RoU5QtkeNfzFuXC86oS5_Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*y7nNbHrRdl7ZpbfVznQRyw.png" /><figcaption>n=30, n=50</figcaption></figure><p>As we can see, the larger the sample size — the more “normal” the final sampling distribution will look like, regardless of the population’s distribution.</p><p>How can we be sure that the results produced by a t-test are valid, even when the population is skewed? We can perform a simple simulation. We can create a skewed population, draw 2 samples from it repeatedly and perform a t-test. Since these 2 samples are from the same population, the results of the t-test should not be significant. However, in reality we can expect the results to be significant <em>sometimes</em>. This <em>sometimes </em>will depend on the chosen significance level (alpha). At alpha=0.05, we can expect 5% of simulation results to be significant. Why is that? <strong>Type I</strong> error is committed when a null hypothesis (=no difference between sample means) is erroneously rejected. The Type I <strong>error rate</strong> directly depends on the chosen alpha. With alpha set to 0.05, 5% of the t-statistics produced, on average, will be erroneously assumed significant, even though they were produced by pure chance. Therefore, we can expect Type I error to be committed at the alpha rate, if everything goes as expected.</p><p>Below I created a left-skewed distribution for our simulation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6f25489902dacb5fb5a37869535e97f/href">https://medium.com/media/e6f25489902dacb5fb5a37869535e97f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*1YPoeSJXMQAo6Iepo0blSw.png" /><figcaption>mean and stdev are in gray</figcaption></figure><p>We will now repeatedly perform 10,000 simulations with the sample size = 10.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10a924a62a7dd1c5a76b092c968b0f2b/href">https://medium.com/media/10a924a62a7dd1c5a76b092c968b0f2b/href</a></iframe><p>The resulted <strong>Type I</strong> rate is 0.0497. Upon repeating this simulation over and over the rate tends of fluctuate around 0.05, which is exactly what the alpha was set to. The results are surprisingly robust even with this relatively small sample size.</p><p>For comparison purposes, I rerun the experiment with a normal distribution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d33c9b8df03576a5879b6138e156d6fe/href">https://medium.com/media/d33c9b8df03576a5879b6138e156d6fe/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*1kQIox2IlD68qe69aZ_Mxg.png" /></figure><p>The results were essentially the same.</p><p>Recent trends in research have shown that most papers use non-parametric tests even when it is not necessary. However, if the goal of the study is to compare the difference of means between 2 samples— then the samples do not have to be normally distributed, given a sufficient sample size, and a parametric test, such as t-test, can be applied.</p><p>For more thorough discussion and experimentation with various distribution parameters refer to this paper: <a href="https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/1471-2288-12-78">https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/1471-2288-12-78</a></p><p>[1] <a href="https://en.wikipedia.org/wiki/Central_limit_theorem">https://en.wikipedia.org/wiki/Central_limit_theorem</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ee91aaaca2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top-5 Essential Python Libraries for Data Analysis]]></title>
            <link>https://miroslavtushev.medium.com/top-5-essential-python-libraries-for-data-analysis-abec978672c9?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/abec978672c9</guid>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Sat, 16 Oct 2021 16:09:04 GMT</pubDate>
            <atom:updated>2021-10-16T16:22:27.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZWJzoMSaaMsE2qEb-jT9A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@davidclode?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">David Clode</a> on <a href="https://unsplash.com/s/photos/python?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Python is one of the best choices when it comes to analyzing data. In fact, <a href="https://statisticstimes.com/tech/top-computer-languages.php">Python is THE language when it comes to programming in general</a>. One of the main advantages of Python for data scientists is the abundance of libraries and frameworks for any kind of goal in mind. In this article I present my top-5 data analysis libraries that I regularly use in my workflow.</p><h3>Pandas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vOF5Jj0CSMWexMGRHy1qCg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@millerthachiller?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Pascal Müller</a> on <a href="https://unsplash.com/s/photos/panda?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Every analysis starts with collecting, representing, and storing data. When it comes to representing and storing the data, the priorities have to be <em>a) access speed b) space efficiency</em> and <em>c) ease of use</em>. In my opinion, <strong>pandas</strong> achieves all of the above. <strong>Pandas </strong>allows massive dataset manipulations without iterating each row individually. This comes especially handy for things like filters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0f338f3a5a11e441dc6cf311e3199c4/href">https://medium.com/media/d0f338f3a5a11e441dc6cf311e3199c4/href</a></iframe><p>The code above, from a dataset of app reviews, takes a sample of 1–2 star rated reviews, published before January 1st, 2021.</p><p>Another thing that I like about <strong>pandas </strong>is the ability to quickly generate and represent DataFrames (the default dataset format) in a print-friendly form, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*FuKvASnHY1i8Zu2otyxbYw.png" /><figcaption>p-values for before-after groups</figcaption></figure><p>The table above shows p-values for various groups tested, which were calculated and entered into a DataFrame. This DataFrame can then be printed on the screen and copy-pasted into a document.</p><p>So why is pandas is efficient? Well, simply because its built on top of <strong>numpy</strong>, which brings me to my next library of choice…</p><h3>numpy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*ylf713ct-qvAOXoT4GeuYQ.png" /><figcaption>source: <a href="https://commons.wikimedia.org/wiki/File:NumPy_logo_2020.svg">https://commons.wikimedia.org/wiki/File:NumPy_logo_2020.svg</a></figcaption></figure><p><strong>Numpy </strong>is the choice when it comes to large-scale matrix computations in Python. <strong>Tensorflow</strong>, for instance, requires your data to be converted to <strong>numpy’s</strong> <em>darray </em>format. One of the reasons <strong>numpy </strong>is preferred is because at its core it’s just C. The primitives, for example, such as <em>int </em>or <em>bool </em>are closely tied to C code, as a result, you get the performance of C and convenience of Python. This is often achieved due to the fact that <em>ndarrays </em>— the default <strong>numpy’s </strong>container format, are contiguous in memory and contain a single data type, unlike python’s lists, which can contain different datatypes and <a href="https://docs.python.org/2/faq/design.html#how-are-lists-implemented">are not necessarily contiguous</a>. This makes millions of operations on <em>ndarrays </em>extremely fast. And I haven’t even touched the surface of <strong>numpy’s </strong>capabilities: <em>ndarrays </em>can also be multidimensional, which is very useful in matrix computations and deep learning.</p><p>The fact that <strong>pandas </strong>uses <strong>numpy </strong>underneath makes the conversion between them very easy, which I personally do all the time</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47b3de710c884c8e2fbb7668ff5ede8f/href">https://medium.com/media/47b3de710c884c8e2fbb7668ff5ede8f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*4AmdU9LyXoKTc7iZvm3U2g.png" /></figure><p>One of the jokes data scientist make is that every workflow starts with these 2 lines of code, and there is definitely an important reason for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b396871157d82630acb589ec86a00ff/href">https://medium.com/media/1b396871157d82630acb589ec86a00ff/href</a></iframe><h3>sklearn</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*6Z5O3bCUaALxNoC-QnekMg.png" /></figure><p><strong>sklearn </strong>is the library that enables machine learning in Python. This library contains a variety of ML supervised and unsupervised algorithms and data preprocessing tools, which are organized in a very reusable and extendable architecture. You can create your own <strong>sklearn </strong>classes (called <em>estimators</em>) with your own algorithms very easily: all you have to do is to inherit from sklearn.base.BaseEstimator and implement fit, transform, and predict, if applicable.</p><p>In my work, I found that <strong>sklearn </strong>covers 99% of my needs when it comes to data analysis. Some things even surprised me. For one of my papers, I needed to implement a binary token matrix for a <em>Wikipedia </em>dump for a faster lookup. This matrix would mark the words that are present in each article. I was delighted to learn that the standard CountVectorizer, which counts the words in a dataset of texts, also provides the <em>binary </em>argument:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd06236eb1b36bb9b7acfe7a621ac715/href">https://medium.com/media/dd06236eb1b36bb9b7acfe7a621ac715/href</a></iframe><p>Some other notable features that <strong>sklearn </strong>provides is <em>pipelines</em>, which simplify and organize your workflow. Overall, <strong>sklearn </strong>is definitely worth learning and mastering.</p><h3>SciPy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*tBuXeC2brBGIwVKQuirzJg.png" /></figure><p><strong>SciPy </strong>is another library that provides tools for numerical computations and linear algebra. However, the main reason why this library is particularly useful for data analysis, in my opinion, is its statistical capabilities. In particular, it is extremely easy to execute various statistical tests in <strong>SciPy:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04fdc566812665205c7a3a8a724d2ea7/href">https://medium.com/media/04fdc566812665205c7a3a8a724d2ea7/href</a></iframe><p>Another useful feature of <strong>SciPy </strong>is sparse matrices. A sparse matrix is an efficient representation of a regular matrix. If we have a matrix with a lot of empty elements (for example, zeroes), instead of storing every element in the memory, we can store the addresses of non-empty elements and save a significant amount of space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*HjtF3E8gtzv-0Bc9osxmnQ.png" /><figcaption>source: <a href="http://www.btechsmartclass.com/data_structures/sparse-matrix.html">http://www.btechsmartclass.com/data_structures/sparse-matrix.html</a></figcaption></figure><p>The advantages of sparse matrices are particularly useful for binary matrices for a set of documents, since documents rarely contain all the possible words in the dataset. In my work, sparse matrices are immensely useful, saving gigabytes of RAM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5aa7e57952c929cce388d63f98dd26f2/href">https://medium.com/media/5aa7e57952c929cce388d63f98dd26f2/href</a></iframe><h3>Matplotlib</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dunUtj5Psx-8T55FVi_uzg.png" /><figcaption>source: <a href="https://towardsdatascience.com/cyberpunk-style-with-matplotlib-f47404c9d4c5">https://towardsdatascience.com/cyberpunk-style-with-matplotlib-f47404c9d4c5</a></figcaption></figure><p><strong>Matplotlib </strong>is the main library when it comes to plotting and visualizing your results. The plots can be saved on your disk in various formats and quality-values. One thing I like about this library is how adjustable everything is. For <a href="https://miroslavtushev.github.io/ndp_policy.html">one of my papers</a> I had to combine two box-plots on the same figure. The catch was that the Y-axis had to be completely different for those plots, while both of them had to be visible. While I wouldn’t call these things trivial in <strong>matplotlib</strong>, they are definitely achievable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/129322c317f3b6238133f983089449d4/href">https://medium.com/media/129322c317f3b6238133f983089449d4/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAvaNKw2uLZEtXbZQRiXzQ.png" /></figure><h3>*Honorable mentions</h3><p>The libraries that I list below are the ones I use a lot, but they are too specialized to be useful for every circumstance.</p><p><strong>gensim </strong>— is a great library for a general-purpose NLP tasks, such as topic modeling. The library provides a multi-core LDA implementation, which is insanely fast. However, one potential drawback with it is that it is not easily compatible for other libraries and requires conversion of your datatypes to gensim’s format.</p><p><strong>seaborn</strong> — another great library for visualization. seaborn is built on top of matplotlib, so all the low-level stuff is available from seaborn’s function calls as well. The library is particularly well-optimized for pandas’s DataFrames, outputting truly beautiful graphs, with the ability to customize using different predefined color schemes.</p><p><strong>spaCy </strong>— another useful library for NLP-tasks. While I don’t have an extensive experience with it, I found its Dependency Parsing capabilities more than adequate.</p><p>What are the best libraries for data analysis in Python in your opinion? What libraries do you personally prefer?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abec978672c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Fake Trump Tweets with LSTM]]></title>
            <link>https://miroslavtushev.medium.com/generating-fake-trump-tweets-with-lstm-7c5979229e81?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c5979229e81</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Fri, 16 Apr 2021 13:06:14 GMT</pubDate>
            <atom:updated>2021-04-16T20:04:47.703Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a part 2 of my series of articles on generating fake Trump tweets. You can <a href="https://miroslavtushev.medium.com/generating-fake-trump-tweets-using-markov-chains-d75d9a2eed08">read part 1</a> here where I used Markov Chains to generate fake tweets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*oyUzT-DZ0xbgTHV2Yu-IPg.png" /></figure><p>In this article we are going to use LSTM for even better results. LSTM (Long Short Term Memory) is a special case of RNN with the ability to memorize long-term dependencies by preserving the state across cells. You can read more about how it actually works in <a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/"><strong>this excellent article</strong></a><strong> </strong><em>(seriously, it’s amazing, go read it)</em><strong>. </strong>LSTM is widely used in a variety of tasks, such as translation, speech recognition, time series predictions, and text generation, which we will do in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5W8FrASMi93Z81NlAui4w.png" /><figcaption><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">source</a></figcaption></figure><p>We are going to be reusing the same <a href="https://www.thetrumparchive.com/faq">massive dump of Trump’s tweets</a> from the previous part. The source code is available <a href="https://github.com/miroslavtushev/medium_3/blob/main/LSTM.ipynb">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fc66932b7f81287e8c4a10d746a7c60/href">https://medium.com/media/6fc66932b7f81287e8c4a10d746a7c60/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*sbT7sRZw3lj249ww_yOA7A.png" /></figure><p>The preprocessing steps are identical to those from the previous part. Namely, we remove hyperlinks, special symbols, and tokenize the tweets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a550ba612490b7c3c3e2697ec929ed9/href">https://medium.com/media/0a550ba612490b7c3c3e2697ec929ed9/href</a></iframe><p>The length of preprocessed tweets ranges from 0 to 100 tokens, with the majority of them concentrated around 20–30 mark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*PjdvEDJYUDeTvRHFH9WdDA.png" /></figure><p>Before feeding the data to our NN, we need to generate sequences and labels. The core idea behind text predictions is the following: <em>given a sequence of n words, what is the most likely word to follow? </em>To realize that idea, similarly to what we did for Markov Chains, we are going to generate sequences of tokens and their corresponding labels.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f6033fb413ca9cc3b7b61be115bb1d7/href">https://medium.com/media/8f6033fb413ca9cc3b7b61be115bb1d7/href</a></iframe><p>Keras provides a variety of ways to manipulate textual data. In this case, we use its Tokenizer to first generate unique ids for each token, and then iterate over our tweets to generate all possible sequences of ids starting from the beginning of a tweet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c21f5fc70de60050f67462ffbf589393/href">https://medium.com/media/c21f5fc70de60050f67462ffbf589393/href</a></iframe><pre>1188946</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a626bab7a50059c1d3dfb206ab49e505/href">https://medium.com/media/a626bab7a50059c1d3dfb206ab49e505/href</a></iframe><p>The labels are simply the last word in a sequence (prediction). Here is what a slice of our data looks so far:</p><pre>[212] 6<br>[212, 6] 92<br>[212, 6, 92] 26<br>[212, 6, 92, 26] 380<br>[212, 6, 92, 26, 380] 1079<br>[212, 6, 92, 26, 380, 1079] 25</pre><p>For example, given that we’ve seen the sequence [212, 6, 92], the most likely token to follow that sequence is 26.</p><p>For the algorithm to work, each sequence has to be of the same length. In practice that means we have to pad the sequences with zeros.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d0a200c44d8232b2ed840ed5013015f/href">https://medium.com/media/5d0a200c44d8232b2ed840ed5013015f/href</a></iframe><pre>array([[ 212,    0,    0, ...,    0,    0,    0],<br>       [ 212,    6,    0, ...,    0,    0,    0],<br>       [ 212,    6,   92, ...,    0,    0,    0],<br>       ...,<br>       [4996,  403,  104, ...,    0,    0,    0],<br>       [4996,  403,  104, ...,    0,    0,    0],<br>       [4996,  403,  104, ...,    0,    0,    0]])</pre><p>Labels have to be converted to one-hot representations too… however, the size of such matrix would be huge: total # of examples times # of unique tokens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6c4f8aae6819d861cb4b4e070f63d9b/href">https://medium.com/media/d6c4f8aae6819d861cb4b4e070f63d9b/href</a></iframe><pre><strong>MemoryError</strong>: Unable to allocate 255. GiB for an array with shape (1188946, 57668) and data type float32</pre><p>To mitigate that, you can save a lot of space by adding an optional dtype=’int8&#39; argument. But I will take a different approach by changing the loss function.</p><p>We are now ready to define our model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f23f74461b281f6ce6cb7e3dea1a6f20/href">https://medium.com/media/f23f74461b281f6ce6cb7e3dea1a6f20/href</a></iframe><p>The first layer is Embedding layer — it takes a sequence and outputs an embedding in the shape of (99, 256). Each token is represented by a vector of 256 numerical values. Mask_zero is used to tell the layer that zeroes were added for padding.</p><p>LSTM is a layer with 256 units, and accepts a 3d tensor as an input in the form of (batch, timestep, features). With Embedding layer added, the input of LSTM layer will be (4096, 99, 256). I added dropout rate of 0.3 here, however, it is not necessary. The stateful is set to False so we don’t preserve the state between batches. Set it to True when your text is continuous, so that your current sequences are related to your previous ones.</p><p>The final layer outputs the probability of each word to follow a given sequence.</p><p>Note that by using loss=’sparse_categorical_crossentropy’ we don’t have to one-hot encode our y anymore, which saves a lot of space. adam is a great optimizer for a variety of tasks. We’ll train our model for 30 epochs with 4096 batch size. This model has 30,108,996 trainable parameters and it takes about 30 minutes to train on my machine with enabled GPU training.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfa1bebd11d73dddbcda81fdb8e8647d/href">https://medium.com/media/bfa1bebd11d73dddbcda81fdb8e8647d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*2Ee9hECC5QyG7zKEuuUXJA.png" /></figure><p>Once the model is trained we can generate our predictions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/562753b5ed105cd45671d40a24c0d84f/href">https://medium.com/media/562753b5ed105cd45671d40a24c0d84f/href</a></iframe><p>The function above takes an initial seed and required length and predicts the most likely token based on the current sequence, updates the sequence with the new tokens, and runs the prediction again. id_to_word is a reverse-lookup dictionary for tokens.</p><p>Let’s see what Mr. President has to say!</p><pre>democrat senators are doing a great job . i am not</pre><pre>democratic states , the democrats are not going to be a total disaster .</pre><pre>republican senators have a great job for the great state of texas . he will be a great governor ! #maga #kag and , @senatorheitkamp. and , others , the people </pre><pre>gop senators must stop the flights from the united states . </pre><pre>obama ’s campaign is a total disaster . </pre><pre>biden has been a total disaster . i will be back soon ! #maga #kag #tcot @foxbusiness oh well , i ’m not going to be a total mess .</pre><p>Only NN can reveal his deep admiration for democrats. I’m glad that we kept punctuation as separate tokens. It looks like coherent sentences with it.</p><p>Below I trained a slightly different model to see what happens.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f1ac6c8ddc814e6e255332865d70d40/href">https://medium.com/media/3f1ac6c8ddc814e6e255332865d70d40/href</a></iframe><p>Here’s a new set of predictions</p><pre>republican senators are working hard to get the job done in the senate . we have a great state and , great healthcare ! we need strong borders and crime !</pre><pre>obama is a disaster for the people . he is a disaster . he is a great guy . he is a winner . he is a winner . he is a winner . he is a winner . he is a great guy and a great guy . he will be missed !<br> <br>bernie sanders is lying to the people of the united states . he is a total mess . he is a total mess . he is a total mess . he is a total mess ! he is a total mess ! he is a corrupt politician ! a total witch hunt ! no collusion , no obstruction . the dems don ’t want to do it . he is a corrupt politician ! he is a corrupt politician ! he is a corrupt politician ! he is strong on crime , borders , and , the enemy of the people !</pre><pre>democrats stole election results . they are a disgrace to our country , and , we will win ! </pre><pre>gop senators are working hard on the border crisis . the dems are trying to take over the border . they are now trying to take away our laws . </pre><pre>biden will bring back our country , and we are going to win the great state of texas . we need you in a second election .</pre><p>While the predictions are good enough, here are a few areas we can improve upon:</p><ol><li><em>Garbage in — garbage out</em>. 90% of success stems from good data. A more careful preprocessing can be done. For instance, you can try to remove hashtags since I found that predictions always go into a “vicious circle” of hashtags when the model doesn’t know what to predict. It will simply output a ton a unrelated hashtags, which obviously doesn’t have a lot of value. Another thing to try would be drop tweets with too low or too high length.</li><li>Model architecture. I was hoping to achieve better results with a deeper NN with less units, but apparently shallower, wider NN worked better for me. You can experiment with the # of layers, # of units, and dropout rate.</li><li>Replace Embedding layer with the actual word embeddings trained on your dataset, such as Glove or Word2vec.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c5979229e81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating fake Trump tweets using Markov Chains]]></title>
            <link>https://miroslavtushev.medium.com/generating-fake-trump-tweets-using-markov-chains-d75d9a2eed08?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/d75d9a2eed08</guid>
            <category><![CDATA[numpy]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[markov-chains]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Sat, 10 Apr 2021 03:21:40 GMT</pubDate>
            <atom:updated>2021-04-16T13:10:07.901Z</atom:updated>
            <content:encoded><![CDATA[<p>Donald Trump, a former US president, is one of the most controversial presidents in the modern US history. His presidency was remembered by the divisive and sometimes borderline offensive rhetoric. On January 8th, 2021 his Twitter account was suspended due to the attack on the US Capitol.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*wpWLBk-b0nBHCxpHecdk7w.png" /><figcaption>Twitter permanently suspends Trump’s account</figcaption></figure><p>And here’s what Trump’s reaction was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*M78QVdKzU_ay-9nWOltrMA.png" /></figure><p>Wait a second. How did he tweet if his account was suspended? He didn’t actually. The tweet above was generated by <strong>Markov Chains</strong>! I only supplied the initial word — “<em>twitter” — </em>and the rest was generated automatically.</p><p>In these series of articles I will explore state-of-the-art techniques for text generation (<a href="http://(part 2 is here)">part 2</a>). We will start with simple ones and gradually ramp up the complexity. In this article, I will demonstrate how you can use Markov Chains to generate pretty believable Trump’s tweets. The code is available <a href="https://github.com/miroslavtushev/medium_2/blob/main/Trump_generator.ipynb">here</a>.</p><blockquote>A <a href="https://en.wikipedia.org/wiki/Markov_chain#Markov_text_generators"><strong>Markov chain</strong></a> is a <a href="https://en.wikipedia.org/wiki/Stochastic_model">stochastic model</a> describing a <a href="https://en.wikipedia.org/wiki/Sequence">sequence</a> of possible events in which the probability of each event depends only on the state attained in the previous event.</blockquote><p>In plain English, you have a set of states and an agent, that jumps between these states with a certain probability. With respect to text generation, each state can be described as a separate word (or n-gram), and each probability — is a probability of another word following that state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*RtIO8H4msnkijc2ECN1D3Q.png" /><figcaption>An example of Markov Chain for text generation</figcaption></figure><p>In this contrived example, each state represents a word and each edge represents a possible transition between states, with a certain probability. Suppose we start with the state <strong>I </strong>and jump to state <strong>like</strong>. From there, there is a slight off-chance (20%) that we jump to <strong>cats </strong>and then finish on the <strong>dot</strong>, resulting in “<strong>I like cats.</strong>”.<strong> </strong>On the other hand, we can also transition from <strong>like </strong>to <strong>dogs </strong>with 80% chance and then jump to <strong>and </strong>and <strong>cats</strong>, resulting in “<strong>I like dogs and cats.”</strong>.</p><p>The bottom line is, there are different combinations available and the “<em>stochastic” </em>part of the Markov Chains definition makes all these sentences non-deterministic and therefore possible. Which makes it especially fun for text generation! So without further ado, let’s get started with tweet generation.</p><p>For this project I used a public dump of Trump’s tweets from 2008 up until his ban. The dataset is available <a href="https://www.thetrumparchive.com/faq">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fc66932b7f81287e8c4a10d746a7c60/href">https://medium.com/media/6fc66932b7f81287e8c4a10d746a7c60/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*sbT7sRZw3lj249ww_yOA7A.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad3c15cd24fbcf9f979e81ebd7c91d48/href">https://medium.com/media/ad3c15cd24fbcf9f979e81ebd7c91d48/href</a></iframe><pre>(56571, 8)</pre><p>We are not particularly interested in all those columns, except for the <strong>text </strong>column.</p><p>Before we continue, it is a good idea to perform some basic cleaning and text preprocessing. For text generation we don’t want to stem or lemmatize the tweets. We want to preserve the original words. But some things, like hyperlinks, or quotations marks are not necessary, so we remove them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a550ba612490b7c3c3e2697ec929ed9/href">https://medium.com/media/0a550ba612490b7c3c3e2697ec929ed9/href</a></iframe><p>Each tweet in processed_tweets<strong> </strong>is a list of tokens. One important part — we want to preserve the punctuation. I will explain later how it will help us to generate more believable sentences. By the way, my code is loosely based on <a href="https://www.kdnuggets.com/2019/11/markov-chains-train-text-generation.html">this</a> article, so feel free to check it out later.</p><p>Now let’s talk about how our algorithm would work. For Markov Chains, we need to define 2 things: <strong>states </strong>and <strong>transitions</strong>. How do we define a state? By the analogy with the previous example, we can define our states as single words from tweets, and transitions as probabilities for each <em>word_i</em> to follow <em>word_i-1</em>. However, such approach will not generate believable tweets because each <em>word_i</em> will not have sufficient context by only considering a single <em>word_i-1</em>. To rectify it, we will define a parameter <strong><em>k</em></strong><em> </em>that will denote how many words behind we look for before predicting the next word. As a concrete example, here is our original tweet:</p><pre>&#39;Getting a little exercise this morning!&#39;</pre><p>And here’s the same tweet with <strong><em>k=2</em></strong><em>:</em></p><pre>[&#39;Getting a&#39;,<br> &#39;a little&#39;,<br> &#39;little exercise&#39;,<br> &#39;exercise this&#39;,<br> &#39;this morning&#39;,<br> &#39;morning !&#39;]</pre><p>As we can see, each state represents each possible context in a tweet. Now, when we generate each possible state for each of the tweets, how do we actually predict new words? Let’s take a look at our example again. What’s the most likely word to follow the state “a little<em>”</em>? Well, there is only one word possible — “exercise”! Our new state is “little exercise”. Now imagine we have another tweet like this:</p><pre>&#39;A little kitty was crossing a street. A little kitty was scared.&#39;</pre><p>Now we have the word “kitty” after the state “a little” that appears 2 times, as opposed to the word “exercise”. Naturally, given these 2 tweets, we would predict the word “kitty” after the state “a little”, so the new state is “little kitty”. <strong><em>And that is the core of Markov Chains. </em></strong>You start with a state, predict the most likely word to follow that state and your new state is now that new predicted word plus the previous word. You continue until you have no words to predict, or until you’ve reached the required length. That’s it!</p><p>For Markov Chains to work, however, you need a table to look up and count which words would follow which states. So we create a matrix, where rows will represent states, and columns will represent words that follow these states.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b13ec66d779ed2ce4a226968233b6d6e/href">https://medium.com/media/b13ec66d779ed2ce4a226968233b6d6e/href</a></iframe><p>The code above is self-explanatory. We create a sparse matrix with n_rows = <em># of distinct states</em> and n_cols = <em># of distinct words</em> (in all of the tweets, of course). One little trick: if you create the dok_matrix using the default constructor — you will run out of memory if you convert it into a numpy matrix. The solution? Use a different dtype! By default, the dtype is set to float64, so uint16 cuts the space requirements by a factor of 4.</p><p>Let’s convert our lists of states and words into dictionaries so we can address specific state-word pairs in our matrix using the words and states themselves as strings</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49848193635ec16bb4a4b96bb833be55/href">https://medium.com/media/49848193635ec16bb4a4b96bb833be55/href</a></iframe><p>We now ready to fill out our matrix. What should go in there? For each state-word pair, we count the number of times that word followed that specific state. We count over all of our tweets, of course. For example, if we have a state “a little” and the word “kitty”, their respective cell will be equal to 2 (from the previous example). The code below does exactly that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25e4927997f590a0721b06f0022fe658/href">https://medium.com/media/25e4927997f590a0721b06f0022fe658/href</a></iframe><p>We are now ready to generate tweets!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20f7ebfe57049027cf93b272f0dc0215/href">https://medium.com/media/20f7ebfe57049027cf93b272f0dc0215/href</a></iframe><p>The function sample_next_word_after_sequence<em> </em>takes a state and extracts the corresponding row with word counts. Each count is weighted and converted to probability. Higher counts — higher probabilities. Using those probabilities we generate the next possible word.</p><p>stochastic_chain<em> </em>starts with a state and repeatedly calls sample_next_word_after_sequence<em> </em>to obtain new words. Each new word is appended to the existing chain, and the current state is shifted (transitioned). When the required chain length is reached — the algorithm is terminated and the string is returned. Here is a sample tweet generated by this method:</p><pre>&#39;exclusive @realdonaldtrump updates ! we can all agree the u .s.a. can give america great ! see&#39;</pre><p>We can see that the chain is exactly 17 (15 + 2 initial) words long. There are 2 problems with this tweet. First, it ends abruptly, ideally we would want it to end on a period, so that each sentence is complete. Second, it still lacks randomness. The algorithm will only generate existing pieces and snippets of text that are in the tweets. It is not <em>truly </em>random…</p><p>Let’s address each of the concerns and modify our algorithm accordingly. How many words each tweet should have? 10? Likely. How about 50? May be… a 100? Not so likely. In fact, we can model the probability of each length easily — we already have all the tweets at our disposal! In what follows I will define a <strong>CDF</strong> — <strong>Cumulative Distribution Function</strong>.</p><p><a href="https://en.wikipedia.org/wiki/Cumulative_distribution_function"><strong>CDF</strong></a> evaluates the probability that <em>X </em>will take on values less or equal to <em>x</em>. In other words, as <em>x</em> gets larger and larger, the area “behind” it grows larger as well, thus increasing the probability. At the extreme case — when <em>x </em>is the largest value in our dataset — the probability that it takes on that value or less is 1, because there is no other value our there to the right of it! We will use the same idea to calculate the length of each tweet and terminate it as it grows larger and larger.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdac5e75fccc194b990802a78f4cabc9/href">https://medium.com/media/cdac5e75fccc194b990802a78f4cabc9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*eyE8Sq2nxVYq7A29A4hQLg.png" /></figure><p>The code above sorts all the possible lengths in our dataset in increasing order, calculates a cumulative sum and rescales them into 0–1 range.</p><p>Now let’s address the second concern — the lack of randomness. How can we rectify it? Well, the simplest way would be to have a tiny chance of selecting a completely random word out of all available words, instead of picking the words from a predefined set of words that can follow the state. We can define a parameter <strong><em>alpha</em></strong><em> </em>that will “fire up” with a 0.1% chance every time we need to append a new word and select a random word out of the entire set of words.</p><p>With both these things addressed, here’s our final algorithm to generate fake tweets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe3f4c478fd0b6f87a4c3ecd8b1bea14/href">https://medium.com/media/fe3f4c478fd0b6f87a4c3ecd8b1bea14/href</a></iframe><p>The only major difference is the alpha parameter and this line</p><pre>elif next_word in list(“.!?”):</pre><p>which uses our <strong>CDF </strong>to check if it’s time to terminate a sentence. In what follows I will show some funny tweets I was able to generate with this algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*WhGgV0FM2ml0MiQjjxumKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*VUEy2ww5YpWfpCNTmvZViw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Krb4NGAN5NvLeYSUGeVUoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*oMUbId_nwo9HAYie3_4CBw.png" /></figure><p>Here are some examples with <strong><em>k=3</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*LioLB5dmlLSsrW5LiMI8ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*WMzQnRvvm-9XCGZwvuIHaw.png" /></figure><p><strong><em>k=4</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*oyUzT-DZ0xbgTHV2Yu-IPg.png" /></figure><p>As we can see, increasing the <em>k</em> can lead to more coherent sentences. At the same time, it limits the number of possible states and as a result requires a larger dataset.</p><p>That’s it! In the next article we will talk about more advanced text generation strategies. I hope you like what you saw. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d75d9a2eed08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Analysis of Red Hot Chili Pepper’s Lyrics Using NLP]]></title>
            <link>https://miroslavtushev.medium.com/an-analysis-of-red-hot-chili-peppers-lyrics-using-nlp-e9b88eb7213c?source=rss-7b877a036858------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9b88eb7213c</guid>
            <category><![CDATA[tf-idf]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lda]]></category>
            <category><![CDATA[red-hot-chili-peppers]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Miroslav Tushev]]></dc:creator>
            <pubDate>Wed, 07 Apr 2021 20:30:08 GMT</pubDate>
            <atom:updated>2021-11-06T20:49:32.283Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*v1CQ2boki-f3SSGH9wyB-g.jpeg" /><figcaption><a href="https://www.nme.com/news/music/red-hot-chilli-peppers-flea-memoir-more-details-revealed-2537757">source</a></figcaption></figure><p>I heard Red Hot Chili Peppers for the first time about 10 years ago and I instantly became obsessed with them. They were (and still are) my #1 favorite band, right after Metallica, which I loved during my teenage years. Despite the fact that many people define RHCP as a typical “funk” band, their musical style has evolved over the years significantly. Early (pre-1999) RHCP’s songs stood out by their explosive slap bass riffs, while post-1999 Peppers had become more melancholic. Does the same relationship hold for their lyrics though? In this blog I will apply common NLP techniques to answer this question <em>(full code is available at my </em><a href="https://github.com/miroslavtushev/An-Analysis-of-Red-Hot-Chili-Pepper-s-Lyrics-Using-NLP"><em>GitHub</em></a><em>)</em>.</p><p>For this analysis I crawled <a href="http://azlyrics.com/">azlyrics.com</a> and downloaded RHCP’s lyrics, organized by album. This resulted in every album from 1984 to 2016:</p><pre># sort albums by year<br>albums = sorted([d for d in os.listdir(os.curdir) if os.path.isdir(d) and d.endswith(‘)’)], <br> key=lambda x: re.search(“(\d{4})”, x).group(0))<br>albums</pre><pre>[&#39;The Red Hot Chili Peppers (1984)&#39;,<br> &#39;Freaky Styley (1985)&#39;,<br> &#39;The Uplift Mofo Party Plan (1987)&#39;,<br> &quot;Mother&#39;s Milk (1989)&quot;,<br> &#39;Blood Sugar Sex Magik (1991)&#39;,<br> &#39;One Hot Minute (1995)&#39;,<br> &#39;Californication (1999)&#39;,<br> &#39;By The Way (2002)&#39;,<br> &#39;Stadium Arcadium (2006)&#39;,<br> &quot;I&#39;m With You (2011)&quot;,<br> &quot;I&#39;m With You Sessions (2013)&quot;,<br> &#39;The Getaway (2016)&#39;]</pre><p>We’ll begin with typical text preprocessing steps. For this analysis I removed punctuation, converted to lower case, removed English stop-words and lemmatized the words. The reason why I chose lemmatization over stemming is simple: to preserve the meaning of the words so I can examine them later. In projects where the meaning doesn’t matter that much, however, we can apply stemming.</p><p>To start off, let’s display the number of unique words per album:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*8IPpMBFRJF5R-T_UVbJcjg.png" /></figure><p>Looks like Stadium Arcadium is the most sophisticated album because it uses the most number of unique words! Or is it? Let’s weight them by the total word length</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*eVAtcrrhCsNniB6VvL3oEg.png" /></figure><p>Let’s visualize them too</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*m6ngRMFDQbq97s3BRXAPfg.png" /></figure><p>Now it doesn’t look so unambiguous anymore. In fact, the <strong>unique / total</strong> goes down from One Hot Minute to I’m With You! This is interesting, because RHCP produced their best songs during that era, arguably of course. Take a look at their discography rankings on <a href="https://en.wikipedia.org/wiki/Red_Hot_Chili_Peppers_discography">Wikipedia</a>. From Californication on, they absolutely dominated all the charts across different countries. Looks like they didn’t use too many different words to write amazing music though.</p><p>By The Way, if you’re wondering how I plotted this — it’s simply <em>seaborn </em>package with <em>‘fivethirtyeight’</em> style.</p><p>Now let’s take a look at the most used words, by total count, per album</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*8xyNQkP-ohsrX3BPRc0X3g.png" /></figure><p>Too bad. Lots of uninformative words, such as “get”, or “know”. Although some songs are clearly recognizable (e.g. “party”, “want”, “pussy” from <em>Special Secret Song Inside</em>). Let’s add a level of sophistication and apply TF-IDF.</p><p>For TF-IDF, I concatenate each song into a single string for each album.</p><pre>tfidf = TfidfVectorizer(preprocessor=None, stop_words=None)<br>X = tfidf.fit_transform(tfidf_corpus)<br>X.A.shape</pre><pre>(12, 4007)</pre><p>We have 12 rows, one per album and 4k unique words. The following code will generate top-5 words with the highest TF-IDF scores, per album:</p><pre>vocab = {v: k for k, v in tfidf.vocabulary_.items()}<br>vocab = sorted(vocab.items(), key=lambda x: x[1])<br>vocab_df = pd.DataFrame(X.A, columns=[c[1] for c in vocab], index=albums)</pre><pre>for i,a in enumerate(albums):<br> largest = vocab_df.iloc[i].nlargest(5)<br> RHCP.loc[a, ‘tfidf:word #1’] = largest.index[0]<br> RHCP.loc[a, ‘tfidf:word #2’] = largest.index[1]<br> RHCP.loc[a, ‘tfidf:word #3’] = largest.index[2]<br> RHCP.loc[a, ‘tfidf:word #4’] = largest.index[3]<br> RHCP.loc[a, ‘tfidf:word #5’] = largest.index[4]<br>RHCP.iloc[:,3:]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*IP7RWvWPzf9a9YAJHLX9_A.png" /></figure><p>May I say I LOVE the fact that the word “californication” finally appeared on Californication album! The way it should be. Looks like TF-IDF picked up on at least 3 different songs in Stadium Arcadium: Hump de Bump, Readymade, and Torture Me. We also have the word “funky” appearing for Mother’s Milk. Does it mean it’s the <em>funkiest </em>album? Well, I don’t know about you, but Mother’s Milk was the first album that I heard from RHCP back in the day. In fact, if you’re interested, check out my video where I played all the popular bass riffs from that album:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FyBOXjaMREAo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DyBOXjaMREAo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FyBOXjaMREAo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/257e0bddba5170b7e6bf01edc9d0e541/href">https://medium.com/media/257e0bddba5170b7e6bf01edc9d0e541/href</a></iframe><p>Anyway, TF-IDF clearly helped us to gain some insights about each album. Although useful, we would love for something that would generalize and pick up an overarching theme from each album, and TF-IDF clearly cannot do that. So how about LDA?</p><p>The main problem with LDA (or feature, depending on how you look at it) is that LDA needs <em>lots </em>of data to separate topics well. In fact, <a href="http://proceedings.mlr.press/v32/tang14.pdf">this paper</a> claims the following:</p><blockquote>The number of documents plays perhaps the most important role; it is theoretically impossible to guarantee identification of topics from a small number of documents, no matter how long.</blockquote><p>Looks like our 12 albums won’t cut it. So let’s split them back into individual songs and hope for the best.</p><pre>from gensim.corpora.dictionary import Dictionary<br>import gensim</pre><pre>lda_corpus = []<br>for album in lyrics_per_album:<br> for song in album:<br> lda_corpus.append(preprocess(song))</pre><p>Sometimes it’s useful to generate various n-grams for LDA — it just works better this way. “New_York” makes more sense rather than “New” and “York”.</p><pre>bigram = gensim.models.Phrases(lda_corpus, min_count=5, threshold=100)<br>trigram = gensim.models.Phrases(bigram[lda_corpus], min_count=5, threshold=100)<br>bigram_mod = gensim.models.phrases.Phraser(bigram)<br>trigram_mod = gensim.models.phrases.Phraser(trigram)<br>lda_corpus = [trigram_mod[bigram_mod[doc]] for doc in lda_corpus]</pre><pre>dictionary = Dictionary(lda_corpus)<br>bow_corpus = [dictionary.doc2bow(text) for text in lda_corpus]</pre><p>Let’s naively assume that every album has that “overarching theme” and that LDA can separate them perfectly into topics (I know, I know). We set the num_topics to 12:</p><pre>from gensim.models.ldamulticore import LdaMulticore<br>from gensim.models import CoherenceModel</pre><pre>model = LdaMulticore(bow_corpus, num_topics=12, id2word=dictionary, workers=7, passes=10, per_word_topics=True,<br> random_state=1)<br>coherence_model = CoherenceModel(model=model, corpus=bow_corpus, texts=lda_corpus, coherence=’c_v’)<br>print(coherence_model.get_coherence())</pre><pre>0.33568880799556466</pre><p>Is it a lot? Well, let’s examine the topics themselves:</p><pre>from pprint import pprint</pre><pre>pprint(model.print_topics())</pre><pre>[(0,<br>  &#39;0.020*&quot;get&quot; + 0.017*&quot;love&quot; + 0.016*&quot;like&quot; + 0.012*&quot;take&quot; + 0.011*&quot;come&quot; + &#39;<br>  &#39;0.010*&quot;could&quot; + 0.009*&quot;another&quot; + 0.008*&quot;make&quot; + 0.007*&quot;back&quot; + 0.007*&quot;go&quot;&#39;),<br> (1,<br>  &#39;0.022*&quot;say&quot; + 0.020*&quot;know&quot; + 0.018*&quot;get&quot; + 0.017*&quot;go&quot; + 0.016*&quot;yeah&quot; + &#39;<br>  &#39;0.015*&quot;come&quot; + 0.014*&quot;hey&quot; + 0.013*&quot;want&quot; + 0.011*&quot;oh&quot; + 0.011*&quot;like&quot;&#39;),<br> (2,<br>  &#39;0.046*&quot;love&quot; + 0.014*&quot;make&quot; + 0.014*&quot;see&quot; + 0.012*&quot;around&quot; + 0.010*&quot;get&quot; + &#39;<br>  &#39;0.010*&quot;want&quot; + 0.009*&quot;know&quot; + 0.009*&quot;way&quot; + 0.008*&quot;never&quot; + 0.008*&quot;go&quot;&#39;),<br> (3,<br>  &#39;0.022*&quot;get&quot; + 0.017*&quot;know&quot; + 0.014*&quot;come&quot; + 0.013*&quot;want&quot; + 0.013*&quot;girl&quot; + &#39;<br>  &#39;0.012*&quot;go&quot; + 0.011*&quot;like&quot; + 0.009*&quot;friend&quot; + 0.008*&quot;call&quot; + 0.008*&quot;walk&quot;&#39;),<br> (4,<br>  &#39;0.054*&quot;get&quot; + 0.013*&quot;know&quot; + 0.011*&quot;give&quot; + 0.010*&quot;say&quot; + 0.010*&quot;tell&quot; + &#39;<br>  &#39;0.009*&quot;right&quot; + 0.009*&quot;one&quot; + 0.009*&quot;love&quot; + 0.009*&quot;come&quot; + 0.009*&quot;make&quot;&#39;),<br> (5,<br>  &#39;0.029*&quot;around&quot; + 0.023*&quot;look&quot; + 0.018*&quot;please&quot; + 0.011*&quot;know&quot; + 0.010*&quot;get&quot; &#39;<br>  &#39;+ 0.009*&quot;way&quot; + 0.009*&quot;never&quot; + 0.009*&quot;torture&quot; + 0.009*&quot;far&quot; + &#39;<br>  &#39;0.008*&quot;like&quot;&#39;),<br> (6,<br>  &#39;0.026*&quot;get&quot; + 0.020*&quot;turn&quot; + 0.014*&quot;well&quot; + 0.012*&quot;yeah&quot; + 0.009*&quot;yes&quot; + &#39;<br>  &#39;0.009*&quot;sale&quot; + 0.008*&quot;like&quot; + 0.008*&quot;blood&quot; + 0.008*&quot;true_men_kill_coyote&quot; &#39;<br>  &#39;+ 0.008*&quot;know&quot;&#39;),<br> (7,<br>  &#39;0.014*&quot;love&quot; + 0.013*&quot;time&quot; + 0.012*&quot;like&quot; + 0.012*&quot;oh&quot; + 0.012*&quot;get&quot; + &#39;<br>  &#39;0.011*&quot;know&quot; + 0.011*&quot;come&quot; + 0.010*&quot;go&quot; + 0.009*&quot;sing&quot; + 0.008*&quot;want&quot;&#39;),<br> (8,<br>  &#39;0.020*&quot;know&quot; + 0.017*&quot;get&quot; + 0.015*&quot;let&quot; + 0.011*&quot;time&quot; + 0.010*&quot;go&quot; + &#39;<br>  &#39;0.009*&quot;man&quot; + 0.009*&quot;like&quot; + 0.008*&quot;say&quot; + 0.008*&quot;want&quot; + 0.008*&quot;girl&quot;&#39;),<br> (9,<br>  &#39;0.020*&quot;get&quot; + 0.015*&quot;long&quot; + 0.014*&quot;make&quot; + 0.013*&quot;come&quot; + 0.012*&quot;gon_na&quot; + &#39;<br>  &#39;0.012*&quot;time&quot; + 0.009*&quot;fall&quot; + 0.009*&quot;baby&quot; + 0.009*&quot;know&quot; + 0.008*&quot;wo&quot;&#39;),<br> (10,<br>  &#39;0.028*&quot;want&quot; + 0.024*&quot;party_pussy&quot; + 0.021*&quot;yeah&quot; + 0.020*&quot;baby&quot; + &#39;<br>  &#39;0.019*&quot;good&quot; + 0.013*&quot;get&quot; + 0.011*&quot;say&quot; + 0.008*&quot;make&quot; + 0.008*&quot;take&quot; + &#39;<br>  &#39;0.007*&quot;god&quot;&#39;),<br> (11,<br>  &#39;0.029*&quot;away&quot; + 0.018*&quot;take&quot; + 0.017*&quot;like&quot; + 0.016*&quot;get&quot; + 0.015*&quot;know&quot; + &#39;<br>  &#39;0.012*&quot;make&quot; + 0.011*&quot;never&quot; + 0.009*&quot;thing&quot; + 0.008*&quot;see&quot; + 0.008*&quot;say&quot;&#39;)]</pre><p>I don’t know about you, but I cannot figure out which one is which. It’s definitely not separating them based on the albums. Rather, it’s separating them based on the songs again — take a look at topic 10 for example.</p><p>LDA has 3 main hyperparameters: <em>number of topics</em>, <em>alpha</em>, and <em>eta. </em>Let’s tune them and see if we can get something meaningful. I use <strong>skopt </strong>for hyperparameter tuning, with Bayesian optimization using Gaussian Processes. We’ll do 100 iteration and see if we can improve on that coherence score.</p><pre>from skopt.space import Real, Integer, Categorical<br>from skopt.utils import use_named_args<br>from skopt import gp_minimize</pre><pre>space = [<br> Integer(3, 20, name=”num_topics”),<br> Real(0.01, 1, name=’alpha’),<br> Real(0.01, 1, name=’eta’),<br>]</pre><pre><a href="http://twitter.com/use_named_args">@use_named_args</a>(space)<br>def objective(**params):<br> model = LdaMulticore(bow_corpus, id2word=dictionary, workers=7, passes=30, per_word_topics=True,<br> random_state=1,<br> num_topics=params[‘num_topics’],<br> alpha=params[‘alpha’],<br> eta=params[‘eta’])<br> coherence_model = CoherenceModel(model=model, corpus=bow_corpus, texts=lda_corpus, coherence=’c_v’)<br> return -coherence_model.get_coherence()</pre><pre>res_gp = gp_minimize(objective, space, n_calls=100,n_jobs=-1, verbose=True)</pre><pre>print(“Best coherence: {:.2f}”.format(res_gp.fun))<br>print(“Best parameters: {}, {:.2f}, {:.2f}”.format(res_gp.x[0], res_gp.x[1], res_gp.x[2]))</pre><pre>Best coherence: -0.58<br>Best parameters: 16, 0.85, 1.00</pre><p>Well, looks like RHCP cover more than 12 topics in their songs (duh…). Also, our coherence score went up! Let’s train the model with these parameters and visualize our results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*wfpbneMQvZ1lWRXsK-enRg.png" /></figure><p>I use t-SNE for visualization, which compresses multi-dimensional data into the required # of dimensions (in our case — 2). Each color represents a separate topic. It looks like one category dominates a lot! Let’s plot them by their frequency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*R5jNXvufTyzOgXwARFLZMw.png" /></figure><p>Category 0 and 4 are the most common. What are their corresponding words?</p><pre>(0,&#39;0.016*&quot;know&quot; + 0.016*&quot;get&quot; + 0.015*&quot;love&quot; + 0.014*&quot;like&quot; + 0.011*&quot;make&quot; + &#39;<br> &#39;0.011*&quot;want&quot; + 0.010*&quot;say&quot; + 0.010*&quot;come&quot; + 0.009*&quot;go&quot; + 0.009*&quot;take&quot;&#39;)<br>(4,&#39;0.032*&quot;get&quot; + 0.009*&quot;time&quot; + 0.008*&quot;love&quot; + 0.007*&quot;come&quot; + 0.007*&quot;give&quot; + &#39;<br> &#39;0.006*&quot;know&quot; + 0.006*&quot;good&quot; + 0.006*&quot;tell&quot; + 0.006*&quot;say&quot; + 0.005*&quot;right&quot;&#39;)</pre><p>Hmm… it still doesn’t look too different to me. May be ~190 documents is still too small of a number for LDA to separate topics. In fact, when I don’t set the random state, every time LDA generates a different set of topics, which suggest that ~190 documents is not enough for it to converge. Finally, let’s plot the topics for each album and see if we can spot any trends</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*s6dP-Z_jCvX1Z9_XRDbbEw.png" /></figure><p>Looks like early Peppers were pretty diverse in terms of their lyrics. We can see more categories for the early albums, and only 2 for their The Getaway.</p><p>Here are some other topics LDA generated:</p><pre>(11,<br> &#39;0.003*&quot;king&quot; + 0.003*&quot;minor&quot; + 0.003*&quot;repeat&quot; + 0.002*&quot;backwoods&quot; + &#39;<br> &#39;0.002*&quot;yertle_turtle&quot; + 0.002*&quot;otherside&quot; + 0.002*&quot;throw&quot; + &#39;<br> &#39;0.002*&quot;television&quot; + 0.002*&quot;turtle&quot; + &#39;<br> &#39;0.002*&quot;dream_californication_dream_californication&quot;&#39;)<br>(13,<br> &#39;0.004*&quot;blood&quot; + 0.004*&quot;well&quot; + 0.003*&quot;true_men_kill_coyote&quot; + 0.003*&quot;yeah&quot; + &#39;<br> &#39;0.002*&quot;feel&quot; + 0.002*&quot;true_men&quot; + 0.002*&quot;gon_na&quot; + 0.002*&quot;hollywood_hill&quot; + &#39;<br> &#39;0.002*&quot;dig_dirt_dig_dust&quot; + 0.002*&quot;paisley_dragon_hollywood_hill&quot;&#39;)<br>(2,<br> &#39;0.002*&quot;stretch&quot; + 0.001*&quot;love&quot; + 0.001*&quot;dirty&quot; + 0.001*&quot;stain&quot; + &#39;<br> &#39;0.001*&quot;bird&quot; + 0.001*&quot;thirty&quot; + 0.001*&quot;earthworm&quot; + 0.001*&quot;burping&quot; + &#39;<br> &#39;0.001*&quot;chirp&quot; + 0.001*&quot;curb&quot;&#39;)</pre><p>Finally, let’s check one theory. When Anthony Kiedis was discussing the recording of Stadium Arcadium album, he said the following about their hit “Dany California” (watch from 0:30):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXO06RsDf1OQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXO06RsDf1OQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXO06RsDf1OQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/68c32689b9d9adf1517aa590851f4441/href">https://medium.com/media/68c32689b9d9adf1517aa590851f4441/href</a></iframe><p>Basically, when writing “Dani California”, Anthony realized that it’s actually a continuation of a story he started earlier in “Californication” (1999) and continued in “By The Way” (2002). Let’s see if these 3 songs share any similarities in terms of lyrics!</p><pre>scat_new = scat.copy()<br>scat_new.loc[:, ‘Label’] = “None”<br>scat_new.loc[89, ‘Label’] = ‘Californication’<br>scat_new.loc[109, ‘Label’] = ‘By The Way’<br>scat_new.loc[131, ‘Label’] = ‘Dani California’</pre><pre>fig, ax = plt.subplots(figsize=(10,10))<br>ax = sns.scatterplot(data=scat_new, x=’x’, y=’y’, hue=’category’, legend=None, s=100)<br>for row in scat_new.iterrows():<br> if row[1][‘Label’] != “None”:<br> ax.text(row[1][‘x’]+.02, row[1][‘y’], str(row[1][‘Label’]))<br>ax.set(xlabel=’’, ylabel=’’)<br>plt.show()<br>plt.clf()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*FMFDJAr7Wsed70SS8qpnsQ.png" /></figure><p>They couldn’t be further apart. With that I will conclude my analysis. Please comment down below, what other techniques might have given better results. Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9b88eb7213c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>