<?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 Andrew Obando on Medium]]></title>
        <description><![CDATA[Stories by Andrew Obando on Medium]]></description>
        <link>https://medium.com/@obandoandrew8?source=rss-82bd0279dcd4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MrSPhohOMxQLmFXIZsQJrA.jpeg</url>
            <title>Stories by Andrew Obando on Medium</title>
            <link>https://medium.com/@obandoandrew8?source=rss-82bd0279dcd4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:25:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@obandoandrew8/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[How to Master Prompt Engineering Using LLMs (From Beginner to Advanced)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/how-to-master-prompt-engineering-using-llms-from-beginner-to-advanced-5702e9ef38c8?source=rss-82bd0279dcd4------2"><img src="https://cdn-images-1.medium.com/max/680/1*0OX30ciEfLhoSMqkow86cw.jpeg" width="680"></a></p><p class="medium-feed-snippet">You don&#x2019;t need to be a data scientist or a machine learning engineer&#x200A;&#x2014;&#x200A;everyone can write a prompt.</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/how-to-master-prompt-engineering-using-llms-from-beginner-to-advanced-5702e9ef38c8?source=rss-82bd0279dcd4------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/how-to-master-prompt-engineering-using-llms-from-beginner-to-advanced-5702e9ef38c8?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5702e9ef38c8</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[writing-prompts]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 01:50:38 GMT</pubDate>
            <atom:updated>2025-07-28T01:50:38.090Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Gin Rummy Theorem Vs. Bayesian Thinking — Importance of Bayes’ Theorem in ML and AI]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/gin-rummy-theorem-vs-bayesian-thinking-importance-of-bayes-theorem-in-ml-and-ai-37d581575b24?source=rss-82bd0279dcd4------2"><img src="https://cdn-images-1.medium.com/max/1280/1*moNATjuanXLNQ69nepCOzA.jpeg" width="1280"></a></p><p class="medium-feed-snippet">The absence of evidence is not the evidence of absence. This has so many implications for AI and Machine learning.</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/gin-rummy-theorem-vs-bayesian-thinking-importance-of-bayes-theorem-in-ml-and-ai-37d581575b24?source=rss-82bd0279dcd4------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/gin-rummy-theorem-vs-bayesian-thinking-importance-of-bayes-theorem-in-ml-and-ai-37d581575b24?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/37d581575b24</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[probability]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 18:47:58 GMT</pubDate>
            <atom:updated>2025-06-27T18:47:58.347Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Coachella Tweet Sentiment Analysis (Deep Learning Tutorial)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://levelup.gitconnected.com/coachella-tweet-sentiment-analysis-deep-learning-tutorial-75a351280609?source=rss-82bd0279dcd4------2"><img src="https://cdn-images-1.medium.com/max/1440/1*l14S6zpnG5PUpqGHdMIkrA.png" width="1440"></a></p><p class="medium-feed-snippet">Fine-tuning RoBERTa base model for sentiment analysis on the Coachella 2015 dataset</p><p class="medium-feed-link"><a href="https://levelup.gitconnected.com/coachella-tweet-sentiment-analysis-deep-learning-tutorial-75a351280609?source=rss-82bd0279dcd4------2">Continue reading on Level Up Coding »</a></p></div>]]></description>
            <link>https://levelup.gitconnected.com/coachella-tweet-sentiment-analysis-deep-learning-tutorial-75a351280609?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/75a351280609</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 08:14:56 GMT</pubDate>
            <atom:updated>2025-06-18T03:01:58.142Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Never Write SQL Ever Again! Vanna.ai SQL AI Assistant Tutorial]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@obandoandrew8/never-write-sql-ever-again-vanna-ai-sql-ai-assistant-tutorial-94036e870903?source=rss-82bd0279dcd4------2"><img src="https://cdn-images-1.medium.com/max/1024/1*XHdj9Lwbv5pLVaH60td13Q.jpeg" width="1024"></a></p><p class="medium-feed-snippet">So it&#x2019;s 2025 and you are still writing SQL? I feel like crying for you. Find out how Vanna can help you generate SQL from your database.</p><p class="medium-feed-link"><a href="https://medium.com/@obandoandrew8/never-write-sql-ever-again-vanna-ai-sql-ai-assistant-tutorial-94036e870903?source=rss-82bd0279dcd4------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@obandoandrew8/never-write-sql-ever-again-vanna-ai-sql-ai-assistant-tutorial-94036e870903?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/94036e870903</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[ai-assistant]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 09:38:13 GMT</pubDate>
            <atom:updated>2025-02-10T11:31:12.662Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Bell Curve Meme — Avoiding the middle with statistics.]]></title>
            <link>https://medium.com/@obandoandrew8/bell-curve-meme-avoiding-the-middle-with-statistics-6301a8f5cfa1?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6301a8f5cfa1</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[normal-distribution]]></category>
            <category><![CDATA[bell-curve]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Sun, 03 Nov 2024 16:17:08 GMT</pubDate>
            <atom:updated>2025-05-31T21:47:03.992Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bell Curve Meme — Avoiding the middle with statistics.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*ch4tuqTUw2ZGFpAWmW35-Q.jpeg" /></figure><p>Ah yes, the <strong>bell curve meme</strong>. You have probably seen a variation of this meme, and the meaning behind it is pretty self explanatory. It has become popular on the internet as a way to humorously depict differences in thinking styles or intelligence across a population.</p><p>Let’s take a look into it and see what we can learn about ourselves and the way we see the world. But first, let’s talk about normal distribution and its significance in statistics.</p><h4>Table Of Contents</h4><p>∘ <a href="#ecea">Normal Distribution</a><br> ∘ <a href="#2915">Examples of the Bell Curve</a><br>· <a href="#6693">The Midwit Meme (Bell Curve Meme)</a><br> ∘ <a href="#082b">Avoiding the middle</a><br> ∘ <a href="#8fbb">Best Midwit Memes</a><br>· <a href="#7785">Reference</a></p><h4>Normal Distribution</h4><p>The <strong>bell curve</strong>, also known as <strong>normal distribution</strong>, is a statistical concept that describes how data points of a particular variable are distributed, or spread out within a range.</p><p>There are different types of distributions in statistics, but this is probably the most used probability distribution, and is the basis for a lot of assumptions and observations we make in life.</p><p>When graphed, it forms a symmetrical, bell-shaped curve. This symmetry is the key component that tells us how data is dispersed, where most data points or instances of something are clustered around the mean(average), with rare occurrences or exceptions to the left and right ends.</p><figure><img alt="Bell Shaped Curve" src="https://cdn-images-1.medium.com/max/384/1*kuMgeKhiyVBkmCQAA4Dmfw.png" /><figcaption>Bell shaped curve (Gaussian Distribution)</figcaption></figure><p>What does this curve actually imply?</p><ul><li><strong>Center Peak</strong>: The highest point in the middle of the curve represents the <strong>mean</strong> (average) of a certain data set.</li><li><strong>Symmetry</strong>: The curve is symmetrical around the mean. This means that data points are distributed equally on either side, and the mean and median are the same.</li><li><strong>Standard Deviation</strong>: This is the spread of the data around the mean. About <strong>68%</strong> of data points fall within one standard deviation of the mean, <strong>95%</strong> fall within two standard deviations, and <strong>99.7%</strong> within three.</li></ul><h4>Examples of the Bell Curve</h4><p>Bell curves are used in many fields, including psychology, education, and finance, to represent things like test scores, or financial returns.</p><p>Most naturally occurring things in life are normally distributed, like height, weight and intelligence. Most people find themselves in the middle. Taller, bigger of smarter people on the extreme stand out just as much as shorter, slender or “dumber” people.</p><p>Even psychographic phenomena such as social class and income level are normally distributed. Most people have an average income (middle class), with the minority being really wealthy, or really poor. Take a look at this image of the wear and tear of a piece of gym equipment.</p><figure><img alt="Normal Distribution in the Gym" src="https://cdn-images-1.medium.com/max/400/1*6nOkolM2fD3rWxjBxeDADQ.jpeg" /><figcaption>Most people lifting between 40–55 Kgs. Gym bros pushing more and noobs pushing less.</figcaption></figure><p>You can literally think of anything and find some evidence of normal distribution. For example, most people take 4 years to finish a college degree. A small minority can finish in 2 or 3 years, and some may take longer: 5 to 7 years.</p><p>Here is a histogram chart showing the distribution of men’s shoe sizes in the US.</p><figure><img alt="Distribution of Men’s Shoe Sizes" src="https://cdn-images-1.medium.com/max/768/1*KsOkvPnCymz2QobZ_ajPJA.png" /><figcaption><a href="https://www.statology.org/example-of-normal-distribution/">The shoe sizes of all U.S. male reveals a bell shape with a single peak at size 10</a></figcaption></figure><h3>The Midwit Meme (Bell Curve Meme)</h3><p>This meme is specifically dealing with distribution of IQ in a population, and how people express and affirm their beliefs in certain things in life. The meme template contains a normally distributed IQ distribution curve with 3 character depictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMs06ROBVq0Q_-5xcrc__A.jpeg" /><figcaption>The “midwit” is in the middle btw. I don&#39;t know if that was pun intended.</figcaption></figure><ul><li><strong>Left Side (Low End)</strong>: This is characterized by a simple caveman creature type person with wide set eyes. This often represents “simple” or “naive” thinking, characterized by a “basic” or straightforward response in the meme.</li><li><strong>Middle</strong>: This represents conventional or average thinking, often shown as an intellectual or reasonable position that majority of people have. Here is the main point of the meme, characterized by a cartoon anon man crying his eyes out in sheer frustration like he just got treated unfairly. He needs some milk.</li><li><strong>Right Side (High End)</strong>: Depicts a return to a seemingly simple idea but with a sophisticated or enlightened twist, implying deep wisdom or insight. The character looks like a young neophyte being initiated into a secret society, wearing a brown hoodie and looking quite pleased with himself and his high IQ and philosophical stance.</li></ul><p>You can check out the history of the meme at <a href="https://knowyourmeme.com/memes/iq-bell-curve-midwit">Know Your Meme</a>, for a more in-depth breakdown.</p><p>I think that the whole idea behind the bell curve meme is to show that the solution dumb people come up with is usually the same as the solution smart people come up with. Most people are midwits because they have average IQ and see themselves as smart but are not so. The midwit in the meme is expressing a conventional belief, but also trying to actively assert said belief as accepted dogma, thus the frustrated tears.</p><p>Dumb people trust their naive intelligence and just do things, while smart people are secure within their own beliefs. People in the middle are actually insecure in their intelligence and societal position and so they end up intellectualizing everything and ignoring their instincts. It’s funny because you might recognize yourself as the midwit and laugh at yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*nRsP2cOGDue_sJGo1WmFPw.png" /><figcaption>Just learn C bro</figcaption></figure><p>The meme assumes that people of average intelligence actually miss the point of many things, which is quite dismissive. Smart people can have opinions that stupid people also have, even though the reasoning underlying the stupid and the wise opinions is very different.</p><p>The smart person has a lot of experience and knowledge, allowing them to think what they think with confidence. The stupid person just randomly stumbled upon the idea, maybe because it’s a simple one, or because they’re following their natural impulses.</p><p>The crux here is that to truly enjoy the meme, you have to assume that you’re in the smart category, which instinctively you do because no one wants to be in the middle, seething at everything instead of just enjoying things. The far left is like autistic thinking — basically taking things very literally — where you just bulldoze through life, and this is a better approach than being a midwit.</p><p>The bell curve meme is useful because it reminds us that sometimes, a wise, well-reasoned opinion can deceptively look like a stupid, superficial one. Don&#39;t take the meme too seriously. Its a meme after all, and makes erroneous assumptions. You may be a midwit if you internalise it too much haha.</p><h4>Avoiding the middle</h4><p>The meme implies that there is value in stepping away from mainstream or expected perspectives. Both ends of the curve reflect non-conformist thinking — whether it’s naive or deeply insightful, its all the same. The simplest or most unconventional ideas (found on either end of the curve) can sometimes hold surprising wisdom, while the middle, representing average or conventional thought, can feel bland or unoriginal.</p><p>If someone said something that you don&#39;t resonate with, you might think they are dumb and just dismiss them. Unless you think they are smart because other people said that they are smart (social proof), in which case you don&#39;t understand it but hold it up as an ideal to strive for. This makes you an average everyday NPC person.</p><p>If you were able to understand and accept the reasoning of smarter or wiser people, that would imply you’re smarter/wiser than you let on…</p><blockquote>“A foolish consistency is the hobgoblin of little minds, adored by little statesmen and philosophers and divines.” — Ralph Waldo Emerson</blockquote><p>Emerson believed that great individuals should not be afraid to change their minds or contradict themselves as they evolve and learn. I wonder what he would think of this meme.</p><h4>Best Midwit Memes</h4><p>Here are some of my best bell curve memes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3NXDc28nZuz83QbjT0YjKQ.jpeg" /><figcaption>Everyone thinks setting SMART goals and productivity hacks work. Just do whatever bro.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kY_XMZUzMqw0vEGgy1o_mg.jpeg" /><figcaption>Planning and strategy is important. Just don&#39;t suffer from analysis paralysis.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*fbSV4gBrUeqQoQuKNsbTDQ.jpeg" /><figcaption>Coding can be boiled down to the same simple concepts when you deep it.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*xtGDhuHtNMq7UiNkgFwMXw.png" /><figcaption>Turn off the TV and get some sleep</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8NuFfJEzRJd_a4ZJDExULg.jpeg" /><figcaption>Perhaps my best one yet. If you like dark humor, you get this one</figcaption></figure><p>When you are looking for a solution, ask yourself: “What simple idea would the idiot and the genius agree upon?”</p><h3>Reference</h3><ul><li><a href="https://www.statology.org/example-of-normal-distribution/">6 Real-Life Examples of the Normal Distribution</a></li><li><a href="https://etiennefd.substack.com/p/the-iq-bell-curve-meme">The IQ Bell Curve Meme</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=twitter&amp;url=https%3A//x.com/george__mack/status/1675251921551257601&amp;image=" width="500" height="281" frameborder="0" scrolling="no"><a href="https://medium.com/media/971c7581fbd90a7cca92ccfccda562b8/href">https://medium.com/media/971c7581fbd90a7cca92ccfccda562b8/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6301a8f5cfa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Relational Database from Excel files — MySQL Workbench]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@obandoandrew8/creating-a-relational-database-from-excel-files-mysql-workbench-3fe56164bf34?source=rss-82bd0279dcd4------2"><img src="https://cdn-images-1.medium.com/max/1280/1*B3M4-LdOZ6tIjyhBkjZqOA.jpeg" width="1280"></a></p><p class="medium-feed-snippet">You can easily create a MySQL database with your excel files in no time! Find out how</p><p class="medium-feed-link"><a href="https://medium.com/@obandoandrew8/creating-a-relational-database-from-excel-files-mysql-workbench-3fe56164bf34?source=rss-82bd0279dcd4------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@obandoandrew8/creating-a-relational-database-from-excel-files-mysql-workbench-3fe56164bf34?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fe56164bf34</guid>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[mysql-server]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[mysql-workbench]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 22:06:21 GMT</pubDate>
            <atom:updated>2025-02-07T07:23:25.827Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Deploying a ML Model with Gradio and Hugging face — Python Machine Learning]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@obandoandrew8/deploying-a-ml-model-with-gradio-and-hugging-face-python-machine-learning-83f076c58a0c?source=rss-82bd0279dcd4------2"><img src="https://cdn-images-1.medium.com/max/712/1*s99QNHmKhkDcDp-8uOHmaQ.png" width="712"></a></p><p class="medium-feed-snippet">How to build a Gradio Web App with a Machine Learning Model and put it on Hugging Face spaces</p><p class="medium-feed-link"><a href="https://medium.com/@obandoandrew8/deploying-a-ml-model-with-gradio-and-hugging-face-python-machine-learning-83f076c58a0c?source=rss-82bd0279dcd4------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@obandoandrew8/deploying-a-ml-model-with-gradio-and-hugging-face-python-machine-learning-83f076c58a0c?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f076c58a0c</guid>
            <category><![CDATA[random-forest-classifiers]]></category>
            <category><![CDATA[hugging-face-tutorials]]></category>
            <category><![CDATA[gradio]]></category>
            <category><![CDATA[classification-problem]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 22:49:23 GMT</pubDate>
            <atom:updated>2025-02-10T12:13:09.101Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building a Machine Learning API with Python, FastAPI and Docker]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@obandoandrew8/building-a-machine-learning-api-with-python-fastapi-and-docker-7281df112565?source=rss-82bd0279dcd4------2"><img src="https://cdn-images-1.medium.com/max/640/1*vmD064Mb7z0DPqa0mmZczQ.png" width="640"></a></p><p class="medium-feed-snippet">Its very easy to build web API&#x2019;s as a python programmer with Fast API. Build and deploy your machine learning model with FastAPI and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@obandoandrew8/building-a-machine-learning-api-with-python-fastapi-and-docker-7281df112565?source=rss-82bd0279dcd4------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@obandoandrew8/building-a-machine-learning-api-with-python-fastapi-and-docker-7281df112565?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7281df112565</guid>
            <category><![CDATA[dockerhub]]></category>
            <category><![CDATA[classification-models]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Tue, 06 Feb 2024 09:01:24 GMT</pubDate>
            <atom:updated>2024-11-18T06:57:43.528Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Machine Learning For Classification Problems (Customer Churn Prediction)]]></title>
            <link>https://medium.com/@obandoandrew8/machine-learning-for-classification-problems-customer-churn-prediction-ae46c574e60?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae46c574e60</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 23:54:56 GMT</pubDate>
            <atom:updated>2024-05-16T15:54:35.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a ML Classification Model with Python — Telco Customer Churn Prediction</h3><figure><img alt="Customer Churn Classification | Supervised Machine Learning" src="https://cdn-images-1.medium.com/max/844/1*NzbhdcY3aWqQeLk3G9kL_w.png" /><figcaption>Customer Churn</figcaption></figure><p>Imagine if a business could predict whether customers are likely to leave/unsubscribe to their services, and do what they can to keep them. It’s like a superpower, or being a fortune teller. You know they say its cheaper and more efficient to keep an existing customer than to obtain a new customer. In the long run, <a href="https://www.outboundengine.com/blog/customer-retention-marketing-vs-customer-acquisition-marketing/#:~:text=Acquiring%20a%20new%20customer%20can,customer%20is%205-20%25.">acquiring a new customer can cost five times more than retaining an existing customer.</a></p><blockquote>Customer churn is the loss of customers who were previously subscribed/making regular purchases or discontinue their association with your company within a specified timeframe. The churn rate says a lot about a business and its ability to retain customers, as well as being a predictor of future success.</blockquote><p>In this project, we use Supervised Machine Learning (classification) to explore the significance of churn analytics. <strong>Supervised machine learning</strong> is a type of machine learning where the algorithm learns from labeled data. <strong>Classification</strong> is a type of supervised machine learning used to predict the <strong>category</strong> or class label of a new data instance based on its input features. In classification, the target variable is <strong>categorical</strong>, meaning it takes on a finite number of discrete values or classes. Examples of classification tasks include spam detection (classifying emails as spam or not spam), sentiment analysis (classifying text as positive, negative, or neutral), and image recognition (classifying images into different categories).</p><p>The project followed the The <strong>Cr</strong>oss <strong>I</strong>ndustry <strong>S</strong>tandard <strong>P</strong>rocess for <strong>D</strong>ata <strong>M</strong>ining (<em>CRISP-DM</em>) framework that serves as the base for a <a href="https://www.datascience-pm.com/data-science-process/">data science process</a>.</p><h4>Table of Contents</h4><p><strong>· </strong><a href="#13eb"><strong>Business Understanding</strong></a><br> ∘ <a href="#749b">Primary Objective</a><br> ∘ <a href="#63ad">Hypothesis</a><br> ∘ <a href="#6f25">Analytical Questions</a><br><strong>· </strong><a href="#b9f4"><strong>Data Understanding</strong></a><br> ∘ <a href="#5f24">Issues with data</a><br> ∘ <a href="#2244">Hypothesis Testing</a><br><strong>· </strong><a href="#e5bc"><strong>Data Cleaning</strong></a><br> ∘ <a href="#ad61">Clean First Training Dataset</a><br> ∘ <a href="#5b08">Clean Second Training Dataset</a><br> ∘ <a href="#f3c1">Merge Final Training Dataset</a><br><strong>· </strong><a href="#c0a7"><strong>Exploratory Data Analysis</strong></a><br> ∘ <a href="#e600">Target Class Distribution</a><br> ∘ <a href="#ce06">Analytical Questions</a><br><strong>· </strong><a href="#e89e"><strong>Feature Engineering</strong></a><br> ∘ <a href="#8288">Feature Importance</a><br> ∘ <a href="#b212">Dataset Split</a><br> ∘ <a href="#5f88">Label Encoder</a><br> ∘ <a href="#6c1d">One-Hot Encoding</a><br> ∘ <a href="#0b4b">Feature Scaling</a><br> ∘ <a href="#7160">Train set Balancing (SMOTE Algorithm)</a><br> ∘ <a href="#57b3">Train-Test Split</a><br><strong>· </strong><a href="#7020"><strong>Modelling</strong></a><br><strong>· </strong><a href="#1dbc"><strong>Evaluation</strong></a><br> ∘ <a href="#7740">K-Fold Cross-Validation</a><br> ∘ <a href="#bc2a">Classification Report</a><br> ∘ <a href="#d18f">Hyperparameter tuning</a><br> ∘ <a href="#fc37">Randomized Search CV</a><br> ∘ <a href="#cdb4">Confusion Matrix</a><br><strong>· </strong><a href="#d0e2"><strong>References</strong></a><br><strong>· </strong><a href="#9539"><strong>Appreciation</strong></a></p><h3><strong>Business Underst</strong>anding</h3><p>The churn analytics predictive model is a data-driven solution designed to address the persistent challenge of customer churn in subscription-based industries. It can be used as a strategic tool for telecommunication companies to proactively identify potential risk factors for churn, optimize retention efforts, and cultivate lasting customer relationships.</p><p><a href="https://www.superoffice.com/blog/reduce-customer-churn/">Up to 65% of a company’s business</a> comes from existing customers. It’s no secret that repeat clients and customers drives a huge chunk of business revenue. According to <a href="https://hbswk.hbs.edu/archive/the-economics-of-e-loyalty">this Harvard Business School repor</a>t, on average, a <strong>5% increase</strong> in customer retention rates results in <strong>25% — 95% increase</strong> of profits. Customers have a lot of options and evolving preferences, therefore, accurately predicting churn has become important to retain and satisfy them.</p><p>This classification model aims to identify customers at risk of churn, enabling businesses to take proactive measures and implement targeted retention strategies.</p><h4>Primary Objective</h4><p>The objective is to create a classification model that evaluates customer data and provides insights into customer behavior, preferences, and patterns to predict the likelihood of customer churn. Model performance is assessed through metrics like accuracy, precision, recall and F1-score.</p><p>The business objective is ultimately to be able reduce customer churn rates and retain valuable customers. Armed with the model’s insights, businesses can create personalized offers, marketing campaigns, and proactive customer support initiatives, thus improving customer satisfaction and fostering loyalty.</p><h4>Hypothesis</h4><ul><li><strong>Null Hypothesis (H0)</strong>: There is no significant relationship between customer tenure and churn rate in the telecom company.</li><li><strong>Alternative Hypothesis (Ha)</strong>: There is a significant relationship between customer tenure and churn rate in the telecom company.</li></ul><h4>Analytical Questions</h4><ol><li>How does customer tenure relate to churn rates? Are long-tenured customers more likely to stay with the company, and do new customers exhibit higher churn behavior?</li><li>Is there a correlation between the total charges and churn rates? Do customers with higher total charges exhibit different churn behavior compared to those with lower total charges</li><li>What is the impact of contract type on churn rates? Do customers on long-term contracts have significantly lower churn rates compared to those on short-term contracts?</li><li>Are there significant differences in churn behavior between customers who have device protection and those who don’t?</li><li>What is the relationship between the availability of tech support and churn rates? Are customers with access to tech support more likely to remain with the company?</li><li>Do streaming services play a role in customer churn? Are customers with streaming services, such as StreamingTV and StreamingMovies, more likely to stay with the company?</li><li>How does the choice of payment method impact churn rates? Are customers with specific payment methods more prone to churn than others?</li></ol><h3>Data Understanding</h3><p>First step is to collect and analyze our data for the project, explore it and verify its quality and relevance. We install our necessary libraries/packages for the project and source our data from multiple sources, including a remote Microsoft SQL server. You can view the jupyter notebook for the project to get more detailed insights <a href="https://github.com/Azie88/ML-Classification-Customer-Churn-Prediction/blob/main/Project_notebook.ipynb">here</a>.</p><p>Our data consists of 3 datasets, two for the train and one for the test:</p><ul><li><strong>data = LP2_Telco_Churn_first_3000</strong></li><li><strong>data_xls = Telco-churn-second-2000 </strong>(our test data without the target variable)</li><li><strong>data_2=LP2_telco-churn-last-2000 for testing</strong></li></ul><pre># View columns and rows of datasets<br><br>(data.shape,data_xls.shape,data2.shape)</pre><figure><img alt="Shape of data frame (rows and columns) | Data Understanding" src="https://cdn-images-1.medium.com/max/295/1*NZQdXAB0FI2czTlNtSFbWA.png" /><figcaption>Columns and rows of the 3 datasets</figcaption></figure><p>After using the pandas.read_csv function to load our data, here is a description of our datasets:</p><figure><img alt="Data frame column descriptions and dtypes | Data Understanding" src="https://cdn-images-1.medium.com/max/618/1*8Kg5kEK6IfH_l4n6eWgNFg.png" /><figcaption>A majority of the columns in our dataset are categorical</figcaption></figure><h4><strong>Issues with data</strong></h4><ul><li>Train datasets need to be merged, however they have inconsistent data types that need to be synchronized</li><li>We need to remove the CustomerID column from the training data as it is not necessary for our analysis</li><li>Missing values need to be imputed or deleted</li><li>TotalCharges column needs to be changed to numeric dtype from object dtype</li></ul><h4>Hypothesis Testing</h4><p>We want to see if there is a relationship/correlation between tenure and churn. Since churn is a binary outcome (Yes or No), we want to use <a href="https://resources.nu.edu/statsresources/Pointbiserial"><strong>point-biserial correlation</strong></a><strong> </strong>and assess its significance using a correlation test.</p><pre># &#39;Churn&#39; should be a binary variable (0 for no churn, 1 for churn)<br>df_hypo = Data_All.copy()<br>df_hypo[&#39;Churn&#39;] = df_hypo[&#39;Churn&#39;].replace({&#39;No&#39;: 0, &#39;Yes&#39;: 1})<br><br># Calculate point-biserial correlation coefficient<br>correlation_coefficient, p_value = stats.pointbiserialr(df_hypo[&#39;Churn&#39;], df_hypo[&#39;tenure&#39;])<br><br># Print the results<br>print(f&quot;Point-Biserial Correlation Coefficient: {correlation_coefficient:.4f}&quot;)<br>print(f&quot;P-value: {p_value:.4f}&quot;)<br><br># Set the significance level (5%)<br>alpha = 0.05<br><br># Determine if the correlation is statistically significant<br>if p_value &lt; alpha:<br>    print(&quot;There is a significant correlation between customer tenure and churn rate.&quot;)<br>else:<br>    print(&quot;There is no significant correlation between customer tenure and churn rate.&quot;)</pre><figure><img alt="Point-Biserial Correlation | Data Understanding" src="https://cdn-images-1.medium.com/max/587/1*ANadC2DsuuZcpl37JUw_VA.png" /></figure><p>The correlation coefficient of -0.3526 suggests a <strong>moderate negative correlation</strong>. This means that as customer tenure increases, the churn rate tends to decrease. Customers who have been with the company for a longer period are less likely to churn. This actually makes sense if you think about it. Longer tenure means customer loyalty and retention.</p><p>The p-value is less than the significance level, which suggests that there is a strong statistical evidence to <strong>reject the null hypothesis</strong> (no correlation) in favor of the alternative hypothesis (significant correlation).</p><h3><strong>Data Cleaning</strong></h3><p>This step includes selecting, cleaning and formatting our data. It takes up about 80% of any machine learning project. Keep in mind that data cleaning is an iterative process as it involves multiple rounds of processing throughout a machine learning project.</p><h4>Clean First Training Dataset</h4><pre>data.info()</pre><figure><img alt="Data frame information (df.info) | Data Cleaning" src="https://cdn-images-1.medium.com/max/398/1*KrpuIvSWYcnMgRjbi1iWrA.png" /><figcaption>Data from our first 3000 rows</figcaption></figure><ul><li>We remove the customerID column. It serves no purpose in explaining whether or not the customer will churn, just only a unique identifier.</li></ul><pre>del data[&quot;customerID&quot;]</pre><ul><li>We convert the bool dtypes to object dtypes for easier analysis.</li></ul><pre># convert bool columns to object Dtypes<br><br>bool_to_obj = {&#39;Partner&#39;: object,<br>               &#39;SeniorCitizen&#39;: object,<br>               &#39;Dependents&#39;: object, <br>               &#39;PhoneService&#39;: object,<br>               &#39;PaperlessBilling&#39;: object}<br><br>data = data.astype(bool_to_obj)</pre><ul><li>We then format our object column values and change them (from True/False to Yes/No) for uniformity and easier legibility.</li></ul><pre># Replace True and False values with Yes and No in Object columns<br><br>replace_values = {True: &#39;Yes&#39;, False: &#39;No&#39;}<br><br># Use replace() method<br>data[&#39;Partner&#39;] = data[&#39;Partner&#39;].replace(replace_values)<br>data[&#39;SeniorCitizen&#39;] = data[&#39;SeniorCitizen&#39;].replace(replace_values)<br>data[&#39;Dependents&#39;] = data[&#39;Dependents&#39;].replace(replace_values)<br>data[&#39;PhoneService&#39;] = data[&#39;PhoneService&#39;].replace(replace_values)<br>data[&#39;MultipleLines&#39;] = data[&#39;MultipleLines&#39;].replace(replace_values)<br>data[&#39;OnlineSecurity&#39;] = data[&#39;OnlineSecurity&#39;].replace(replace_values)<br>data[&#39;OnlineBackup&#39;] = data[&#39;OnlineBackup&#39;].replace(replace_values)<br>data[&#39;DeviceProtection&#39;] = data[&#39;DeviceProtection&#39;].replace(replace_values)<br>data[&#39;TechSupport&#39;] = data[&#39;TechSupport&#39;].replace(replace_values)<br>data[&#39;StreamingTV&#39;] = data[&#39;StreamingTV&#39;].replace(replace_values)<br>data[&#39;StreamingMovies&#39;] = data[&#39;StreamingMovies&#39;].replace(replace_values)<br>data[&#39;PaperlessBilling&#39;] = data[&#39;PaperlessBilling&#39;].replace(replace_values)<br>data[&#39;Churn&#39;] = data[&#39;Churn&#39;].replace(replace_values)</pre><ul><li>We have one missing value in our target variable Churn which we drop. The missing values in TotalCharges have a tenure of 0, even though there are values in the MonthlyCharges column. A customer with a tenure of 0 and 0 total charges should not have any monthly charges. We can simply drop those rows (5) to avoid confusion.</li></ul><pre># Drop rows where tenure = 0<br><br>data.drop(labels=data[data[&#39;tenure&#39;] == 0].index, axis=0, inplace=True)</pre><ul><li>For the rest of our missing categorical values, we replace them with the mode of their respective columns.</li></ul><pre># replace the remaining missing values with the mode of their respective columns<br><br>columns_to_replace = [&#39;MultipleLines&#39;, &#39;OnlineSecurity&#39;, &#39;OnlineBackup&#39;,<br>           &#39;DeviceProtection&#39;, &#39;TechSupport&#39;, &#39;StreamingTV&#39;,<br>           &#39;StreamingMovies&#39;]<br><br>for column in columns_to_replace:<br>    data[column].fillna(data[column].mode()[0], inplace=True)</pre><p>Our data frame looks a little better now.</p><pre># Reset index after dropping rows<br><br>data.reset_index(drop=True, inplace=True)<br><br>data.info()</pre><figure><img alt="Cleaned data frame with no null values | Data Cleaning" src="https://cdn-images-1.medium.com/max/376/1*DH-4u2dq_x4rCmRvBBoWpA.png" /><figcaption>First 3000 rows after cleaning</figcaption></figure><h4>Clean Second Training Dataset</h4><pre>data2.info()</pre><figure><img alt="Pandas df.info method | Data Cleaning" src="https://cdn-images-1.medium.com/max/373/1*bdz87T9w6-7zJadoukFvXA.png" /><figcaption>Data from last 2000 rows</figcaption></figure><ul><li>The customerID column gets dropped, and the TotalCharges column gets converted to numeric data type.</li></ul><pre># change Dtype of TotalCharges column from object to numeric<br><br>data2[&#39;TotalCharges&#39;] = pd.to_numeric(data2[&#39;TotalCharges&#39;], errors=&#39;coerce&#39;)</pre><p>After applying the transformation, the TotalCharges column has some missing values (3) which we drop just like we did in our first training dataset, since they have a tenure of 0.</p><h4>Merge Final Training Dataset</h4><p>We merge our 2 cleaned datasets together.</p><pre>Data_All= pd.concat([data, data2], ignore_index=True)<br>Data_All.describe(include=[&#39;object&#39;]).T</pre><figure><img alt="Pandas .describe method | Data Cleaning" src="https://cdn-images-1.medium.com/max/407/1*axFZ9J4_V4l8_bn1D0MeFA.png" /><figcaption>Final Train Dataset</figcaption></figure><h3>Exploratory Data Analysis</h3><p>Let’s explore and visualize the data to gain some insights and answer our analytical questions.</p><h4>Target Class Distribution</h4><figure><img alt="Donut Chart of Churn Distribution | Exploratory Data Analysis" src="https://cdn-images-1.medium.com/max/474/1*XYVx1t1DhiKWPYnOcxUigQ.png" /><figcaption>Churn Distribution</figcaption></figure><ul><li>The target variable (Churn) in our data is <strong>imbalanced</strong>. This means that that one class is more than the other. We will have to <strong>balance the the target classes</strong> so that our model does not give biased predictions in favor of the majority class (not churned).</li><li>The percentage of customers that did not churn (majority class) can be used as a baseline to evaluate the quality of the our model. The model should similarly, or even outperform the baseline capabilities to be considered for future predictions.</li></ul><h4>Analytical Questions</h4><p><strong>1. How does customer tenure relate to churn rates?</strong></p><figure><img alt="KDE Plot of churn and tenure | Exploratory Data Analysis" src="https://cdn-images-1.medium.com/max/704/1*_i87ra7qB2BKQvyCi13v1w.png" /><figcaption>KDE Plot of Churn by Tenure</figcaption></figure><ul><li>From our hypothesis test, we have already gathered that there is a negative correlation between tenure and churn. The probability density plot shows us that customers with a lower tenure are more likely to churn. As the length of tenure increases, customers who have stayed for longer are less likely to churn.</li></ul><p><strong>2. Is there a correlation between the total charges and churn rates?</strong></p><figure><img alt="lmplot for total charges by churn | Exploratory Data Analysis" src="https://cdn-images-1.medium.com/max/490/1*djk4MU7WtxM9x4yxXkITEQ.png" /><figcaption>lmplot for total charges by churn</figcaption></figure><ul><li>The weak downward slope on the <a href="https://seaborn.pydata.org/generated/seaborn.lmplot.html"><strong>lmplot</strong></a>, which helps us plot a logistic regression line on a scatterplot, suggests that there is a <strong>weak negative correlation </strong>between total charges and churn rates. The more a customer has spent with the company, the likelihood of churn slightly decreases.</li></ul><p><strong>3. What is the impact of contract type on churn rates?</strong></p><figure><img alt="Stacked Bar chart of churn by contract duration | Exploratory Data Analysis" src="https://cdn-images-1.medium.com/max/545/1*ahjcyveV_UQqPLxYUZfmCg.png" /><figcaption>Stacked bar chart of Churn by Contract Duration</figcaption></figure><ul><li>Customers with short term (month-to-month) contracts have higher churn rates than customers with long term (one year+ contracts)</li></ul><p><strong>4. Are there significant differences in churn behavior between customers who have device protection and those who don’t?</strong></p><figure><img alt="Percentage Stacked Bar plot of churn by device protection | Exploratory Data Analysis" src="https://cdn-images-1.medium.com/max/537/1*omlPoz5TTsJMUqt7wy89Ag.png" /><figcaption>Percentage Stacked Bar plot of churn by device protection</figcaption></figure><ul><li>Customers without device protection are slightly more likely to churn, although this metric is not clear or significant enough.</li></ul><p><strong>5. What is the relationship between the availability of tech support and churn rates?</strong></p><figure><img alt="Stacked Bar chart of churn by tech support | Exploratory Data Analysis" src="https://cdn-images-1.medium.com/max/545/1*Qr4RVcBFSkwDbdqFWRha7Q.png" /><figcaption>Stacked Bar chart of churn by tech support</figcaption></figure><ul><li>Customers with no tech support were more likely to churn.</li></ul><p><strong>6. Do streaming services play a role in customer churn?</strong></p><figure><img alt="Subplot Stacked Bar chart of churn by Streaming Services | Exploratory Data Analysis" src="https://cdn-images-1.medium.com/max/1024/1*cwd6dme_c126R_WlG1U9kg.png" /><figcaption>Subplot Stacked Bar chart of churn by Streaming Services</figcaption></figure><ul><li>No significant relationship between streaming services and churn rates.</li></ul><p><strong>7. How does the choice of payment method impact churn rates?</strong></p><figure><img alt="Stacked Bar chart of churn by payment method | Exploratory Data Analysis" src="https://cdn-images-1.medium.com/max/862/1*x5y0f9wvswO-77bm4t_wDw.png" /><figcaption>Stacked Bar chart of churn by payment method</figcaption></figure><ul><li>Customers who pay by electronic check were more likely to churn, compared to other payment methods.</li></ul><h3>Feature Engineering</h3><p>Feature engineering is an important part of machine learning, where we remove and/or add features in our dataset, and also transform our data into acceptable forms that can be passed through a ML model. A lot of ML models need numerical values as inputs, which means that categorical values have to be converted.</p><h4>Feature Importance</h4><p>We have already explored some relationships between our variables and target variable with our EDA. Now we want to identify which categorical features are more informative in relation to the target variable, making them potentially valuable for predicting or understanding the Churn behavior.</p><blockquote>In machine learning, feature importance helps us in selecting the most relevant features for training our model. By focusing on the most important features, unnecessary noise and redundancy can be eliminated, leading to a simpler, more efficient and more accurate model. One way to do that is to get <strong>Mutual Information Scores.</strong></blockquote><p><strong>Mutual Information</strong> is a measure of the dependence between two variables, which quantifies how much knowing the value of one variable reduces uncertainty about the other variable. Pearson’s correlation coefficient gives us correlation between linear relationships. Mutual information detects both linear and non-linear relationships</p><p>So in essence, a higher score means that the feature is good at predicting the target variable, and a lower score suggests that the variable is not that helpful in predicting the dependent variable. Let’s get the mutual information scores of our categorical features, in relation to our target variable (churn).</p><pre># Lets find out feature dependency on the target variable using mutual information score<br><br>x_cat = Data_All.select_dtypes(include=object).drop(&#39;Churn&#39;, axis=1)<br>y_cat = Data_All[&#39;Churn&#39;]<br><br>mi_scores = []<br><br>#  loop to calculate the Mutual Information Score for each categorical feature <br>#  with respect to the &#39;Churn&#39; target variable<br><br>for column in x_cat.columns:<br>    mi_score = mutual_info_score(x_cat[column], y_cat)<br>    mi_scores.append((column, mi_score))<br><br># sort features by their importance dependency on the target variable, <br># with the most important ones at the top.<br><br>mi_scores.sort(key=lambda x: x[1], reverse=True)<br><br>for feature, score in mi_scores:<br>    print(f&quot;{feature} - {score}&quot;)</pre><figure><img alt="List of Mutual Information Scores | Feature Importance" src="https://cdn-images-1.medium.com/max/315/1*_IRTGVNFafiWWEtNpvUdtw.png" /><figcaption>List of Mutual Information Scores</figcaption></figure><p>This gives us a list of our categorical features and their scores in descending order. Instead of reading a list of numbers, its always good to visualize.</p><figure><img alt="Plotly barplot of mutual information scores | Feature Importance" src="https://cdn-images-1.medium.com/max/700/1*fj9oTp8ssV7B1eeSeMJC2g.png" /><figcaption>Horizontal Bar Plot of Mutual Information Scores</figcaption></figure><ul><li>Contract has the highest mutual score. We saw in our earlier visualizations too that the contract type has a strong relationship with churn probability. Internet Service and payment method also have high mutual scores. The type of internet service and preferred payment method a customer has may be strongly related to churn.</li><li>The gender , phoneservice and multiplelines variables have a very low mutual score. This suggests that they have little to no predictive power or relationship with the target variable. I decided to delete them from the data frame as they may add unnecessary noise which may affect the model performance.</li></ul><h4>Dataset Split</h4><p>We separate the independent variable(y) from the dependent variables(X), since we are using X to predict y.</p><pre>X = df_encode.drop(columns=[&#39;Churn&#39;])<br>y = df_encode[&#39;Churn&#39;]</pre><h4>Label Encoder</h4><p>The target variable is then transformed to numerical values with <strong>label encoder</strong>. Label Encoding is a technique used in machine learning to transform categorical data into numerical format, specifically integers. Label encoding assigns integer labels sequentially <strong>without considering any order among categories. </strong>It is normally used to transform target values (y), not the input (X).</p><pre># Encode the target variable (Churn) to have 0 or 1 instead of No or Yes<br><br>labelEncoder = LabelEncoder()<br><br>y = labelEncoder.fit_transform(y)</pre><p>The result is a single column with integer-encoded values.</p><h4><strong>One-Hot Encoding</strong></h4><p>When we have 3 or more options for a discrete variable, like we do for some of our categorical columns, we can use the <strong>one-hot encoder</strong> to transform the categorical data to numerical data. This will create new columns for each option in a variable.</p><p>If we use label encoding for columns with 3 or more options to assign each option with a random number (e.g. 0,1,2), some machine learning models can treat<strong> the order of the numbers</strong> as if they are significant and this can cause problems. So we use the one-hot encoder.</p><p>Some of my categorical variables only have 2 options, but i still used the one-hot encoder across them for uniformity.</p><pre># One hot encoding for categorical columns<br><br>categorical_columns = [&#39;SeniorCitizen&#39;, &#39;Partner&#39;, &#39;Dependents&#39;,<br>                       &#39;InternetService&#39;, &#39;OnlineSecurity&#39;, &#39;OnlineBackup&#39;, &#39;DeviceProtection&#39;, <br>                       &#39;TechSupport&#39;, &#39;StreamingTV&#39;, &#39;StreamingMovies&#39;, &#39;Contract&#39;, <br>                       &#39;PaperlessBilling&#39;, &#39;PaymentMethod&#39;]<br><br># Create column transformer instance<br>transformer = make_column_transformer(<br>    (OneHotEncoder(sparse=False), categorical_columns)<br>)<br><br>transformed_data = transformer.fit_transform(X[categorical_columns])<br><br># Transformating back to a dataframe<br>transformed_df = pd.DataFrame(transformed_data, columns=transformer.get_feature_names_out())<br><br># One-hot encoding removed an index. Let&#39;s put it back<br>transformed_df.index = X.index<br><br># Joining tables<br>encoded_df = pd.concat([X, transformed_df], axis=1)<br><br># Dropping original categorical columns<br>encoded_df.drop(categorical_columns, axis=1, inplace=True)</pre><p>This code transforms the categorical columns in the list into numerical values, changes the result back into a data frame, merges this data frame into our original data frame, and deletes the original categories.</p><p>Remember this creates a new column for each option. Each column has a value of 1 where that option was true, and 0 where that option was false.</p><figure><img alt="Snippet of Data Frame after One-Hot Encoding | Feature Engineering" src="https://cdn-images-1.medium.com/max/574/1*b5nBuFZkA04uQgASNOR2Tw.png" /><figcaption>Snippet of Data Frame after One-Hot Encoding</figcaption></figure><p>The issue with one-hot encoding is how it increases the <strong>dimensionality</strong> of the dataset by adding new columns. This can be a problem if you have many unique categories. Increasing the number of features will make your model more complex, leading to <strong>overfitting</strong> ,<strong> longer training times</strong> or poor performance.</p><p>One-hot encoding can also introduce <strong>multicollinearity</strong> among the encoded features, where some features are highly correlated with each other. This can affect the stability and interpretability of the model, particularly in linear models. Always keep this in mind. In our case, we don’t have too many categories, so this should be fine.</p><h4>Feature Scaling</h4><p>We also have to do some transformations on our numerical columns. Feature scaling ensures that all numerical features are on a similar scale, also called <strong>normalization. </strong>This is important because many machine learning algorithms, such as gradient descent-based algorithms or distance-based algorithms like the k-nearest neighbors (KNN) are <strong>sensitive to the scale of features</strong>. Features with larger scales may dominate those with smaller scales during model training, leading to biased results. It can also lead to <strong>improved model performance</strong> by reducing the impact of varying feature scales on the model’s predictions.</p><p>We will use the standardscaler which scales the features such that they have a mean of 0 and a standard deviation of 1. This makes our model less sensitive to outliers in the data. This is also called <strong>standardization.</strong></p><pre># standardization for numeric values<br><br>cols = [&#39;tenure&#39;, &#39;MonthlyCharges&#39;, &#39;TotalCharges&#39;]<br><br>scaler = StandardScaler()<br><br>encoded_scaled = scaler.fit_transform(encoded_df[cols])<br><br># Create new DataFrames with the scaled values<br>X_scaled_df = pd.DataFrame(encoded_scaled, columns=cols, index=X.index)<br><br># Drop the original unscaled columns<br>encoded_df.drop(cols, axis=1, inplace=True)<br><br># Concatenate the scaled columns with the original DataFrames<br>encoded_df = pd.concat([encoded_df, X_scaled_df], axis=1)[p</pre><p>This code makes our numerical columns standardized, put in a new data frame, drops the original unscaled columns, and then concatenates the scaled columns with the original data frame.</p><h4><strong>Train set Balancing (SMOTE Algorithm)</strong></h4><p><strong>SMOTE (Synthetic Minority Over-sampling Technique)</strong> is a method used to address class imbalance in a <strong>binary classification problem</strong>.</p><p>Earlier we realized that our target variable has a class imbalance. One class <strong>(the minority class) </strong>has significantly fewer instances than the other class <strong>(the majority class)</strong>. This imbalance can negatively impact the performance of machine learning models, as they might become biased toward the majority class.</p><p>SMOTE will aim to balance the class distribution by generating synthetic samples until the minority class has the same number of instances as the majority class. By creating synthetic samples, SMOTE helps the model better capture the patterns in the minority class and prevents it from favoring the majority class due to the imbalance.</p><pre># apply SMOTE to the training data (oversampling)<br><br>smote = SMOTE(random_state=42, k_neighbors=5, sampling_strategy=&#39;auto&#39;)<br><br>X_resampled, y_resampled = smote.fit_resample(encoded_df, y)</pre><p>Let’s draw a bar graph showing the original distribution and the balanced distribution.</p><figure><img alt="Bar graph with two subplots showing target distribution before and after balancing | SMOTE Balancing" src="https://cdn-images-1.medium.com/max/583/1*ndNBKa6cmGcSfxuysM7edw.png" /><figcaption>Before and after balancing target variable</figcaption></figure><h4>Train-Test Split</h4><p>We can now split our data into training and evaluation sets. By splitting the dataset into separate training and testing subsets, we can train the model on one subset (training set) and evaluate its performance on the other subset (evaluation set). This allows us to assess how well the model generalizes to new, unseen data. The evaluation set will be 20% of the training data. This is common practice in machine learning.</p><pre># Split the data into training and testing sets<br><br>X_train, X_test, y_train, y_test = train_test_split(X_resampled, y_resampled, test_size=0.2, random_state=42, stratify=y_resampled)</pre><h3>Modelling</h3><p>Now for the fun part. We can now train different models and choose the best performing model. It’s important to test different models because different models have different strengths and weaknesses, so testing them on the same data allows you to assess which model provides the most accurate predictions or best generalizes to unseen data.</p><p>We will be testing 6 different models:</p><ul><li><strong>Logistic Regression</strong></li><li><strong>K-Neighbors Classifier</strong></li><li><strong>Random Forest Classifier</strong></li><li><strong>Support Vector Classifier</strong></li><li><strong>Gradient Boosting Classifier</strong></li><li><strong>XGBoost Classifier</strong></li></ul><p>The steps are the same for each. We declare an instance of the model and then fit the model with our training data. Here is an example, with the Gradient Boosting Classifier:</p><pre>gb = GradientBoostingClassifier(random_state=42)<br><br># Train the model<br>gb.fit(X_train, y_train)</pre><p>We can now assess the performance of the models.</p><h3>Evaluation</h3><h4><strong>K-Fold Cross-Validation</strong></h4><p><strong>K-fold cross-validation</strong> estimates the performance on our models across multiple subsets of the data <strong>(k-folds)</strong>, providing a comprehensive evaluation of their generalization ability. The model is trained and evaluated k times, with <strong>each fold serving as the validation set</strong> once. This process helps estimate how well a model will perform on new, unseen data and provides insights into its stability and consistency.</p><pre># Create a dataframe with the K-fold Cross-Validation results<br><br>models = [<br>    (&#39;Logistic Regression&#39;, LR),<br>    (&#39;K nearest neighbors&#39;, knn),<br>    (&#39;Random Forest&#39;, rfm),<br>    (&#39;SVC&#39;, svm),<br>    (&#39;Gradient Boosting&#39;, gb),<br>    (&#39;XGBoost&#39;, xgb)<br>]<br><br># number of k-folds<br>k = 5<br><br>results = []<br><br>for name, model in models:<br>    kf = KFold(n_splits=k, shuffle=True, random_state=42)  # Create a KFold object<br>    scores = cross_val_score(model, X_train, y_train, cv=kf, scoring=&#39;accuracy&#39;)<br><br>    # Append results to the list<br>    results.append((name, scores.mean(), scores.std()))<br><br>results_df = pd.DataFrame(results, columns=[&#39;Model&#39;, &#39;Mean Accuracy&#39;, &#39;Std Deviation&#39;])<br><br>results_df.sort_values(by=&#39;Mean Accuracy&#39;, ascending=False)</pre><figure><img alt="K-Fold Cross-Validation Scores | Machine Learning Model Evaluation" src="https://cdn-images-1.medium.com/max/388/1*ehLUE279HnsZMTfr35Cm6g.png" /><figcaption>K-Fold Cross-Validation Scores</figcaption></figure><ul><li><strong>Average Accuracy</strong> is the mean across all k folds during the cross-validation process. <strong>Higher mean accuracy</strong> values indicate <strong>better predictive performance</strong>.</li><li><strong>Standard Deviation</strong> measures the variability or spread of accuracy values across the k folds. A lower standard deviation suggests that the model’s performance is consistent across different subsets of the data (folds), while a higher standard deviation indicates that the model’s performance varies more widely. Smaller standard deviations are generally desirable because they indicate a more stable model.</li></ul><p>The <strong>Random Forest</strong> model has the highest mean accuracy (0.846180) <strong>85%</strong> among the evaluated models. This means that, on average, the model correctly predicted the target variable for about 85% of the data points in each fold. It performs well on average across different folds, and it has a relatively low standard deviation (0.007953), indicating consistent performance.</p><h4><strong>Classification Report</strong></h4><p>A classification report is a summary of the performance of a classification model, providing various evaluation metrics for each class in the dataset. It is commonly used in assessing classification models, hence the name.</p><pre>model_names = [&#39;Logistic Regression&#39;, &#39;k-NN&#39;, &#39;Random Forest&#39;, &#39;SVM&#39;, &#39;Gradient Boosting&#39;, &#39;XGBoost&#39;]<br>models = [LR, knn, rfm, svm, gb, xgb] # our trained models<br>model_names_list = []<br>accuracy_scores = []<br>precision_scores = []<br>recall_scores = []<br>f1_scores = []<br><br># Loop through each model to calculate metrics and store information<br>for name, model in zip(model_names, models):<br>    # Make predictions on the test data<br>    y_pred = model.predict(X_test)<br>    <br>    # Calculate accuracy, precision, recall, and F1-score<br>    accuracy = accuracy_score(y_test, y_pred)<br>    precision = precision_score(y_test, y_pred)<br>    recall = recall_score(y_test, y_pred)<br>    f1 = f1_score(y_test, y_pred)<br>    <br>    # Store model name and metrics<br>    model_names_list.append(name)<br>    accuracy_scores.append(accuracy)<br>    precision_scores.append(precision)<br>    recall_scores.append(recall)<br>    f1_scores.append(f1)<br><br># Create a DataFrame with the calculated metrics<br>metrics_df = pd.DataFrame({<br>    &#39;Model&#39;: model_names_list,<br>    &#39;Accuracy&#39;: accuracy_scores,<br>    &#39;Precision&#39;: precision_scores,<br>    &#39;Recall&#39;: recall_scores,<br>    &#39;F1-Score&#39;: f1_scores<br>})<br><br># Display the DataFrame<br>metrics_df.sort_values(by=&#39;Accuracy&#39;, ascending=False)</pre><figure><img alt="Classification Report of classification models | Machine Learning Model Evaluation" src="https://cdn-images-1.medium.com/max/462/1*jBuxX7xdqRaV_xitxmvdAg.png" /><figcaption>Classification Report</figcaption></figure><ul><li><strong>Accuracy</strong>: Accuracy measures the proportion of correctly predicted instances out of the total instances in the dataset. It is an important metric for classification tasks. Our XGBoost model has the highest accuracy <strong>(0.852)</strong>. This means that around <strong>85%</strong> of the predictions made by the Random Forest model were correct. Since our data is balanced, we want to use the accuracy score as our main evaluation metric.</li></ul><blockquote>With balanced data, there is less risk of a classification model being biased towards one class due to class imbalance. As a result, accuracy effectively captures the model’s ability to correctly classify instances from both classes equally. When the classes are balanced, a high accuracy score indicates that the model is performing well across both classes and is making accurate predictions overall.</blockquote><ul><li><strong>Precision</strong>: Precision quantifies how many of the positive predictions made by the model were actually correct. It’s the ratio of true positives (correctly predicted positives) to the total number of instances predicted as positive. A higher precision indicates fewer false positives. In the XGBoost model, the precision is approximately <strong>(0.8487)</strong> meaning that about <strong>85%</strong> of the positive predictions made by the model were accurate.</li><li><strong>Recall</strong>: Recall, also known as <strong><em>sensitivity</em></strong> or true positive rate, measures the proportion of actual positive instances that were correctly predicted by the model. It’s the ratio of true positives to the total number of actual positives. A higher recall indicates fewer false negatives. In the XGBoost model, the recall is approximately <strong>0.8567</strong>, indicating that about <strong>86%</strong> of the actual positive instances were correctly identified by the model.</li><li><strong>F1-Score</strong>: The F1-Score is the harmonic mean of precision and recall. It combines both precision and recall into a single metric. The F1-Score gives us a balanced measure of a model’s performance, considering both false positives and false negatives. In the XGBoost model, the F1-Score is approximately <strong>0.8527</strong>, which takes into account both precision and recall.</li></ul><p>Our top 3 models (Random Forest, XGBoost and Gradient Boosting) are all tree based models, specifically ensemble learning techniques that combine multiple individual trees to improve overall performance and robustness. They reduce overfitting by averaging or boosting the individual trees’ predictions. They offer a combination of powerful features that make them robust, accurate, and versatile for classification tasks across a wide range of domains and data characteristics.</p><h4><strong>Hyperparameter tuning</strong></h4><p>Machine learning models are parameterized such that there has to be a search for the combination of parameters that will result in the optimal performance of the model. The parameters that define the model architecture are referred to as <strong>hyperparameters</strong> while the process of exploring a range of values is called <strong>hyperparameter tuning</strong>. It is important to note the distinction between model parameters and hyperparameters. Unlike hyperparameters, model parameters are learnt during the training phase while setting hyperparameters is exclusive of the training process. Ideally, when hyperparameter tuning is completed, the result is the best parameters for the model. Grid search and random search are two common strategies for tuning hyperparameters.</p><p>Currently, our models have been trained with the default parameters that it comes with. The parameters control aspects of the model’s learning process and can significantly impact its performance. Before we choose a final model, we have to tune the hyperparameters of our best performing models to see if we can improve the accuracy of our models, and then choosing the best.</p><p>In our example, I will Fine-tune our top 3 models using a RandomizedSearchCV method found in the sklearn.model_selection module to find the best hyperparameters and achieve the maximum performance of each of the Top 3 models, then compare them again to select the best one.</p><h4><strong>Randomized Search CV</strong></h4><p><strong>RandomizedSearchCV</strong> is a technique used for hyperparameter tuning in machine learning models. It is a variant of the more traditional <strong>GridSearchCV</strong> method, which exhaustively searches through a specified subset of hyperparameter combinations. RandomizedSearchCV, on the other hand, performs a <strong>randomized search</strong> over a specified hyperparameter space.</p><p>The main reason to use a randomized search over a grid search is because RandomizedSearchCV is computationally more efficient (takes less time and resources) compared to GridSearchCV, especially when the hyperparameter space is large. By randomly sampling a subset of configurations, it can explore a wider range of hyperparameter values with fewer total evaluations.</p><p>After tuning the top 3 models, the best model was the <strong>random forest classifier</strong>.<strong> </strong>I will only be showing the tuning process for this model.</p><p>First it’s a good idea to look at the current parameters of the model.</p><pre># Check current model parameters<br><br>current_params = rfm.get_params()<br>current_params</pre><figure><img alt="Default Model Parameters | Random Forest Classifier | Hyperparameter Tuning" src="https://cdn-images-1.medium.com/max/268/1*04gQw9BJxNISe3m1FLR8GA.png" /><figcaption>Default Model Parameters (Random Forest Classifier)</figcaption></figure><p>These are the current parameters for our model. Every model has different parameters. From a first glance it looks like some complex scientific gibberish, and you would be right. It does take some experience and study to understand the meaning and effects of the different hyperparameters.</p><p>For our random search, we will pick a grid of hyperparameters, and random combinations of them will be sampled.</p><pre># Define the parameter distributions for hyperparameter tuning<br>param_grid = {<br>  &#39;n_estimators&#39;: [20, 50, 100, 200, 300],<br>  &#39;max_depth&#39;: [None, 10, 15, 20, 25],<br>  &#39;min_samples_split&#39;: [2, 3, 4, 5, 6],<br>  &#39;min_samples_leaf&#39;: [1, 2, 3, 4, 5],<br>  &#39;class_weight&#39;: [&#39;balanced&#39;, None],<br>  &#39;max_features&#39;: [&#39;auto&#39;, &#39;sqrt&#39;, &#39;log2&#39;],<br>  &#39;criterion&#39;: [&#39;gini&#39;, &#39;entropy&#39;]<br>}<br><br># Initialize RandomizedSearchCV with the RandomForestClassifier model and parameter distributions<br>random_search_rf = RandomizedSearchCV(estimator=rfm, param_distributions=param_grid, <br>                                      scoring=&#39;accuracy&#39;, n_iter=150, random_state=42,<br>                                      cv=5, n_jobs=-1, verbose = 1)<br><br># fit best estimator on train data<br>random_search_rf.fit(X_train, y_train)<br><br># best parameters<br>best_params = random_search_rf.best_params_<br><br>best_params</pre><p>This code tunes the hyperparameters of our model in the paramgrid using RandomizedSearchCV to find the combination that maximizes accuracy on our dataset. Our hyperparameters for the random forest classifier are defined below:</p><ul><li>n_estimators: Number of trees in the forest.</li><li>max_depth: Maximum depth of the trees.</li><li>min_samples_split: Minimum number of samples required to split an internal node.</li><li>min_samples_leaf: Minimum number of samples required to be at a leaf node.</li><li>class_weight: Weights associated with classes in the form of a dictionary or &quot;balanced&quot; to automatically adjust weights inversely proportional to class frequencies.</li><li>max_features: Number of features to consider when looking for the best split.</li><li>criterion: Function to measure the quality of a split (&#39;gini&#39; or &#39;entropy&#39;).</li></ul><p>We also get an output of the best parameters.</p><figure><img alt="RandomizedSearchCV best parameters for Random Forest Classifier | Hyperparameter Tuning" src="https://cdn-images-1.medium.com/max/218/1*ThRqfofrb9qeKnntvuHZ5w.png" /><figcaption>RandomizedSearchCV best parameters</figcaption></figure><p>We can go ahead and get a classification report of our tuned model with the best parameters after fitting it with our train data and predicting with our test data and compare it with our original model.</p><figure><img alt="RandomizedSearchCV tuning Random Forest Classifier | Hyperparameter Tuning" src="https://cdn-images-1.medium.com/max/552/1*D4mmwzt-T2EKK3lyMaYccA.png" /><figcaption>Before and after hyperparameter tuning</figcaption></figure><p>Our model has improved by every metric. Our accuracy has improved slightly to <strong>86%. </strong>This is fair enough. Let’s look at a confusion matrix to see its performance a little closer.</p><h4>Confusion Matrix</h4><p>It is an N x N matrix that gives a summary of the correct and incorrect predicted classification results for the Ntarget classes. The values in the diagonal of the matrix represent the number of correctly predicted classes while every other cell in the matrix indicates the misclassified classes. This means that the more predicted values that fall in the diagonal, the better the model. True positive, false positive, true negative and false negative are terms used when interpreting a confusion matrix.</p><pre># construct the confusion matrix for tuned model<br>confusion_matrix_rf = confusion_matrix(y_test, random_search_rf_pred)<br><br>plt.figure(figsize=(6, 6))<br>sns.heatmap(confusion_matrix_rf, annot=True, fmt=&#39;d&#39;, cmap=&#39;Blues&#39;, cbar=False,<br>            xticklabels=[&#39;Churn&#39;, &#39;No Churn&#39;],<br>            yticklabels=[&#39;Churn&#39;, &#39;No Churn&#39;])<br>plt.xlabel(&#39;Actual&#39;)<br>plt.ylabel(&#39;Predicted&#39;)<br>plt.title(&#39;Confusion Matrix&#39;)<br>plt.show()</pre><figure><img alt="Tuned Random Forest Classifier model confusion matrix | Model Evaluation" src="https://cdn-images-1.medium.com/max/532/1*xb-YGmhBxJHloEOJcVHXBQ.png" /><figcaption>Tuned model confusion matrix</figcaption></figure><ul><li>The top-left value <strong>(630) </strong>represents the number of instances that were correctly classified as positive(often referred to as <strong>True Positives </strong>or TP).</li><li>The top-right value <strong>(110)</strong> represents the number of instances that were predicted a positive class while the actual class is negative (<strong>False Positives</strong> or FP). This is also called a Type I error.</li><li>The bottom-left value <strong>(97)</strong> represents the number of instances where the predicted value is negative and the actual value is positive (<strong>False Negatives </strong>or FN). This is also known as a Type II error.</li><li>The bottom-right value <strong>(643)</strong> represents the number of instances that were correctly classified as belonging to the negative class (<strong>True Negatives</strong> or TN).</li></ul><p>We can now save our tuned model and use it to make predictions on unseen data.</p><pre>destination = &quot;Toolkit&quot;<br><br>#create a directory if it doesn&#39;t exist<br>if not os.path.exists(destination):<br>    os.makedirs(destination)<br><br>#Create a dictionary  to store the object and their filename<br>models ={<br>    &quot;model&quot;:tuned_rf_model,<br>}<br><br>#Loop through the model and save using joblib.dump()<br>for name,model in models.items():<br>    file_path =os.path.join(destination,f&quot;{name}.joblib&quot;)<br>    joblib.dump(model,file_path)</pre><p>And thats it, we have successfully trained, tuned and saved a classification model 🙌</p><h3>References</h3><ul><li><a href="https://towardsdatascience.com/end-to-end-machine-learning-project-telco-customer-churn-90744a8df97d">End-to-end machine learning project: Telco customer churn</a></li><li><a href="https://www.kaggle.com/code/kushalnigam/customer-churn-analysis-and-prediction">Customer Churn Analysis and Prediction</a></li><li><a href="https://www.superoffice.com/blog/reduce-customer-churn/">Customer Churn: 12 Strategies to Stop Churn Right Now!</a></li></ul><h3>Appreciation</h3><p>I highly recommend Azubi Africa for their comprehensive and effective programs. Read More articles about Azubi Africa <a href="https://medium.com/@azubiafrica">here</a> and take a few minutes to visit this link to learn more about Azubi Africa life-changing <a href="https://www.azubiafrica.org/data-analytics?utm_source=medium%2Clinkedin&amp;utm_medium=articles&amp;utm_campaign=DAP+Learners">programs</a>.</p><p><strong><em>Thank you for reading!</em></strong></p><p><strong><em>You can access all the code for this project in my </em></strong><a href="https://github.com/Azie88/ML-Classification-Customer-Churn-Prediction"><strong><em>github repository</em></strong></a><strong><em>. Show your appreciation if you found this insightful. Leave me a comment if you have any points or suggestions.</em></strong></p><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/andrewobando/"><strong><em>LinkedIn</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae46c574e60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner Data Analytics — Indian Startup Ecosystem Dataset (2018–2021)]]></title>
            <link>https://medium.com/@obandoandrew8/beginner-data-analytics-indian-startup-ecosystem-dataset-2018-2021-e4a5a2fb5516?source=rss-82bd0279dcd4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4a5a2fb5516</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[seaborn]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Andrew Obando]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 18:38:17 GMT</pubDate>
            <atom:updated>2024-03-21T23:09:02.831Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beginner Data Analytics— Data Cleaning &amp; Visualization with Python &amp; Power BI</h3><figure><img alt="Abstract Data Charts | Beginner Data Analytics" src="https://cdn-images-1.medium.com/max/1024/1*NZjeEdwrfdbsBRcjgvvGYA.png" /><figcaption>Data Analytics &amp; Visualization</figcaption></figure><p>In this article, let’s explore the basics of data cleaning and gaining insights through visualization. We will be using data from Indian startups that were funded from 2018 to 2021. We will also use the <a href="https://www.datascience-pm.com/crisp-dm-2/">CRISP-DM framework</a> , a common approach that guides data mining, analytics, and data science projects. Let’s dig deep into the world of Indian startups.</p><p>The main goal of my research was to understand the Indian startup ecosystem, figure out the important trends and find out which industries got the most funding during this time (2018–2021). Data analytics and visualization can help people make better business decisions. So, let’s dive in and discover the interesting things I found during this exploration!</p><h4>Table Of Contents</h4><p><strong>· </strong><a href="#16bd"><strong>1. Business Understanding</strong></a><br> ∘ <a href="#e33a">Hypothesis</a><br> ∘ <a href="#83df">Analytical Questions</a><br><strong>· </strong><a href="#bded"><strong>2. Data Understanding</strong></a><br> ∘ <a href="#b225">Loading packages</a><br> ∘ <a href="#723f">Column names and description</a><br> ∘ <a href="#5038">Preview the Data Frames</a><br> ∘ <a href="#4b35">Data Understanding Summary</a><br><strong>· </strong><a href="#7a75"><strong>3. Data Preparation</strong></a><br> ∘ <a href="#ae64">Exploratory Data Analysis</a><br> ∘ <a href="#36be">Power BI Dashboard</a><br><strong>· </strong><a href="#7ab0"><strong>4. Conclusion and Recommendations</strong></a><br> ∘ <a href="#f946">References</a><br> ∘ <a href="#b125">Appreciation</a></p><h3>1. Business Understanding</h3><p>Indian Startups have made a name for themselves across the world, attracting investment for many sectors. The Indian startup ecosystem has borne witness to a phenomenal surge, driven by India’s rapidly expanding economy and the emergence of influential unicorn startups on the global stage.</p><p>Despite their relatively modest size, startups wield a profound impact on economic growth, stimulating job creation and nurturing a robust employment market, consequently contributing to a healthier economy. Moreover, they play a pivotal role as catalysts for economic vitality, fueling innovation and fostering healthy competition.</p><figure><img alt="Best Indian Startups of the Decade 2010–2020 | Beginner Data Analytics" src="https://cdn-images-1.medium.com/max/1024/1*G4qW2L2Bj7mGxoVkq-BrGQ.jpeg" /><figcaption><a href="https://startuptalky.com/startups-of-the-decade/">Best Indian Startups of the Decade 2010–2020</a></figcaption></figure><blockquote>According to Prime Minister Narendra Modi, “<a href="https://viestories.com/national-startup-day-2023-top-20-startup-quotes/">India’s startups are now working in 55 different industries. Five years ago, there were not even 500 startups in India! Today the number has crossed 60,000.</a>” (January 15, 2022).</blockquote><h4><strong>Hypothesis</strong></h4><p><strong><em>Null Hypothesis(Ho)</em></strong> : Amount raised(capital) is limited to only a few core sectors.</p><p><strong><em>Alternate Hypothesis(Ha)</em></strong> : Amount raised is spread widely across multiple sectors (more evenly spread).</p><h4>Analytical Questions</h4><ol><li>Which year has the highest amount of investment?</li><li>Which sector received the highest amount of funding collectively?</li><li>Which region has the most startups?</li><li>Which Region received the most investment</li><li>Which sector received the lowest amount of funding collectively?</li><li>What is the average amount of capital invested for the top 5 sectors?</li><li>Top 10 companies with highest amount invested?</li></ol><h3>2. Data Understanding</h3><p>We first collect our data and organize it to make it fit for analysis. Verifying data quality and consistency are the objectives here.</p><h4><strong>Loading packages</strong></h4><p>To start with, we import the basic native python packages and modules for data analysis. These include:</p><ul><li><strong>Pandas</strong>: for data manipulation and structuring</li><li><strong>NumPy</strong>: for mathematical functions on arrays</li><li><strong>Matplotlib</strong>: for data visualization</li><li><strong>Seaborn</strong>: for data visualization</li><li><strong>Warnings</strong>: to deal with the potential issues</li></ul><figure><img alt="Importing Python Packages for Data Analytics | Beginner Data Analytics" src="https://cdn-images-1.medium.com/max/768/1*VgLo-zFlgItRNzuzZkCzCw.png" /><figcaption>Import Python Packages</figcaption></figure><p>I am using a <strong>Jupyter notebook</strong> on <a href="https://code.visualstudio.com/"><strong>Visual Studio code</strong></a>. You can also use <a href="https://colab.google/"><strong>Google colab</strong></a>.</p><h4>Column names and description</h4><p>These are the columns in our dataset and their descriptions:</p><ul><li><strong>Company/Brand</strong>: Name of the company/start-up</li><li><strong>Founded</strong>: Year start-up was founded</li><li><strong>Sector</strong>: Sector of service</li><li><strong>What it does</strong>: Description about Company</li><li><strong>Founders</strong>: Founders of the Company</li><li><strong>Investors</strong>: Investors</li><li><strong>Amount($)</strong>: Raised fund</li><li><strong>Stage</strong>: Round of funding reached</li></ul><h4><strong>Preview the Data Frames</strong></h4><p>We then import our individual datasets as Pandas Data Frames. The datasets were cleaned and merged, with this process being literally 90% of the project.</p><p>You can get the individual and concatenated <a href="https://github.com/Azie88/LP1-Data-Analysis/tree/main/Dataset"><strong>datasets</strong></a> and the <a href="https://github.com/Azie88/LP1-Data-Analysis/blob/main/Project_notebook.ipynb"><strong>jupyter note book</strong></a> for an in-depth view. This dataset is very messy and disorganized. It is great practice for cleaning and preparing data for analysis and even modelling. However, we wont be making any models. Here is a summary of our data:</p><p><strong>The 2018 Data Frame</strong></p><figure><img alt="Screenshot of 2018 Startup Data Frame Preview | Data Cleaning" src="https://cdn-images-1.medium.com/max/1003/1*NbHCGiCKPTf1DJWkNVoO6g.png" /><figcaption>2018 Data Frame</figcaption></figure><ul><li>The Data Frame has 526 rows and 6 columns.</li><li>Dashes were used in the Amount column for deals whose values were not known.</li><li>The Amount column has a mix of currencies; Indian Rupees (INR) and US Dollars (USD), meaning they have to be converted into the same currency.</li><li>The Industry and Location columns have multiple information that needs to be simplified and standardized. A decision is to be made between selecting the first value before the separator(,) as the main value or representing that column with a word cloud.</li></ul><p><strong>The 2019 Data Frame</strong></p><figure><img alt="Screenshot of 2019 Startup Data Frame Preview | Data Cleaning" src="https://cdn-images-1.medium.com/max/998/1*vh9rPVEoHjjYs24q-m5x_w.png" /><figcaption>2019 Data Frame</figcaption></figure><ul><li>The Data Frame has 89 rows and 9 columns.</li><li>The data type of the Founded column is set to float datatype. It should be set to a string or integer for uniformity.</li><li>The headquarter column has multiple information. A decision is to be made between selecting the first value before the separator(,) as the main value or representing that column with a word cloud</li></ul><p><strong>The 2020 Data Frame</strong></p><figure><img alt="Screenshot of 2020 Startup Data Frame Preview | Data Cleaning" src="https://cdn-images-1.medium.com/max/996/1*sg2Ru-8nAftNM2qbUXM3IQ.png" /><figcaption>2020 Data Frame</figcaption></figure><ul><li>There is an extra column called column10, giving it a total of 10 columns. It should be dropped to ensure complete alignment with the other Data Frames for ease of concatenation.</li><li>The data type of the Founded column is set to float datatype. It should be set to a string or integer for uniformity.</li></ul><p><strong>The 2021 Data Frame</strong></p><figure><img alt="Screenshot of 2021 Startup Data Frame Preview | Data Cleaning" src="https://cdn-images-1.medium.com/max/990/1*vRYIDoBcgW8tyc-HKx3yiQ.png" /><figcaption>2021 Data Frame</figcaption></figure><ul><li>The data type of the Founded column is set to float datatype. It should be set to a string or integer for uniformity.</li></ul><h4><strong>Data Understanding Summary</strong></h4><ul><li>The column names in 2018 are different from those of 2019–2021, meaning they have to be renamed before concatenation for uniformity.</li><li>The currency signs and commas have to be removed from each amount in the Amount column for each Data Frame. We just want them as plain numbers.</li><li>All the columns with amounts have to be set to float data type.</li><li>All the years in the Founded column should be converted to object or integer data types.</li><li>We need to create a column with the year of funding for each Data Frame.</li></ul><p><strong>Assumptions</strong></p><ol><li>The average Indian Rupee (INR) to US Dollar (USD) rate for the relevant year will be used for currency conversions. Amounts in Rupees will be converted to Dollars for uniformity.</li><li>The values in the Industry and Location columns in the 2018 data frame are referring to the primary sector and headquarters respectively.</li><li>Amounts without currency symbols are assumed to be in USD.</li><li>Imputations will not be made for undisclosed and/or unavailable (missing) amounts due to the uncertainties, risks of misstatements and possible misleading effects on the analyses.</li></ol><h3><strong>3. Data Preparation</strong></h3><p>Here we clean our data, re-format datatypes, delete unwanted fields and columns and merge our datasets to prepare our final dataset. Without proper cleaning, we will get inaccurate analysis. Garbage in, garbage out. The following key activities were undertaken:</p><ol><li><strong>String formatting</strong>: All columns, except for the Amount columns, underwent string formatting. The Amount columns were converted to numeric format for statistical analysis.</li><li><strong>Separation of location and industry</strong>: The entries in the Location and Industry columns were simplified. Values were separated using commas as delimiters, with the first value being selected.</li><li><strong>Duplicates and Null Values</strong>: Duplicated rows and null values were deleted or imputed with appropriate values</li><li><strong>Currency conversion</strong>: For the 2018 data frame Amount column, two new columns were created to facilitate currency conversion. After standardizing the amounts, the extra columns were dropped. Commas and currency symbols were removed from the Amount columns</li><li><strong>Drop Columns</strong>: Unwanted columns such as Founded , Founders, and Investor were deleted. They were unnecessary for our analysis. The column10 was also deleted.</li><li><strong>Data integrity</strong>: To ensure data integrity, ‘<strong>nan’</strong> string values were replaced with np.nan, and any notable misplaced or erroneous values were renamed and rectified in their respective rows. It is very tedious work doing it manually but also necessary.</li><li><strong>New Columns</strong>: A new column called Year, indicating the year of funding, was added to each Data Frame.</li><li><strong>Unification of Data Frames</strong>: The column names were renamed to match each other before merging them. We end up with a clean merged dataset that we use to gain insights through visualization.</li></ol><figure><img alt="Screenshot of Final merged Startup Data Frame Preview | Data Cleaning" src="https://cdn-images-1.medium.com/max/1024/1*2iWEAHDqOe7pSJQhyF8flg.png" /><figcaption>Final Cleaned Dataset</figcaption></figure><p>For a more detailed understanding of the code, functions and processes employed, kindly refer to the <a href="https://github.com/Azie88/LP1-Data-Analysis/blob/main/Project_notebook.ipynb"><strong>project notebook</strong></a>. It encompasses comprehensive insights into the step-by-step procedures undertaken during the data analysis and preparation.</p><h4><strong>Exploratory Data Analysis</strong></h4><figure><img alt="Screenshot pf Power BI Dashboard | Data Visualization" src="https://cdn-images-1.medium.com/max/892/1*1Jr9BPHyX__AstXAfJwjuQ.png" /><figcaption>Power BI Dashboard</figcaption></figure><p>Now the fun part! <strong>Exploratory data analysis</strong> is a crucial step in any data science project. Using visualizations and descriptive statistics, we can gain insights into our data. <strong>Univariate analysis</strong> focuses on analyzing one variable, such as the amount invested, or the number of companies. <strong>Bivariate analysis</strong> helps us understand the relationship between two variables, such as amount invested by sector or year. <strong>Multivariate analysis</strong> gives us analysis on three or more variables.</p><p>We use EDA to answer our research questions. The main takeaways from the EDA are as follows:</p><ul><li><strong>Fintech Dominance</strong>: The Fintech sector emerged as the frontrunner, securing the highest amount of funding, with an impressive total funding of <strong>$179.88 billion </strong>from 2018–2021. This indicates that investors and funding sources have shown considerable interest and confidence in the Fintech startups during the analyzed period.</li></ul><figure><img alt="Bar graph of top 5 sectors by amount of funding received | Data Visualization" src="https://cdn-images-1.medium.com/max/778/1*Rof1LvzMXcB7pBH8ajO5vQ.png" /><figcaption>Fintech Dominance</figcaption></figure><ul><li><strong>Favorable Economic Conditions in 2021</strong>: The year 2021 witnessed a significant surge in investments within the startup ecosystem, reaching approximately <strong>$195 billion</strong>. This suggests that the economic conditions during that year were highly conducive to attracting substantial investments in startups, potentially indicating a thriving and favorable market. The spike in investment during the pandemic years may also be fueled by low interest rates and investors looking for the ‘next big thing’.</li></ul><figure><img alt="Line graph of sum of funding by year | Data Visualization" src="https://cdn-images-1.medium.com/max/774/1*GmP-WL2RfRptGUIrpSmPiQ.png" /><figcaption>Sum of Funding each Year</figcaption></figure><ul><li><strong>Bangalore’s Startup Hub</strong>: Bangalore emerged as the primary hub for startups, hosting a remarkable number of approximately <strong>855 startups</strong> in the region. This prominence further solidifies Bangalore’s reputation as a leading destination for entrepreneurship and innovation within the Indian startup landscape.</li></ul><figure><img alt="Table of top 5 cities with the most startups | Data Visualization" src="https://cdn-images-1.medium.com/max/756/1*Fbc7SeMjPAAWF4Vp6eaXKw.png" /><figcaption>Top 5 regions with the most startups</figcaption></figure><ul><li><strong>Sector Distribution in Bangalore</strong>: Among the startups in Bangalore, the distribution across sectors showed that <strong>retail</strong> sector has the highest amount invested, with <strong>food delivery</strong> and <strong>innovation management </strong>also having significant investment. This indicates that these sectors have seen significant activity and interest from entrepreneurs and investors in the region, possibly due to their growth potential and opportunities for disruption.</li></ul><figure><img alt="Bar graph of top 5 sectors in Bangalore | Data Visualization" src="https://cdn-images-1.medium.com/max/1024/1*iztXCREr-iGRV_D5jN9O0Q.png" /><figcaption>Top 5 startup sectors in Bangalore</figcaption></figure><ul><li><strong>Mumbai’s Investment Magnet</strong>: The data reveals that Mumbai received the highest amount of investments among the analyzed cities, totaling approximately <strong>$242.2 billion</strong>. This indicates that Mumbai holds a significant allure for investors, making it a prominent destination for startup funding within the Indian startup ecosystem.</li><li><strong>Startup Funding Struggle</strong>: On the other end of the spectrum, <strong>Warehouse</strong>, <strong>Interior &amp; Decor, E-sports </strong>and <strong>Milk Startup </strong>emerged as the sectors with the lowest amount of funding, receiving <strong>$100,000 </strong>or less. This suggests that these sectors faced challenges in attracting substantial investments during the specified period, possibly due to various factors like market competitiveness or investor preferences. Unfortunately, you just have to bootstrap your milk startup.</li></ul><figure><img alt="Bar graph of sectors with the lowest funding | Data Visualization" src="https://cdn-images-1.medium.com/max/1024/1*a947rGG3Ho5n9wetIoOEKA.png" /><figcaption>Bottom 5 sectors by funding</figcaption></figure><ul><li><strong>The average capital invested for the top 5 sectors is as follows</strong>:</li></ul><p><strong><em>Retail</em></strong><em>: $2.4 billion</em></p><p><strong><em>Multinational Conglomerate Company</em></strong><em>: $2.2 billion</em></p><p><strong><em>FinTech</em></strong><em>: $697.2 million</em></p><p><strong><em>Food Delivery</em></strong><em>: $315.3 million</em></p><p><strong><em>Hospitality</em></strong><em>: $90.9 million</em></p><figure><img alt="Horizontal bar graph of top 5 sectors by average amount invested | Data Visualization" src="https://cdn-images-1.medium.com/max/974/1*ZqMyA0moaHMCFusgjEwAVw.png" /><figcaption>Top 5 sectors by average amount invested</figcaption></figure><ul><li><strong>The top 10 companies with the highest funding</strong> are illustrated below, with <strong>Alteria Capital</strong> taking the lead with <strong>$150 billion</strong>.</li></ul><figure><img alt="The top 10 companies with the highest funding | Indian Startups | Data Visualization" src="https://cdn-images-1.medium.com/max/922/1*21qTz402Rz9aIkXnI38QPQ.png" /><figcaption>The top 10 companies with the highest funding</figcaption></figure><h4>Power BI Dashboard</h4><p>Power BI is a business analytics service by Microsoft that provides interactive visualizations and business intelligence capabilities with an interface simple enough for end users to create their own reports and dashboards.</p><p>The final dataset was exported into Power BI to gain further insights and analysis, due to its smart and interactive nature. It is very easy for anyone to create a dashboard. Here is a link to <a href="https://app.powerbi.com/view?r=eyJrIjoiZjFiMjUyNTAtYTBlOC00Njk3LWI4OWUtZWI3MWI0YjMwMDVlIiwidCI6IjQ0ODdiNTJmLWYxMTgtNDgzMC1iNDlkLTNjMjk4Y2I3MTA3NSJ9"><strong>my dashboard</strong></a>.</p><h3>4. Conclusion and Recommendations</h3><ul><li>Top sectors in Indian startup ecosystem are <strong>Fintech</strong>, <strong>Retail</strong>, <strong>Edtech</strong>, <strong>Tech</strong> and <strong>E-commerce</strong>.</li><li><strong>Bangalore</strong> has the most startups. It seems to be an emerging city with the top sectors being <strong>Retail</strong>, <strong>Food Delivery, Innovation Management </strong>and <strong>FinTech.</strong></li><li><strong>Mumbai</strong> is the big city with the big money investments, with leading sectors being <strong>Fintech</strong>, <strong>Retail</strong> and a <strong>Multinational conglomerate.</strong></li><li>In different regions, different sectors are more heavily invested in. In this case, we reject our null hypothesis and accept our alternate hypothesis that the investment raised is spread widely across multiple sectors</li><li>Business in <strong>Mumbai</strong> in <strong>Fintech</strong> or <strong>Retail </strong>is doing well. This is the best bet for new startups in India as you can get a slice of the pie if you have a good product. There seems to be high demand for finance solutions and shopping experiences. Moreover, retail was popular during the pandemic as more people were probably shopping from home.</li><li>Alternatively, you could start a business in <strong>Bangalore</strong>, since it seems the preferred region for startups. <strong>Retail</strong>, <strong>Food Delivery, Innovation Management </strong>or <strong>FinTech</strong> is the preferred sector to go into.</li></ul><h4>References</h4><ul><li><a href="https://careerfoundry.com/en/blog/data-analytics/the-data-analysis-process-step-by-step/">A Step-by-Step Guide to the Data Analysis Process [2024]</a></li><li><a href="https://towardsdatascience.com/a-beginners-guide-to-data-analysis-in-python-188706df5447">A Beginner’s Guide to Data Analysis in Python</a></li><li><a href="https://monkeylearn.com/blog/data-cleaning-steps/">Data Cleaning Steps &amp; Process to Prep Your Data for Success</a></li></ul><h4>Appreciation</h4><p>I highly recommend Azubi Africa for their comprehensive and effective programs. Read More articles about Azubi Africa <a href="https://medium.com/@azubiafrica">here</a> and take a few minutes to visit this link to learn more about Azubi Africa life-changing <a href="https://www.azubiafrica.org/data-analytics?utm_source=medium,linkedin&amp;utm_medium=articles&amp;utm_campaign=DAP+Learners">programs</a>.</p><p><strong><em>Thank you for reading!</em></strong></p><p><strong><em>You can access all the code for this project in my </em></strong><a href="https://github.com/Azie88/LP1-Data-Analysis"><strong><em>github repository</em></strong></a><strong><em>. Show your appreciation if you found this insightful. Leave me a comment if you have any points or suggestions.</em></strong></p><p><strong><em>Connect with me on </em></strong><a href="https://www.linkedin.com/in/andrewobando/"><strong><em>LinkedIn</em></strong></a><strong><em>.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4a5a2fb5516" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>