<?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 Gregory Kwaku Arthur on Medium]]></title>
        <description><![CDATA[Stories by Gregory Kwaku Arthur on Medium]]></description>
        <link>https://medium.com/@gregoryarthur98?source=rss-768dee559ee2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oKXPwOMFerscw-kuj8TTEg.jpeg</url>
            <title>Stories by Gregory Kwaku Arthur on Medium</title>
            <link>https://medium.com/@gregoryarthur98?source=rss-768dee559ee2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:27:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gregoryarthur98/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[Building a Sentiment Analysis Web App with Streamlit and Fine-Tuned Tiny-Bert]]></title>
            <link>https://gregoryarthur98.medium.com/building-a-sentiment-analysis-web-app-with-streamlit-and-fine-tuned-tiny-bert-1bc6ca1c3585?source=rss-768dee559ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bc6ca1c3585</guid>
            <dc:creator><![CDATA[Gregory Kwaku Arthur]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 11:37:17 GMT</pubDate>
            <atom:updated>2023-09-14T11:37:17.840Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introduction</h4><p>The emergence of Natural Language Processing (NLP) has unlocked various applications that were once considered out of reach. One such application is Sentiment Analysis, which provides insights into the emotional tone underlying text. By leveraging a pre-trained Tiny-Bert model, this project aims to offer a simple, yet effective, web-based Sentiment Analysis tool. Built with Python’s Streamlit library, the web app incorporates some advanced features, including caching and animations, to enhance the user experience.</p><h4>The Code Layout</h4><p>The code starts by importing necessary modules such as Streamlit, Torch, Transformers, Pandas, and others. These libraries provide the foundation for data manipulation, model loading, and web interfacing.</p><pre>import streamlit as st <br>import torch <br>from transformers import AutoTokenizer, AutoModelForSequenceClassification<br>import re<br>from transformers import pipeline</pre><h4>The Front-End</h4><p>The front-end of the app is built using Streamlit’s intuitive and interactive elements. The main title and text input fields are established right away.</p><pre>st.title(&quot;Welcome to the Fine-Tuned Tiny-Bert Sentiment Classifier Page&quot;)<br>text = st.text_input(&quot;Please Enter Your Thoughts of The Movie: &quot;)</pre><h4>Incorporating Animations</h4><p>Streamlit also allows for animations using the `streamlit_lottie` package. The code has a function `load_lottiefile()` to read in a JSON file containing the animation.</p><pre>from streamlit_lottie import st_lottie <br>def load_lottiefile(filepath: str):<br> with open(filepath, &quot;r&quot;) as f:<br> return json.load(f)</pre><h4>Caching and Session State</h4><p>To improve performance, Streamlit’s `<a href="http://twitter.com/st">@st</a>.cache_data` decorator is used for both loading the model and tokenizer. This reduces the time to reload these components. The session state management feature allows the app to maintain the state between reruns.</p><pre>@st.cache_data(ttl=86400)<br>def load_model(model_name):<br> return AutoModelForSequenceClassification.from_pretrained(model_name)<br><br>@st.cache_data(ttl=86400)<br>def load_tokenizer(tokenizer_name):<br> return AutoTokenizer.from_pretrained(tokenizer_name)</pre><h4>Text Processing</h4><p>The `data_cleaner` function removes unwanted characters, such as hashtags and punctuation, making the text ready for analysis.</p><pre>def clean_text(text):<br>    # Remove stopwords<br>    text = &quot; &quot;.join([word for word in text.split() if word not in stopwords])<br>    <br>    # Convert numbers to words<br>    text = &quot; &quot;.join([num2words(word) if word.isdigit() else word for word in text.split()])<br>    <br>    # Remove special characters<br>    pattern = r&#39;[^a-zA-Z0-9\s]&#39;<br>    text = re.sub(pattern, &#39;&#39;, text)<br>    <br>    ##for numbers that do no get converted will be dropped <br>    <br>    text = re.sub(r&#39;\d+&#39;, &#39;&#39;, text)<br>    return text</pre><h4>Prediction and Output</h4><p>Finally, the app uses a pre-trained Tiny-Bert model for sentiment analysis and displays the result along with the confidence score.</p><pre>result = pipe(data_cleaner(text))<br>if st.button(&quot;Predict Sentiment&quot;):<br> for results in result:<br> st.write(f&quot;Your sentiment is {results[&#39;label&#39;]} with a confidence score of {results[&#39;score&#39;]}&quot;)</pre><h4>Conclusion</h4><p>Building a web-based sentiment analysis tool might seem daunting, but with the right tools and libraries, it’s entirely feasible. This article provides a comprehensive overview of building such an app using Streamlit and a pre-trained Tiny-Bert model for sentiment analysis. The app is not only efficient but also user-friendly, thanks to the implementation of caching and session state management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bc6ca1c3585" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Sepsis Prediction System with FastAPI:]]></title>
            <link>https://gregoryarthur98.medium.com/building-a-sepsis-prediction-system-with-fastapi-9296a796f2e4?source=rss-768dee559ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9296a796f2e4</guid>
            <dc:creator><![CDATA[Gregory Kwaku Arthur]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 18:41:50 GMT</pubDate>
            <atom:updated>2023-08-20T18:41:50.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Kyk5fK8gSjwX3cETwH9Wxw.png" /></figure><p>The world of healthcare is undergoing a digital transformation, and one of the areas gaining traction is the integration of machine learning models for predictive diagnostics. The given code snippet is a beautiful example of how FastAPI, a modern and fast web framework for building APIs, can be used to build a sepsis prediction system.</p><h4>1. Importing Libraries</h4><p>The code starts by importing essential libraries such as FastAPI, uvicorn for serving the app, pandas for data manipulation, and joblib for loading the trained model. It also includes XGBoost and imblearn, which suggests that the underlying model may be using these libraries.</p><h4>2. Loading the Model</h4><p>The pretrained model xgb.joblib is loaded using joblib, a popular library for serializing Python objects. This model likely uses the XGBoost algorithm and has been trained to predict sepsis based on certain input features.</p><h4>3. Defining the API with FastAPI</h4><p>FastAPI is used to define the API, and the code snippet establishes two main endpoints:</p><ul><li>GET Endpoint: A basic welcome message that serves as a health check or an introduction to the API.</li><li>POST Endpoint: A more complex endpoint that predicts sepsis based on input parameters.</li></ul><h4>4. Sepsis Prediction Endpoint</h4><p>The POST endpoint, defined under /predict/, takes in various parameters, including Plasma_glucose, Blood_Pressure, BMI, and other blood work-related variables. These are then processed into a DataFrame, which is fed into the model for prediction.</p><p>The classification result is mapped into a human-readable format using the classify function, and the prediction is returned as a JSON response.</p><h4>5. Running the Application</h4><p>Finally, the application is run using Uvicorn when executed as a standalone script. You can run it by <a href="https://garthur98-sepsis.hf.space/docs">accessing the link here</a>.</p><h3>Conclusion</h3><p>This code represents a powerful tool in healthcare, leveraging state-of-the-art techniques to make sepsis predictions. FastAPI provides an easy and efficient way to serve the model, making it accessible to other systems or front-end applications. It’s a fantastic illustration of how modern Python libraries can be used to bridge the gap between machine learning research and real-world applications.</p><p>By integrating this API into hospital systems or healthcare applications, doctors and medical professionals can have instant access to a tool that could be vital in early detection and treatment of sepsis, potentially saving lives. The code structure also allows for easy expansion, meaning other models or additional endpoints could be added as needed.</p><p>The simplicity and effectiveness of this code are a testament to the power of Python and its ecosystem in developing meaningful solutions for real-world problems. Whether you’re a healthcare professional, data scientist, or developer, this code serves as a great template for building and deploying predictive models.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9296a796f2e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Pre-trained Models to Predict Twitter Sentiments]]></title>
            <link>https://gregoryarthur98.medium.com/leveraging-pre-trained-models-to-predict-twitter-sentiments-c191b5da61a5?source=rss-768dee559ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c191b5da61a5</guid>
            <dc:creator><![CDATA[Gregory Kwaku Arthur]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 23:05:12 GMT</pubDate>
            <atom:updated>2023-08-04T07:44:51.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*ZMe57TEcg_HyFwpY9ITQzA.jpeg" /><figcaption>Image Credit: GeeksforGeeks</figcaption></figure><p>Welcome once again to yet another article by yours truly: Gregory Arthur, a data scientist/analyst from Ghana. In this article, we will go through how you can fine-tune a pre-trained model for text classification, which in this case my texts are Covid-19 tweets.</p><p>During the Covid-19 pandemic, most people stayed home, and as such tons of people resorted to using various social media platforms to help them cope with boredom and connect with family/friends across the globe. One of the most used social media platforms was Twitter. And obviously, most tweets on the platform were about the pandemic: Covid-19. As such, it became imperative for data scientists to scrape and analyze Covid-19 themed tweets to extract the sentiments these tweets carry.</p><p>So, as an aspiring Data scientist, I was tasked to analyze these tweets using pre-trained models (transformers), and I must say it has been a tough yet enlightening journey.</p><p>As always, we will be using the CRISP-DM framework for this post. Also, it is worth noting that <strong>I have deployed the </strong><a href="https://huggingface.co/gArthur98/Greg-DistilBert-classifier"><strong>DistilBert model</strong>,</a> and <a href="https://huggingface.co/gArthur98/Roberta-Sentiment-classifier">t<strong>he Roberta Base model</strong></a>. and <a href="https://huggingface.co/spaces/gArthur98/distill_sentiment_classifier"><strong>I also have the app fully deployed as well</strong></a><strong>.</strong></p><p>In this article, you will learn the following:</p><ul><li>How to preprocess text data</li><li>How to visualize textual data</li><li>How to fine-tune and evaluate a pre-trained model</li></ul><h3>Outline:</h3><ul><li>Business Understanding</li><li>Data Understanding</li><li>Data Preparation</li><li>Modelling</li><li>Evaluation</li><li>Deployment</li></ul><p><strong>That being said, below is a video of my app in action:</strong></p><p><a href="https://github.com/Greg-Art/Streamlit-App-Sentiment-Analysis/assets/126587191/20ca9a43-fa85-4a22-9a36-7f8342541ba6">https://github.com/Greg-Art/Streamlit-App-Sentiment-Analysis/assets/126587191/48030828-2527-4409-9b0d-f0de2cae3784</a></p><p>You can check out the app <a href="https://sentiment-analysis-hft7l62e9r.streamlit.app/"><strong>by clicking on this link</strong></a>.</p><p>If you are looking to build such an amazing app, <a href="https://medium.com/@gregoryarthur98/create-a-multipage-app-for-your-regression-model-without-using-css-html-django-f5b552b4a875"><strong>then do well to check out my previous blog</strong></a>.</p><p>Now, with these out of the way, let’s dive into how this was achieved.</p><h3>1.Business Understanding</h3><p>Twitter is a powerful tool for businesses to understand public sentiment and trends related to COVID-19. By analyzing tweets, businesses can identify topics that are important to their customers, track the evolution of public opinion, and identify potential risks and opportunities.</p><p>For example, a business that sells face masks could use Twitter to track the number of tweets that mention face masks. This information could help the business to determine the demand for face masks and to adjust its marketing and sales strategies accordingly.</p><p>In addition, businesses can use Twitter to listen to customer feedback and identify potential problems. For example, if a business starts to see a lot of tweets about customer dissatisfaction with its products, it could use this information to improve its products or services.</p><p>Overall, Twitter can be a valuable tool for businesses that are looking to understand the impact of COVID-19 on their customers and to stay ahead of the curve.</p><p>Here are some specific business risks that can be identified through COVID-19 tweets:</p><p><strong>Changes in consumer behaviour</strong>: Businesses can track changes in consumer behaviour, such as a shift to online shopping or a decrease in spending on discretionary items.</p><p><strong>Public health concerns: </strong>Businesses can monitor public health concerns, such as the spread of new variants or the effectiveness of vaccines.</p><p><strong>Government regulations:</strong> Businesses can track government regulations, such as travel restrictions or mask mandates.</p><p>By understanding these risks, businesses can take steps to mitigate them and protect their bottom line.</p><h3>2. Data Understanding</h3><h4>2.1.Feature Understanding</h4><p>The data presented consisted of two datasets: train and test set. I used the train set for my analysis. The train data came with the following features</p><ul><li><strong>Tweet id: </strong>Contained information about the various unique id of each tweet.</li><li><strong>safe text</strong>: Contained the various tweets from various users.</li><li><strong>label</strong>: Contained the sentiment score for each tweet. -1 meant the tweet was negative, 0 meant the tweet was neutral, and 1 meant the tweet was positive.</li><li><strong>agreement</strong>: Showed the confidence level for each sentiment.</li></ul><h4>2.2 Libraries Used:</h4><p>I used the following libraries for my preprocessing and visualizations:</p><pre>%%capture<br><br>##for data handling<br>import pandas as pd<br>import numpy  as np<br><br>##visualizations<br><br>import matplotlib.pyplot as plt<br>import plotly.express as px<br>import seaborn as sns<br><br>##NLP<br><br>import nltk<br>from wordcloud import WordCloud, STOPWORDS<br>import re,string, unicodedata<br>from nltk.tokenize import word_tokenize<br>from nltk.stem import WordNetLemmatizer<br>from string import punctuation<br>from nltk.corpus import wordnet<br>from collections import Counter<br>import string<br>nltk.download(&#39;punkt&#39;)<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;maxent_ne_chunker&#39;)<br>nltk.download(&quot;words&quot;)<br>import nltk<br>from nltk.corpus import gutenberg<br>from nltk import FreqDist</pre><h4>2.2 Data Overview and EDA</h4><p>In this section, I dived deep into the dataset to see if there were any discrepancies.</p><h4><strong>2.2.1 Checking for Missing Values</strong></h4><p>I started by checking for missing values using the code below.</p><pre>data=[df_train, df_test]<br>names=[&quot;df_train&quot;, &quot;df_test&quot;]<br>for m, i in zip(data, names):<br>print(f&quot;the missing values in the&quot;, i,&quot;dataset are: &quot;, &quot;\n\n&quot;, m.isna().sum(), &quot;\n\n&quot;, &quot; - -&quot;*20 )</pre><p>the results are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7IFuKP0IfuouNZagOvJgdg.png" /></figure><p>NB: We will handle the missing values in the data processing stage.</p><h4>2.2.2 Visualizations</h4><p>The next step was to perform some visualizations to understand my data better.</p><p>i.Checking the distribution of the Label</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qP092EyCEFS2-1yj7AdCLg.png" /></figure><ul><li>Most tweets carried neutral sentiments</li><li>There were more positive tweets than negative</li><li>There is a class imbalance since the negative class was under-represented.</li><li>There is a random value which doesn’t belong to any of our predefined class</li></ul><p>ii. <strong>Visualizing the most occurring words:</strong></p><p>I also went ahead to visualize the most occurring words in the uncleaned tweets.</p><p>The image is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*6FsULRwFhTL7TXwKC0O4jw.png" /></figure><p><strong>iii. Visualizing Word Count:</strong></p><p>Also, I thought I might have an idea of the length of most covid-19 related tweets</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4KhfCv3SvOqYW_YmkRO4Q.png" /></figure><p>From the image above, it can be inferred that most tweets were between 15 to 20 words.</p><h3>3. Data Preparation</h3><p>After having an idea of the nature of my feature and label, I proceeded to clean the data and then perform some NLP preprocessing steps to get the data clean and ready for my model.</p><p>I performed the following minor steps:</p><ul><li>I renamed the <strong>safe_text</strong> feature to <strong>tweets </strong>for easy readability.</li><li>I got rid of the<strong> tweet_id</strong> feature since it had no inherent value</li><li>I changed every word to lowercase for consistency and to make handling the sentence easy.</li><li>I also saved my preprocessed tweets in a feature named “<strong>clean_tweet</strong>” This helped me see how the various preprocessing steps I took materialized.</li></ul><h4><strong>3.1 Handling Missing Values</strong></h4><p>As shown earlier, there were missing values. I decided to drop them since they were just a few missing values.</p><pre>df_train= df_train.dropna()<br>df_test= df_test.dropna()</pre><p>The code above gave me the result below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOQC6lSoRt3xh7kcG4FuTg.png" /></figure><p>As can be seen, there are no more missing values. Also, dropping the missing values got rid of</p><h4>3.2 Removing Punctuations</h4><p>In NLP, we are interested in removing punctuations since the value of a sentence lies in the words.</p><blockquote>Note: This got rid of hashtags together with emojies.</blockquote><p>To do this, I used the code below:</p><pre>def punctuation_remover(text):<br>  ##removing has tags<br>  text= re.sub(r&#39;#\w+&#39;, &#39;&#39;, text)<br>  ##removing punctuations<br>  text= re.sub(&quot;[^\w\s]&quot;, repl= &quot;&quot;, string=text)<br>  return text</pre><p>The code gave me the result below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tssgYnuD8v3RzJJQY6Vc4Q.png" /></figure><h4>3.3. Removing Stopwords</h4><p>In NLP, it is recommended that you remove stopwords. Stop words are words such as pronouns and prepositions which do not hold any value.</p><p>To help me with this I used the code below:</p><pre>##instantiating my Stopwords module<br><br>stopwords= STOPWORDS<br><br>##creating a function to only return words that are not in my stopword variable <br><br>def remove_stopwords(text):<br>  return &quot; &quot;.join([word for word in text.split() if word not in stopwords])<br><br>##applying the function to my dataframe<br>df_train[&quot;clean_tweet&quot;]= df_train[&quot;clean_tweet&quot;].apply(lambda x: remove_stopwords(x))</pre><p>The results of the code above can be seen below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSEHj61KGSKNohBOoxca8w.png" /></figure><p>You can see that words like “you”, “my” and similar words got removed.</p><h4>3.4. Removing Unnecessary Words and Numbers</h4><p>It can be seen that words like “user” and “url” were the predominant words. Essentially, “user” represents the case of someone being tagged and “url” represented a case where the user included an external link to their tweet. These words won’t be necessary to our analysis; hence, I had to get rid of them.</p><p>I also got rid of numbers since they didn’t add any value to the tweets.</p><pre>##creating a fucntion to get rid of numbers <br>def number_remover(text):<br>  text= re.sub(r&#39;\d+&#39;, &#39;&#39;, text)<br>  return &quot; &quot;.join([word for word in text.split() if not word.isdigit()])<br><br>## appying the function to my dataframe<br>df_train[&quot;clean_tweet&quot;]= df_train[&quot;clean_tweet&quot;].apply(number_remover)<br><br>##creating a function to get rid of user and url<br><br>def text_remover(text):<br>  return &quot; &quot;.join([word for word in text.split() if word not in [&quot;user&quot;, &quot;url&quot;]])<br><br>##applying the function to my column<br>df_train[&quot;clean_tweet&quot;]= df_train[&quot;clean_tweet&quot;].apply(lambda x: text_remover(x))</pre><p>The result of the above processes is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*B8f1DuJ5LMdwp5wOuiZvIQ.png" /></figure><p>After the above preprocessing steps, I visualized my clean data frame, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*D4v6ytbfn8MGCf5BtTEdlg.png" /></figure><h3>4.Modelling</h3><p>With my clean dataset, the next step was to model. With this, I fine-tuned a pre-trained model. Pre-trained models refer to algorithms— called transformers — that have already been trained on a large corpus and then you can leverage these pre-trained models for various Natural Language Processes such as:</p><ul><li>Sentiment Analysis</li><li>Name Entity Recognition</li><li>Text Summarization</li><li>Text Generation and many more.</li></ul><p>I choose to fine-tune two pre-trained models:</p><ul><li><strong>DistilBert from Huggingface</strong></li><li><strong>Roberta from Facebook</strong></li></ul><p>In this section, I will walk you through how I finetuned my Roberta model together with how I handled the class imbalance.</p><blockquote><strong>Also, I will like to emphasize that I used Google Colab for the modelling since my PC doesn’t have the GPU capacity to run the fine-tuning process.</strong></blockquote><p>Having said that, below are the libraries I used for my modelling:</p><pre>##for handling path of my datasets<br>import os<br>from google.colab import drive<br><br>##for data handling:<br><br>import pandas as pd<br>import numpy as np<br><br>##for visuals-- just in case<br><br>import seaborn as sns<br>import matplotlib.pyplot as plt<br><br>from transformers import AutoTokenizer, AutoModelForSequenceClassification<br>import torch<br>from transformers import TrainingArguments<br>from scipy.special import softmax<br>from torch import nn<br>import torch<br>from transformers import Trainer<br><br>##modelling:<br><br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import f1_score<br>import transformers<br>from transformers import pipeline<br>from datasets import load_dataset<br>import nltk<br>nltk.download(&#39;punkt&#39;)<br><br>##others<br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)<br>import os<br>os.environ[&quot;WANDB_DISABLED&quot;] = &quot;true&quot;<br>pd.set_option(&quot;display.max_rows&quot;, None)<br>pd.set_option(&quot;display.max_columns&quot;, None)</pre><h4><strong>4.1. Fine-Tuning A Pre-trained Model (RoBerta)</strong></h4><p><strong>i.Reloading my Data</strong></p><p>After my data cleaning, I saved my data and then I reloaded it on a new notebook for my modelling. However, after reloading, I realized there were some missing values, and my best guess will be due to some encoding issues during saving.</p><p>Luckily, the missing values were just 29 values; therefore, I dropped them.</p><p><strong>ii. Splitting my Data</strong></p><p>Once the data was reloaded, the next step was to split it up into my train and eval set. I did the 80/20 split and also enabled the <strong>stratify </strong>feature, again, this is a classification project; therefore, the stratify there ensures that the labels are equally distributed in the split.</p><p>iii<strong>. Using the “datasets” Library</strong></p><p>This library has the load_dataset module which allows us to load our datasets in a format where we can sample batches during the training process. I achieved this with the code below:</p><pre>dataset= load_dataset(&quot;csv&quot;, data_files={&quot;train_set&quot;:&quot;train_set.csv&quot;, <br>&quot;eval_set&quot;:&quot;eval_set.csv&quot; }, encoding= &quot;ISO-8859-1&quot;)</pre><p><strong>iv. Tokenization</strong></p><p>Now we have our dataset ready, the next step is to tokenize the sentences. What this means is that we are going to break down the sentences into words, and then encode them/ convert them to numbers, which is the way the model can understand.</p><p>Before that, I had to make sure that I convert my labels from -1,0,1 to 0,1,2 respectively. This is because most pre-trained models tend to associate 0 to negative, 1 with neutral, and 2 with positive. Therefore, it is generally recommended that you do that.</p><p>The first step to tokenizing is to import a tokenizer specific to my model. With this I used the AutoTokenizer; however, it is worth noting that some models have their own tokenizer.</p><p>I used the code below:</p><pre>tokenizer= AutoTokenizer.from_pretrained(&quot;roberta-base&quot;)</pre><p>Also, I then went ahead to create a function to apply my tokenization and also map the label transformation I highlighted earlier, which is 0 for negative, 1 for neutral and 2 for positive.</p><pre>## our labels are-1, 0, 1 and we will like to transform them into 0,1,2 respectively<br><br>def transform_labels(input):<br>  label= input[&quot;label&quot;]<br>  num =0<br><br>  if label== -1:<br>    num= 0<br>  elif label== 0:<br>    num =1<br>  elif label == 1:<br>    num = 2<br>  return {&quot;labels&quot;: num}<br><br>def tokenize(example):<br>  return tokenizer(example[&quot;clean_tweet&quot;], padding= &quot;max_length&quot;, truncation=True, return_tensors= &quot;pt&quot;)</pre><ul><li>I am telling my tokenizer to target the clean_tweet feature of each dataset</li><li>padding= “max_length”, Essentially, I am telling the tokenizer to maximize the padding to the max length of the model.</li><li>truncation= True, with this I am telling the tokenizer to cut off any words that are more than the max words of the model.</li><li>return_tensors= “pt” is just telling the model to return Pytorch Tensors.</li></ul><p>This was the final look at the dataset after applying the function above as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hdLyCN8o4lyZDUChJcRmdA.png" /></figure><p><strong>v.Importing Model</strong></p><p>The next step was to import the model and also, go ahead and model using the code below:</p><pre>model= AutoModelForSequenceClassification.from_pretrained(&quot;roberta-base&quot;, <br>num_labels= 3)</pre><p>It is worth noting that I also set my evaluation metric to an f1-score since we are dealing with an imbalanced dataset.</p><pre>def compute_metrics(pred):<br>  labels = pred.label_ids<br>  preds = pred.predictions.argmax(-1)<br>  f1 = f1_score(labels, preds, average=&quot;weighted&quot;)<br>  return {&quot;f1&quot;: f1}</pre><p>Also, I use the following arguments during my training:</p><ul><li>I fine-tuned the model through 3 epochs</li><li>I saved and evaluated the model through each step</li></ul><p>Finally, I used the seed shuffle to have a fixed batch size throughout the training and eval process.</p><p>Below are the results after the training and evaluation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLmMtJSLzZPGrKiHm1dW4w.png" /></figure><p><strong>vi. Handling Class Imbalance</strong></p><p>Handling class imbalance I had to assign class weights to each class with the class with the lower distribution having a higher weight than the class with the higher distribution.</p><p>Afterwards, I created a custom class to feed the class weight to the model.</p><p>Below are the codes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjWXUfFWv3LExAthpC-FqA.png" /></figure><p>This was the performance of the model afterwards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aha97u_aHANgKtpcEPgaLA.png" /></figure><ul><li>It is worth noting that my DistilledBert achieved an F1 score of 0.71; however, I went through the normal training process and the class-weight process with Roberta which is why I showed it. Below is an image of DistilBert’s performance</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/821/1*2dQVbugC-28zVkmjp33J0w.png" /></figure><h3>5. Deployment</h3><p>The fine-tuned model was pushed to HuggingFace, and then I created an app using Streamlit, which I eventually deployed on Streamlit Cloud.</p><p>You can check out the app <a href="https://huggingface.co/spaces/gArthur98/distill_sentiment_classifier"><strong>by clicking on this link</strong></a>.</p><p>Also, kindly do well to<a href="https://github.com/Greg-Art/Streamlit-App-Sentiment-Analysis"> <strong>check out the GitHub repository </strong></a>of the project.</p><p>Finally, you can check out the deployed model <a href="https://huggingface.co/gArthur98"><strong>on my HuggingFace profile</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c191b5da61a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Build and Deploy A Simple ML App With Just Python Functions: No CSS/HTML Required.]]></title>
            <link>https://gregoryarthur98.medium.com/lets-build-and-deploy-a-simple-ml-app-with-just-python-functions-no-css-html-required-6a275955735c?source=rss-768dee559ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a275955735c</guid>
            <dc:creator><![CDATA[Gregory Kwaku Arthur]]></dc:creator>
            <pubDate>Tue, 27 Jun 2023 08:00:57 GMT</pubDate>
            <atom:updated>2023-07-20T07:00:38.002Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlHWaAmZifeoGz1KqdQT3g.png" /><figcaption>Image Credit: GeekLearning</figcaption></figure><h3>Let’s Build and Deploy A Simple ML App With Just PythonFunctions: No CSS/HTML Required.</h3><p>Hello, and welcome back again. If this is your first time here, then do well to <a href="https://medium.com/@gregoryarthur98/maximizing-customer-retention-a-churn-prediction-analysis-for-vodafone-43640fb5fb0f"><strong>read my third article</strong></a>, as this post is related to it. Nonetheless, you can still proceed to read this post, and you would still gain valuable insights from this post. Also, you can <a href="https://huggingface.co/spaces/gArthur98/Churn-app">access the app by clicking on this link</a>.</p><p>Just as the title suggests, I will be walking you through how I was able to build a simple interface for my classification model. In my third article, I built various classification models, and then I decided to build an interface for my model.</p><p>Before I begin, I want to say a big thank you to <a href="https://www.linkedin.com/school/azubi-africa/mycompany/"><strong>Azubi Africa</strong> </a>for helping me learn all these skills at no upfront cost. I recommend you join their next cohorts if you are interested in learning data science/data analytics.</p><p>With that out of the way, let’s dive into business.</p><h3>Outline:</h3><ul><li>What is Gradio?</li><li>Backend</li><li>Front End</li><li>Deployment</li><li>Conclusion</li></ul><h3>1.What is Gradio?</h3><p>Gradio is an open-source framework which allows users to create graphical user interfaces for their machine-learning models by wrapping their models around functions. Gradio provides users with a simple interface, allowing for quick deployment of models.</p><p>Gradio works by accepting three parameters:</p><ul><li>Your Function (fn)</li><li>Your Input (inputs)</li><li>Your Output (outputs)</li></ul><p>Yes, it is that simple.</p><h3><strong>2.Backend</strong></h3><p>Now, how did I get my app to work? Well, first of all, I will like to state that I created a pipeline to streamline my modelling process, so everything was a breeze. If you are new to machine learning, I highly recommend you learn how to build pipelines as it makes everything easy from modelling to deployment.</p><p>Okay, back to business.</p><h4><strong>Step 1:Dumping and Loading My Pipeline</strong></h4><p>This is what my pipeline looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*l6Ut6HYqQnZmYvFLKne4iA.png" /></figure><p>I started by saving (“dumping”) my model from my notebook using Joblib. the code for this was:</p><pre>dump(HP_LRP, &quot;Desktop/models/LR.joblib&quot;)</pre><p>After the model, was saved, I copied it into the directory “models” on vscode. I reloaded it again and then tested it</p><pre>model= joblib.load(&quot;models/LR.joblib&quot;)</pre><h4><strong>Step 2: Creating my Secondary Function</strong></h4><p>Since my model is a binary classification model, it will be returning either a 0 or 1; however, I wanted it to return a string saying: “Customer will Churn” or “Customer will not churn”. To do this, I created a simple function which will accept a number and then return an output based on the number received. The code is displayed below:</p><pre>def classify(num):<br>    if num == 0:<br>        return &quot;Customer will not Churn&quot;<br>    else:<br>        return &quot;Customer will churn&quot;</pre><h4><strong>Step 3: Creating my Primary Function</strong></h4><p>My primary function refers to the function I used for making my prediction.</p><p>To do this, I started by creating a function for my prediction. Here is a laid-out procedure of how it was done:</p><ul><li>I declared my parameters. I ensured that the function accepted the same number and name of inputs as I trained my model on.</li></ul><pre>def predict_churn(SeniorCitizen, Partner, Dependents, tenure, InternetService,<br>                  OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,<br>                  StreamingTV, StreamingMovies, Contract, PaperlessBilling,<br>                  PaymentMethod, MonthlyCharges, TotalCharges):</pre><ul><li>Since I trained my model using a data frame, I created a list of my input parameters and then transformed the list into a data frame (input_df).</li></ul><p>as shown below:</p><pre>  input_data = [<br>        SeniorCitizen, Partner, Dependents, tenure, InternetService,<br>        OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,<br>        StreamingTV, StreamingMovies, Contract, PaperlessBilling,<br>        PaymentMethod, MonthlyCharges, TotalCharges<br>    ]    <br>##I am changing my features into a dataframe since that is how I trained my model<br><br>    input_df = pd.DataFrame([input_data], columns=[<br>        &quot;SeniorCitizen&quot;, &quot;Partner&quot;, &quot;Dependents&quot;, &quot;tenure&quot;, &quot;InternetService&quot;,<br>        &quot;OnlineSecurity&quot;, &quot;OnlineBackup&quot;, &quot;DeviceProtection&quot;, &quot;TechSupport&quot;,<br>        &quot;StreamingTV&quot;, &quot;StreamingMovies&quot;, &quot;Contract&quot;, &quot;PaperlessBilling&quot;,<br>        &quot;PaymentMethod&quot;, &quot;MonthlyCharges&quot;, &quot;TotalCharges&quot;<br>    ])</pre><ul><li>The next step was to make my prediction, and with this, I simply pass the input_df through my model. Then I passed the output (either 0 or 1) through my secondary function (classify)</li></ul><p>the code is shown below:</p><pre>pred = model.predict(input_df) ##I am making a prediction on the input data.<br><br>    output = classify(pred[0])</pre><ul><li>Finally, I went ahead to specify my output to return the classification result plus the output from my classify function.</li></ul><p>as shown below:</p><pre> if output == &quot;Customer will not Churn&quot;:<br>        return [(0, output)]<br>    else:<br>        return [(1, output)] </pre><h3>3.Front End</h3><p>In this section, I will walk you through how I created my beautiful output.</p><p>With this, I used the following Gradio Features:</p><ul><li>Gradio Blocks: gr.Blocks()</li><li>Gradio Radio Buttons: gr.Radio()</li><li>Gradio Number Inputs: gr.inputs.Numbers</li><li>Gradio Slider: gr.slider()</li></ul><h4>Creating My Front-End Gradio Blocks:</h4><p>Gradio blocks is a Gradio feature that allows you to customize the layout of your GUI using various templates. I went for the simple Gradio Blocks layout.</p><p>So, how does it work?</p><p><strong>Step 1: Instantiate your Blocks Class</strong></p><p>This means saving your Blocks class into a variable. Also, I declared my theme.</p><pre>block= gr.Blocks(theme= &quot;freddyaboulton/dracula_revamped&quot;)</pre><p><strong>Step 2: Define my input and output parameters</strong></p><p>Once you are done, the next step is to declare your input and output parameters leveraging the various input and output features provided by Gradio.</p><p>The markdown also adds a header to my app.</p><pre>with block:<br>    gr.Markdown(&quot;&quot;&quot; # Welcome to My Customer Churn Prediction App&quot;&quot;&quot;)<br>    input=[gr.inputs.Slider(minimum=0, maximum= 1, step=1, label=&quot;SeniorCitizen: Select 1 for Yes and 0 for No&quot;),<br>        gr.inputs.Radio([&quot;Yes&quot;, &quot;No&quot;], label=&quot;Partner: Do You Have a Partner?&quot;),<br>        gr.inputs.Radio([&quot;Yes&quot;, &quot;No&quot;], label=&quot;Dependents: Do You Have a Dependent?&quot;),<br>        gr.inputs.Number(label=&quot;tenure: How Long Have You Been with Vodafone in Months?&quot;),<br>        gr.inputs.Radio([&quot;DSL&quot;, &quot;Fiber optic&quot;, &quot;No&quot;], label=&quot;InternetService&quot;),<br>......]<br><br><br>    output= gr.outputs.HighlightedText(color_map={<br>     &quot;Customer will not Churn&quot;: &quot;green&quot;,<br>     &quot;Customer will churn&quot;: &quot;red&quot;}, label= &quot;Your Output&quot;) <br></pre><p>With my output, I am assigning a colour to my output from my primary function.</p><p><strong>Step 3: Creating my Button</strong></p><p>The next step was to create a button to allow the user to see visualize their prediction once clicked.</p><p>Essentially, I am creating a button with the name “Predict”, and indicating that my output shows only if the button is clicked.</p><p>For this, I used the code below:</p><pre>predict_btn= gr.Button(&quot;Predict&quot;)<br>     <br>    predict_btn.click(fn= predict_churn, inputs= input, outputs=output)</pre><p><strong>Step 4: Launch</strong></p><p>The next step was to launch, and it worked!!</p><h3>4.Model Deployment</h3><p>Finally, I deployed the GUI on HuggingFace, and you can access the app by <a href="https://huggingface.co/spaces/gArthur98/Churn-app"><strong>clicking on this link</strong></a>.</p><p>Check out the GitHub repo for this project as well: <a href="https://github.com/Greg-Art/Gradio-App-for-Customer-Churn">https://github.com/Greg-Art/Gradio-App-for-Customer-Churn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a275955735c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leverage Streamlit to Build and Deploy a Multipage App For Your Regression Model Without…]]></title>
            <link>https://gregoryarthur98.medium.com/create-a-multipage-app-for-your-regression-model-without-using-css-html-django-f5b552b4a875?source=rss-768dee559ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5b552b4a875</guid>
            <dc:creator><![CDATA[Gregory Kwaku Arthur]]></dc:creator>
            <pubDate>Mon, 26 Jun 2023 17:58:22 GMT</pubDate>
            <atom:updated>2023-07-28T11:58:03.448Z</atom:updated>
            <content:encoded><![CDATA[<h3>Leverage Streamlit to Build and Deploy a Multipage App For Your Regression Model Without CSS/HTML/Django.</h3><p>Hello, everyone, welcome to my fourth article. In my previous articles, I developed machine learning models. However, we can all attest to the fact that these models can only be used if you have background knowledge in data science; therefore, I decided to build an interface and deploy one of my models so that everyone can use them — isn’t that awesome?</p><p>That being said, if you are non-technical you can go ahead and <a href="https://fbpforecast.streamlit.app/"><strong>just click on this link</strong></a> to use the app. However, if you want to learn how I built and deployed such an awesome app, you can follow along, as this article will highlight the detailed process.</p><p>With that out of the way, let’s dive into it:</p><h3>Outline:</h3><ol><li>What is Streamlit</li><li>Backend</li><li>Frontend</li><li>Model Deployment on Streamlit Cloud</li><li>Conclusion</li></ol><h3>1. What is Streamlit?</h3><p><a href="https://streamlit.io/">Streamlit</a> is an open-source Python framework that allows data scientists to develop graphical user interfaces (GUI) for their models. Streamlit also provides users with a cloud service for deploying their apps.</p><p>From the horse’s mouth:</p><blockquote>A faster way to build and share data apps</blockquote><p>Essentially with Streamlit, you can wrap your model and its components around various functionalities, and have people interact with it.</p><p>So, how is this done?</p><p>Let’s take a look.</p><h3>2.Backend</h3><p>Do not be scared by my use of the word “backend”, I am just trying to refer to how I was able to get my model to work.</p><p>Okay…</p><p>Before I delve into this section, I will like to state that the model I chose was Facebook Prophet with extra regressors and an embedded holiday effect — do not worry you will understand soon.</p><p>From my <a href="https://medium.com/@gregoryarthur98/building-accurate-models-for-unit-sales-prediction-in-favorita-stores-using-time-series-forecasting-ff4b90eda30b">initial modelling</a>, I had the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*ViVnKKUDRHw1aWNPhPGq5w.png" /></figure><p>So, why Facebook Prophet (FBP)?</p><p>I choose FBP for two main reasons:</p><ul><li>I couldn’t maximize the modelling power of my ARIMAX model since I didn’t have the computational power to run my model with period 365. However, it did really well using a period of 12.</li><li>The decision tree model is a pure machine learning algorithm which isn’t ideal for time series. Since it can&#39;t give us a decomposition of our time series and also, it cannot generate uncertainty intervals.</li></ul><p>So, since the RMSLE of my FBP with extra regressor was 0.202, I decided to go with it.</p><p>Note: An RMSLE of 0.202 is relatively good as well.</p><h4>2.1 Modelling</h4><p>To get my code, first I had to instantiate my model and then declare my holiday and extra regressors. This was achieved by using the code below.</p><p><strong>a.Instantiating my model:</strong></p><pre>model_2= Prophet(yearly_seasonality= True,<br>                 seasonality_mode= &quot;multiplicative&quot;, seasonality_prior_scale=25)</pre><p><strong>b.Adding my Holiday Effect:</strong></p><p>The dataset I used had some features which contained holiday information about Ecuador. However, Facebook Prophet had an embedded Holiday Feature, which allows you to incorporate the effect holidays have on a prediction.</p><p>Therefore, I decided to leverage FBP’s inbuilt holiday effect to make my modelling and interface simple. With this, I dropped the various features which contained the holiday information, since, FBP will take care of that.</p><p>This was achieved with the code:</p><pre>model_2.add_country_holidays(country_name= &quot;ECU&quot;)</pre><p>Note: “ECU” is the three-letter abbreviation of Ecuador.</p><p><strong>c.Adding Extra Regressors:</strong></p><p>Besides the holiday effect, there were some features I had to add (“transactions”, and “onpromotions”) to boost the performance of the model. I achieved this with the code below:</p><pre><br>for col in train_2.drop(columns=[&quot;ds&quot;, &quot;y&quot;], axis= 1):<br>    model_2.add_regressor(col, standardize=True, prior_scale=20)</pre><ul><li>the “ds” refers to my date column</li><li>the “y” refers to my sales column (my target)</li></ul><p>Afterwards, I fitted and predicted my test data and the performance was good.</p><h4>2.2 Making the Model Work</h4><p>Now, to make my model work, I had to save and reload my model using Joblib. The saved model can be found in the (models) folder of my repository.</p><p>I executed my backend codes on the “forecast.py” page; so, do well to check it out if you need any extra information.</p><p>But to sum it all up, I did the following:</p><p><strong>a.Defined my inputs</strong></p><p>Essentially, I was trying to set how my model will receive the user’s input.</p><p>The st.header() is a Streamlit attribute for creating headers.</p><p>To create my inputs, I used the “st.<strong>number_input</strong>” attribute to allow the user to input information about the transactions and promotions. I also used the “st.<strong>date_input</strong>” to allow the user to input the dates for their sales forecast.</p><p>The code is below:</p><pre>st.header(&quot;Make a Forecast Here: &quot;)<br>ds= st.date_input(label= &quot;Please enter the date you would want to forecast&quot;)<br>transactions= st.number_input(label= &quot;Please enter the total number of expected transactions&quot;)<br>onpromotion= st.number_input(label= &quot;Please enter the total number of expected items to be on promotions&quot;)</pre><p><strong>NOTE: I am limiting my inputs to only the features I used in training my model.</strong></p><p><strong>b.Converting input to Dataframe</strong></p><p>Since I trained my model using a data frame, I have to concat and transform the user’s input into a data frame, and to do this, I used the code below:</p><pre>input_data= [ds, onpromotion, transactions]<br>inputs= pd.DataFrame([input_data], columns=[&quot;ds&quot;, &quot;onpromotion&quot;, &quot;transactions&quot;])</pre><p><strong>c.Making the Prediction</strong></p><p>Now the data is ready, and the model can make a prediction. To do this, I passed the “inputs” variable through my model. The code is displayed below:</p><pre>forecast= model.predict(inputs)<br>forecast_value= forecast[&quot;yhat&quot;]<br>forecast_output = f&quot;Your sales on {ds} will be ${forecast_value.values[0]:.2f}&quot;</pre><p>The forecasted sales for Facebook Prophet always appear as “<strong>yhat</strong>”, which is why I have that filtered out.</p><p>For the forecast_output, I am trying to specify a string output for my forecast and date.</p><p>d.<strong>Making my Forecast Appear</strong></p><p>Now, we have our forecast output stored, the next step was to display the output. To do this, I followed the under-listed processes:</p><ul><li>Created a submit button</li><li>Used a for loop to display the results only when the Submit button is clicked on.</li><li>Also, if the Submit button isn’t clicked on then an empty data frame and the statement “Your sales on …… will be …..” will be displayed.</li></ul><p>The code for executing the above processes is displayed below:</p><pre>output= st.button(&quot;Submit&quot;)<br><br><br>st.subheader(&quot;Your Sales Forecast is Displayed Below: &quot;)<br><br>##telling my model to return the yhat if the submit button is clicked<br>if output:<br>    st.write(forecast_output)<br>else:<br>    st.write(&quot;Your sales on ...... will be .....&quot;)<br><br>st.subheader(&quot;Your Forecast Dataframe is Displayed Below: &quot;)<br>##creating an output for my output<br>if output:<br>    st.write(forecast)<br>else:<br>    st.write(forecast_emp)</pre><p>Below is a picture of my forecast page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wgKX7qmEXR1YivIeS4q9g.png" /></figure><h4><strong>3.Front-End</strong></h4><p><strong>3.1 Streamlit Features</strong></p><p>For my front end, I made use of some Streamlit’s attributes including:</p><ul><li>st.title(): For my titles</li><li>st.write(): For my outputs; both images and text</li><li>st.plotly_chart(): For displaying interactive plotly charts</li><li>st.subheader(): For subheaders</li><li>st.button(): For creating clickable buttons</li></ul><p>For an in-depth understanding of the features I used, kindly read <a href="https://docs.streamlit.io/">Streamlit’s documentation</a>.</p><p><strong>3.2 Multipage Feature</strong></p><p>Now how did I create a multi-page interface like this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l623_O2_8NhwC6k0FxCXlw.jpeg" /></figure><p>Well, this was simple. I leveraged Streamlit’s multipage feature. To replicate this, you can follow the steps below:</p><ul><li>First, have a main.py file. This is the file that will be your welcome page. The name of the file can be anything. However, ensure that you define your sidebar in this file. I did this with the code below:</li></ul><pre>st.set_page_config(page_title=&quot;Welcome to Greg&#39;s Time Series Forecast App&quot;, <br>                   page_icon=&quot;👋&quot;<br>                   )<br><br>##and <br><br>##setting my sidebar<br><br>st.sidebar.success(&quot;Please Select the Page&quot;)</pre><ul><li>When done, create a folder and name it “pages”. This folder will contain your auxiliary web pages. After creating the folder, drag and drop any auxiliary webpage you want to see and you would have it displayed.</li></ul><p>Below is an image showcasing how I did mine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uN6pN2xqXRnKledwAS_7ZQ.png" /></figure><p>From the image above, Welcome.py is my main file and the Forecast Page, Explore, and About are my auxiliary pages.</p><p>Below is an image of each auxiliary page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDsuK2mK4gX95h47XDb_5w.png" /><figcaption>A Picture of the Explore Page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCrPlfZIcvSEK4IXL0SP2g.png" /><figcaption>My About Page</figcaption></figure><p>Since I have already shared screenshots of my Forecast and Welcome Page, I won’t display them again.</p><p>Also, I will like to state that, I replicated the form in my About Page using this video by the Data Professor, so <a href="https://www.youtube.com/watch?v=YaFvCwjk-_A&amp;t=177s">do well to check his channel out</a>.</p><p>For any other aesthetics, do well to <a href="https://github.com/Greg-Art/Streamlit-App">check out my repository for this project on GitHub</a>.</p><h3>4.Deployment</h3><p>I deployed my app on <a href="https://streamlit.io/cloud"><strong>Streamlit Cloud</strong></a>. Also, <a href="https://fbpforecast.streamlit.app/"><strong>click here</strong></a><strong> </strong>to view on website fully hosted on Streamlit Cloud.</p><p>The deployment process was simple:</p><p><strong>Step 1: Create a Streamlit Cloud Account</strong></p><p>Streamlit Cloud allows you to create an account with either your GitHub or your Email. I highly recommend that you create an account with your GitHub since it makes it easy for you to access any repository you want to deploy.</p><p><strong>Step 2: Tap on the new app feature</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oupK0wAg_7i1b2HdOxlL-Q.jpeg" /></figure><p>Once, you have created your account it is time to deploy your awesome app, and to do this, click on the new app feature as highlighted in the image above.</p><p><strong>Step 3: Input the necessary information</strong></p><p>Upon clicking on the “New app” button you should see a page like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJ0ol_LwvDajLa6rPqanCg.png" /></figure><p>Do not get scared, all you have to do is to:</p><ul><li>Insert the link of the repository you want to create an app for. Ensure that you have your requirements.txt file available.</li><li>Then select the branch. It should switch automatically from “master” to “main”. So, you do not need to worry; however, you can manually change it to the respective branch.</li><li>The next step is to select the path of your app. What you want to do here is to input the name of the Python file your interface was built in. If you are building a multi-page app, it should be your main Python file.</li><li>Finally, input the URL you want your site to have. The URL length should be between 6 to 67 characters. Once you see text with the inscription: “URL available”, then you are good to go.</li></ul><p><strong>Step 4: Click on Create app and viola!! Your app is ready.</strong></p><h3>5.Conclusion:</h3><p>Streamlit makes creating websites easy. Therefore, if you are a data scientist looking to create an MVP or a simple GUI for your model, then you should definitely leverage Streamlit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5b552b4a875" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing Customer Retention: A Churn Prediction Analysis for Vodafone]]></title>
            <link>https://gregoryarthur98.medium.com/maximizing-customer-retention-a-churn-prediction-analysis-for-vodafone-43640fb5fb0f?source=rss-768dee559ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/43640fb5fb0f</guid>
            <dc:creator><![CDATA[Gregory Kwaku Arthur]]></dc:creator>
            <pubDate>Sun, 28 May 2023 17:27:04 GMT</pubDate>
            <atom:updated>2023-07-20T07:54:48.689Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*xv1zXArW5maLrjhA.jpg" /><figcaption>Image Credit: Voxco</figcaption></figure><p>Greetings, everyone, and a warm welcome to my third project. This particular project focuses on customer churn within Vodafone PLC. I have strived to strike a balance between simplicity for data analysis newbies and technical depth for data science professionals. I kindly request your undivided attention as I present numerous captivating insights that are sure to pique your interest.</p><p>The outline of this post will follow the CRISP-DM framework, which includes:</p><ul><li>Business Understanding</li><li>Data Understanding</li><li>Data Preparation</li><li>Modelling</li><li>Hyper-parameter Tuning</li><li>Evaluation</li></ul><p>Note, we won’t cover the Deployment and Model management stage of the CRISP-DM framework in this post.</p><p>Besides using the framework as a guideline, I will also, cover the following:</p><ul><li>Hypothesis testing</li><li>Conclusion</li></ul><p>Please find a link to:</p><ul><li><a href="https://github.com/Greg-Art/Customer_Churn.git">The Notebook on GitHub</a></li><li><a href="https://app.powerbi.com/groups/63f57d54-6638-49d3-9175-87a59becd300/reports/8aae8740-d952-457f-bc00-c8d1d87471be/ReportSection?experience=power-bi">The PowerBI Dashboard for the project</a>: A screenshot of the dashboard is below.</li></ul><p>With that out of the way, let’s dive into the project.</p><h3>1. Business Understanding:</h3><p>Profit is the driving force for every business, and one of the ways businesses can maximize profits is through customer retention. Ensuring customer retention should be a core part of every business because <a href="https://www.forbes.com/sites/forbesbusinesscouncil/2022/12/12/customer-retention-versus-customer-acquisition/#:~:text=In%20fact%2C%20studies%20suggest%20that,customers%20versus%20retaining%20current%20ones.">according to a study by Forbes</a>, acquiring a new customer can cost businesses 5 to 7 times the amount it requires to keep an old customer. Therefore, as a company looking to maximize profit and minimize expenditure, it is imperative that you increase customer retention, and minimize churn.</p><p>For those of you new to the term “churn”, it refers to the process of customers leaving one company for another; this could be halting the use of one or more products/services of the company or just leaving the company. This project aimed to leverage classification models to predict the likelihood of a customer leaving (Churning) Vodafone.</p><h3>2. Data Understanding:</h3><h4>2.1.Dataset Overview</h4><p>The file for this project came in a CSV format, and when I loaded it into Pandas, I saved it into a variable called “df”. After loading, I performed a quick overview and per the overview, the data contained 7043 rows and 21 columns, as displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*PRnsyFcpRCDHXNabuqaKfg.png" /><figcaption>fig.1</figcaption></figure><p>From the overview, we can see that there seem to be no missing values and there everything seems right.</p><p>I proceeded to take a look at the actual data frame to see what was happening. The images are displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UW8jWTjKVMd5_U748CxYJg.png" /><figcaption>fig 2(a)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tl1i3WtDog-CXIu09GMlyQ.jpeg" /><figcaption>fig 2 (b)</figcaption></figure><p>After going through the dataset, I realized that the Total Charges column had quantitative values (numerals); however, the initial overview detected the column to be an object data type (meaning it contains non-numerals). Therefore, we will have to investigate the column for any disparities.</p><p>I employed two different approaches for this task:</p><ul><li>Initially, I utilized the Fillna method during my exploratory data analysis (EDA).</li><li>Subsequently, I incorporated a custom transformer into my pipeline as the second method to handle the missing values.</li></ul><h4>2.2.Data Description</h4><p>The next step was to describe the dataset using the “.describe()” method to give a descriptive overview of our data. I performed two descriptions, and this was because of the TotalCharges column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxVFB7EmwRUprITM05qQ-w.png" /><figcaption>fig 3</figcaption></figure><p>Note, the NaN means Not a Number, and for columns that have NaN, it means they weren’t numeric values; hence, no statistical calculations could be made on them.</p><p>From the description, I gained some insights, which included:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Grs9vEQICIk0vgxgUQ0gg.png" /></figure><h4>2.3 Data Exploration:</h4><p>In this section, I will be using various visualizations to draw insight from the data to help me understand it much better. However, before exploring the dataset, I did three things:</p><ul><li>Made a copy of the dataset, to allow me to use one for my exploratory Data Analysis and allow me to use the other for my modelling. I used the copy (df_copy) for my analysis and the original data frame (df) for my modelling.</li><li>I had to convert my Total Charges attribute to a numerical datatype using the code below:</li></ul><pre>df_copy[&quot;TotalCharges&quot;]= pd.to_numeric(df_copy[&quot;TotalCharges&quot;], errors= &quot;coerce&quot;)</pre><p>The errors= “coerce” section will convert any errors encountered to NaN, making it easy for any further analysis. After the conversion, I realized there were 11 missing values as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlaX1H90lq7gC1Tb2JP0Kw.png" /></figure><p>I replaced the missing values with the mean value of the “TotalCharges” feature using the code below:</p><pre>df_copy.fillna(value= df_copy[&quot;TotalCharges&quot;].mean(), inplace= True)</pre><ul><li>Finally, I dropped the CustomerID column, since it contained no inherent information relevant to my analysis.</li></ul><h4>2.3.1.Univariate Analysis:</h4><p>The univariate analysis involves analyzing just one column.</p><p><strong>2.3.1(a). Checking the distribution of attributes of the dataset</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtoEhb-xnINVE1mrGRta7Q.png" /><figcaption>Distribution of the various numeric attributes of the dataset</figcaption></figure><ul><li>We can see our SeniorCitizen attribute is highly right-skewed; meaning most individuals in that sample are non-senior citizens</li><li>Our tenure and TotalCharges attributes are slightly right-skewed</li><li>Our MonthlyCharges attribute is a bit right-skewed</li></ul><p><strong>2.3.1(b). Using A Boxplot to Check For Outliers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*njyO2JSboriiROOh6b-wlg.png" /></figure><p><strong>2.3.1(c). Checking the distribution of attributes in my Label</strong></p><p>And with this, I started by exploring the “Churn” column. I wanted to see the distribution of the “Yes” vs “No” in my label (the column I want to predict). I plotted a pie chart using Plotly Express and I got the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*-rB5uXmuRPw5uXbq_hL2iA.png" /><figcaption>fig 4.</figcaption></figure><p>From this image, we can see that non-churners outnumber the churners; hence there is some sort of data imbalance, which we will have to deal with since the goal of this project is to predict churners.</p><p><strong>2.3.1(d)Univariate of Categorical Columns with Respect To Churn</strong></p><p>I then went ahead to see the various categorical features varied with the Churn column. I used the for loop below to loop through the categorical features:</p><pre>for  col in df_copy.drop([&quot;Churn&quot;, &quot;tenure&quot;, &quot;MonthlyCharges&quot;, &quot;TotalCharges&quot;], axis= 1):<br>    fig_2= px.histogram(df_copy, color= &quot;Churn&quot;, x= col, <br>title= f&quot;Count of {col}, with respect to Churn&quot;, <br> color_discrete_sequence=random.sample([&quot;red&quot;, &quot;pink&quot;, &quot;blue&quot;, &quot;green&quot;], k=2))<br>    offline.iplot(fig_2)</pre><p>This gave me an insight into the data; however, I realized that this didn’t give me a standardized representation of my data. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*W_yoIkuPaRlaggw0nNX7Ww.png" /><figcaption>fig 5</figcaption></figure><p>The disparity in population sizes may lead to the misconception that non-senior citizens are churning more than senior citizens. This is primarily because the non-senior citizen group has a larger representation in the dataset compared to the senior citizen group. However, percentage-wise, senior citizens were churning more than non-senior citizens. As shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*R3CFE3PaCZM5gfetbgMzCg.png" /></figure><p>From the percentage comparison, senior citizens churned more than non-senior citizens, which is a more standardized representation of the column.</p><p>Both the count and percentage-wise comparison was executed on all categorical columns using a for loop. And for the percentage-wise comparison, I used the code:</p><pre><br>for col in df_copy.drop([&quot;Churn&quot;, &quot;tenure&quot;, &quot;MonthlyCharges&quot;, &quot;TotalCharges&quot;], axis= 1):<br>    churn_by_col = df_copy.groupby(col)[&#39;Churn&#39;].value_counts(normalize=True).mul(100).rename(&#39;percent&#39;).reset_index()<br>    fig_3 = px.bar(churn_by_col, x=col, y=&#39;percent&#39;,color=&quot;Churn&quot;, text=&#39;percent&#39;, <br>                   title= f&quot;Percentage of: {col} with respect to Churn&quot;, <br>                      color_discrete_sequence=random.sample([&quot;chartreuse&quot;,&quot;darkblue&quot;,&quot;darkviolet&quot;,&quot;aqua&quot;,<br>                                                             &quot;aquamarine&quot;, &quot;beige&quot;, &quot;burlywood&quot;], k=2) )<br>    fig_3.update_traces(texttemplate=&#39;%{text:.2f}%&#39;, textposition=&#39;outside&#39;)<br><br>    offline.iplot(fig_3)</pre><p>One interesting thing I realized was that most of the customers that churned were customers that had a tenure between 0–11 months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*urzLUcFPDEgPTfiK0wSXrw.png" /></figure><p><strong>2.3.1(e)Univariate of Numerical Features with Respect To Churn</strong></p><p>I proceeded to visualize how my numerical features varied with my label.</p><p><strong>i.For Monthly Charges, I got the below image:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*GwQJgyRoIMFASimOtoEomA.png" /><figcaption>Monthly Charges with respect to Churn</figcaption></figure><ul><li>There is high brand loyalty among customers who pay a monthly charge between 0 to $30.</li><li>Also, there was a high number of churners among customers that paid a monthly charge between $70 to $110.</li></ul><p>ii. <strong>For TotalCharges I Got The Image Below</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*gJXHD6okB5-IdHnD5gPBog.png" /></figure><ul><li>It can be seen from the image above that most of Vodafone’s loyal customers pay a total charge between 0 and $2000.</li><li>Similarly, most churners paid a total charge between 0 and $2000.</li></ul><p><strong>From the univariate analysis, I came up with some points:</strong></p><ul><li>Individuals with 0 to 11 months of use are most likely to churn; hence Vodafone might want to target customers in those tenure brackets.</li><li>Individuals with electronic checks churn out the most</li><li>Individuals on the fibre optics plan had the highest churn</li><li>Individuals who paid via electronic check churned more.</li><li>Individuals with paperless billing churned more.</li><li>Individuals on a month-to-month plan churned more.</li><li>Female customers churned more than male customers</li><li>Even though there were more non-senior citizens than senior citizens (from our count plot), senior citizens churned more percentage-wise. This could be because of old age, death or other factors.</li><li>Customers with no dependents are most likely to churn</li><li>A high number of individuals paying monthly charges between $70 to $110 churned the most.</li></ul><h4>2.3.2 Bivariate Analysis</h4><p>The idea here is to compare two columns and see the relationship they have or how they affect each other.</p><p>I performed various bivariate analyses to gain some insight, and these include:</p><p><strong>2.3.2.1Monthly Charges vs Total Charges</strong></p><p>I performed a scatterplot to see how monthly charges varied with total charges, and from the plot below, we can see both attributes have a positive relationship.</p><p><strong>In simple terms</strong>: This means as monthly charges increase the total charges increase. Also, we can see that as total charges increase, churn (the red dots) becomes less.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*8c5sF4JNX81oeI5WUB15HQ.png" /></figure><p><strong>2.3.2.2 Relationship Between Tenure and Monthly Charges</strong></p><p>I also wanted to see how the tenure affected total charges, and we can see that there is a positive relationship as well.</p><p><strong>In simple terms</strong>: As tenure increases the total charges increase as well. However, we can see that for tenure, the churn is more during the first 19 months, and it becomes less as the customer spends more time with the company.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*weF4aXlb0M9Jc7KecAnI0w.png" /></figure><p><strong>2.3.2.3. Senior Citizens and Total Charges:</strong></p><p>I realized that even though senior citizens were churning more, on average, senior citizens tend to spend more than non-senior citizens — the keyword is on average.</p><p><strong>In simple terms</strong>: This means when you consider a single senior citizen&#39;s spending and compare it to a non-senior citizen’s spending, that of the senior citizen is more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*u4wQ-g9wksVUMEdnqnhizw.png" /></figure><p><strong>2.3.1.4 Relationship Between Total Charges and Churn With Respect To Contract</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*dZJ4NnQnSLNNbz09D89PVA.png" /></figure><p>Notes:</p><p>- generally, churners were paying more total charges than non-churners</p><p>For No Churn:</p><p>- 50% of month-to-month customers who didn’t churn are spending between $223 and $2,254.223.</p><p>- 50% of Vodafone customers who are on a one-year plan and haven’t churned spend between $938 and $4598</p><p>- 50% of Vodafone customers who are on a two-year plan spend between $1270 and $5962.</p><p>For Yes Churn:</p><p>- 50% of Vodafone customers who were on a month-to-month plan and churned spent between $94 and $1654.825.</p><p>- 50% of Vodafone customers who were on a one-year plan and churned spent between $2354 and $5916.</p><p>- 50% of Vodafone customers who were on a two-year plan and churned spent between $4554 and $7203. <br>.</p><p>For Outliers:</p><p>- A lot of customers who are on a month-to-month plan spent more than $5295, which is far more than what the average customer from that sample is paying.</p><p>- Similarly, a lot of churners on a month-to-month plan were spending more than $3994, which is far more than what the average customer from that sample is paying.</p><p><strong>2.3.2.5 Relationship Between Tenure and Churn with Respect to Contract Type</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*xgS1WAafClitZL-odG2F3w.png" /></figure><p>Notes:</p><p>For No Churn:</p><p>- 50% of month-to-month customers who didn’t churn currently have a tenure between 5 months and 33 months with the median tenure being 16 months.</p><p>- 50% of Vodafone customers who are on a one-year plan are on their 26th to 58th month. This shows most of them have renewed their service with the company since one year-plan will last for 12 months.</p><p>- 50% of Vodafone customers who are on a two-year plan are on their 48th to 71st month.</p><p>For Yes Churn:</p><p>- 50% of Vodafone customers on a month-to-month plan and churned spent only 2 to 21 months with the company.</p><p>- 50% of Vodafone customers on a one-year plan and churned spent only 33 to 59 months with the company.</p><p>- 50% of Vodafone customers on a two-year plan and churned spent only 51 to 70 months with the company.</p><p>For Outliers:</p><p>- For No Churn, quite a number of customers who were on a two-year plan — as displayed by the dots below the lower whiskers — only had a tenure between 0 and 13 months. This means that these customers have newly subscribed to the two-year plan; hence, their low tenure.</p><p>- It can also be seen that some churners who were on month-to-month contract plans spent more than 50 months with the company before churning.</p><ul><li>Only two customers considered as churners on a two-year contract spent less than 39 months with the company.</li></ul><h4><strong>2.3.3 Multivariate Analysis:</strong></h4><p><strong>2.3.3.1. Heatmap of All Numeric Features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*ByOVxSRQR2JeqgGbKIDJHA.png" /></figure><p><strong>2.3.3.2 Relationship Between Monthly Charges and Churn With Respect to Contract</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*442toQv0Q8JlY7s4ah2HMA.png" /></figure><p>The idea here was to investigate which group of customers with respect to contract type churned the most. After my investigation, I realized that customers who were on a month-to-month payment plan and paid a monthly charge between $70 to $110 churned the most.</p><p><strong>2.3.3.3 Relationship Between Total Charges and Churn With Respect to Contract</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*E-1n9xKbIYDDCY6dL-pC3g.png" /></figure><ul><li>There was low churn among customers who are on long-term plans (One-year and two-year plans).</li><li>Most customers on a month-to-month plan who paid a total charge between $0 to $200 in total charges churned</li></ul><h4>2.3.4 Questions.</h4><p>I then went ahead to ask 5 questions I thought might be interesting to find answers to. These questions include:</p><p><strong>Question 1: Which Age Group Paid the Highest Total Charges?</strong></p><p>For this question, I used the code below:</p><pre><br>sum_agegroup= df_copy.groupby(&quot;SeniorCitizen&quot;).agg({&quot;TotalCharges&quot;: &quot;sum&quot;}).reset_index()<br><br>sns.barplot(x= &quot;SeniorCitizen&quot;, y= &quot;TotalCharges&quot;, data= sum_agegroup, palette= &quot;colorblind&quot;)<br><br>plt.title(&quot;TotalCharges per age group&quot;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*7sRtBoOwIaXaQ01hvMF7yA.png" /></figure><p>From this chart, we can see that non-senior citizens spend more money in terms of Total Charges than senior citizens.</p><p>In simple terms: This means if you look at each age group as a group, non-senior citizens spend more than senior citizens. And this makes sense cause non-senior citizens outnumber senior citizens.</p><p><strong>Q2. Which Gender Recorded the Highest Churn?</strong></p><p>For this question, I used the code below:</p><pre>churners= df_copy[df_copy[&quot;Churn&quot;]== &quot;Yes&quot;] ##filtering the churners out<br><br>##ploting the chart <br><br>fig_6= px.histogram(x=&quot;gender&quot;, data_frame=churners, color= &quot;gender&quot;, color_discrete_sequence=[&quot;teal&quot;, &quot;grey&quot;],<br>             title= &quot;Plot of the Occurence Of Churn Across the Various Gender&quot;)<br><br>offline.iplot(fig_6)</pre><p>The code gave me the answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*XDtDB2RviB9ZwZrfppwAYw.png" /></figure><p>It was unveiled that female customers churned more than male customers.</p><p><strong>Question 3: Which Internet Service Was Purchased the Most?</strong></p><p>For this question, I used the code below:</p><pre>## grouping the various values <br><br>internet_count= df.InternetService.value_counts().to_frame(name= &quot;count&quot;) <br><br>##plotting <br>fig_7 = px.scatter(internet_count, x=internet_count.index, y=&#39;count&#39;, size=&#39;count&#39;, color= internet_count.index, <br>                   <br>                hover_name=internet_count.index,<br>                 log_y=False, size_max=60, title= &quot;Plot of The Popularity Of The Various Internet Services&quot;)<br><br>offline.iplot(fig_7)</pre><p>The code above gave me the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*oJ3GdDU3Fmp8EvWA32A4iA.png" /></figure><p>We realized most Vodafone customers were on a fibre optic plan.</p><p><strong>Question 4: How Much Monthly and Total Revenue Do Churners Generate?</strong></p><p>I used the code below:</p><pre>##since we are looking at churners, we will use the churners dataframe we created earlier in question 2<br><br>money= churners.agg({&quot;MonthlyCharges&quot;: &quot;sum&quot;, &quot;TotalCharges&quot;: &quot;sum&quot;}).reset_index()<br><br>money.columns= [&quot;Charge&quot;, &quot;Amount&quot;] ##setting my columns<br><br>fig_8=px.bar(data_frame= money, x= &quot;Charge&quot;,<br>       <br>       y= &quot;Amount&quot;, title= &quot;Amount Generated By Churners In Terms&quot;, text= &quot;Amount&quot;, color= &quot;Charge&quot;,<br>             color_discrete_sequence= [&quot;yellow&quot;, &quot;black&quot;])<br><br>offline.iplot(fig_8)</pre><p>This gave me the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*xDi7LFDva--xifXp82gx8A.png" /></figure><p>We realized that churners brought in a total of 139,130.85 monthly, and a total of 2,862,926.9</p><p><strong>Question 5: Which Payment Method is the Most Popular?</strong></p><p>For this question, I used the code below:</p><pre>sns.countplot(x=&quot;PaymentMethod&quot;, data=df, palette= &quot;pastel&quot;  )<br>plt.title(&quot;Plot of Counts of Various Payment Methods&quot;)<br>plt.xticks(rotation= 45)<br>plt.figure(figsize= (15,5))<br>plt.show()</pre><p>The code gave me the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*MACiyCVmgri46VKkRmLCKQ.png" /></figure><p>This means most Vodafone customers preferred to pay their bills via an electronic check payment.</p><h3>3. Data Preparation:</h3><p>Once I took an overview of my data set, the next step was to prepare the data for my classification model. Besides changing the TotalCharges column to a numeric data type, there wasn’t much cleaning required for the dataset.</p><h4>3.1 Primary Feature Selection</h4><p>I started by getting rid of certain features that didn’t have any correlation with the target column (label). Since certain columns were categorical, I used the phi-k test for the selection.</p><p>I used the code below:</p><pre>churn_corr= df.phik_matrix().loc[&quot;Churn&quot;] ##getting my Churn results from the correlation<br><br>##sorting the values <br>churn_cor=churn_corr.sort_values()<br><br>##plotting the results:<br><br>sns.heatmap(churn_cor.to_frame(), annot= True, cmap= &quot;coolwarm&quot;)<br><br>plt.title(&quot;Phi_k Correlation Matrix for all  Features&quot;)<br><br>plt.figure(figsize= (10,15));</pre><p>This gave me the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*5J7iW6KtMKHXK_AdCdLb0w.png" /></figure><p>What I did was drop the features with a correlation coefficient of less than 0.1.</p><p><strong>Note:</strong></p><p>The TotalCharges attribute has a correlation coefficient of 0, and this is because I didn’t convert it to the right data type. So, I won’t be dropping it.</p><p>I used the code below to drop the uncorrelated columns:</p><pre>df_drop= df.drop([&quot;gender&quot;, &quot;PhoneService&quot;, &quot;MultipleLines&quot;], axis= 1)</pre><h4>3.2 Data Splitting</h4><p>The next step was to separate my label (y, or the column I will be predicting ) from my features (X). Also, I had to divide my data into the training set and the evaluation set, which I will refer to as a test.</p><p>For this, I used the codes below:</p><pre>##seperating my X and Y variables <br><br>X= df_drop.drop(&quot;Churn&quot;, axis=1)<br>y= df_drop.Churn</pre><pre>##getting my tranining and test set <br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, <br>random_state=42, stratify=y)</pre><p>This basically means, I want 20% of my dataset for evaluation and 80% for training the model. Also, the stratify ensures an even distribution of the y variable (the classes).</p><p>I also used a Label encoder to convert my labels; with 0 being for “No”, and 1 for “Yes.”</p><h4>3.3 Preprocessing Pipeline</h4><p>With this, I did three things here:</p><ul><li>Created a class to handle the spaces in the TotalCharges attribute. As stated earlier, it was an object datatype and had to be changed to a numeric data type (int or float). After running a regex function, I realized there were spaces that made the attribute appear as such; therefore, what this custom transformer will do is automatically convert the spaces to a NaN value, which we can then impute with the mean for further analysis.</li></ul><p>as shown below:</p><pre>##defining a function to convert spaces to NaN values<br>def remove_space(in_df):<br>    in_df[&quot;TotalCharges&quot;]= in_df[&quot;TotalCharges&quot;].replace(r&quot;^\s*$&quot;, np.nan,<br> regex= True)<br>    return in_df<br><br>##creating a custom transformer <br>class SpaceImputer():<br>    def __init__(self,func):<br>        self.func= func<br>    <br>    def transform(self, in_df, **transform_params):<br>        return self.func(in_df)<br>    <br>    def fit(self, X, y=None, **fit_params):<br>        return self</pre><ul><li>Created a pipeline to handle scaling and encoding.</li></ul><p>The pipeline is shown below:</p><pre>num_pipeline= Pipeline([(&quot;mean_imputer&quot;, SimpleImputer(strategy=&quot;mean&quot;)), (&quot;scaler&quot;, StandardScaler())])<br><br>cat_pipeline= Pipeline([(&quot;one_hot&quot;, OneHotEncoder())])<br><br>##final pipeline for encoding and scaling:<br>col_pipe= ColumnTransformer([(&quot;num_pipe&quot;, num_pipeline, num_attr),<br>(&quot;cat_pipe&quot;, cat_pipeline, cat_attr)])</pre><h4>3.4 Feature Selection</h4><p>For feature selection, I used Sk-Learn’s inbuilt “SelectKbest” and the “Class_if” feature selection metric.</p><p>The code is as shown below:</p><pre>SelectKBest(score_func=f_classif, k=10))</pre><p>The above code means I want to use the 10 best features for my modelling.</p><h3>4. Data Modelling:</h3><p>For my modelling, I compared the following algorithms:</p><ul><li>Decision Tree Classifier</li><li>Logistic Regression Classifier</li><li>Random Forest Classifier</li><li>XGboost</li><li>Support Vector Machine</li></ul><h4>Methodology:</h4><p>For evaluating each model, I considered the following:</p><ul><li>The f-1 score</li><li>The average recall</li><li>The recall of the Yes class or 1(how well a model did at not misclassifying churners as non-churners)</li><li>Accuracy</li></ul><p><strong>Note: Since we are predicting churners, I sorted the results by the recall of the “Yes” class or “1” class. This will be our most crucial metric</strong></p><p>Let’s dive into the steps:</p><p><strong>1. Run a base model without setting any parameters</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*jWMrPGcVcVyW7NCYH2roMQ.png" /><figcaption>Picture of the Random Forest Classifier with no parameters</figcaption></figure><p><strong>2. Handle the class imbalance using class_weight and SMOTE and then compared the results</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*xCiaMLcxPfJ5aXXO2hl-QA.jpeg" /><figcaption>Decision Tree Classifier with Class_weight</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*UGM1ixUxHkffXubTxFYSNw.png" /><figcaption>Decision Tree Classifier with Smote</figcaption></figure><p>After modelling with Class_weights (_CW), SMOTE (_SM) and the baseline model, I came up with the following conclusion:</p><ul><li>Balancing did improve the performance of our model, especially for the “Yes” class.</li><li>At the end of the modelling process, I realized that for each model, the class-weights (CW) method did relatively better than the SMOTE (SM) method, and the SMOTE did better than the base model in terms of prediction Churners.</li></ul><p>as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*mJ5gJDWGZ7k4Ld43Gqj7eA.png" /></figure><h3>5. Hyperparameter Tuning:</h3><p>For hyperparameter tuning, I will be using GridSearchCV. I tuned the following parameters:</p><ul><li>The C-parameter</li><li>The Max iterations</li><li>The random state</li></ul><p>The code is displayed below:</p><pre>params = {<br>    &quot;model__C&quot;: np.geomspace(1e-5, 1e5, num=20),<br>    &quot;model__max_iter&quot;: [100, 1200],<br>    &quot;model__random_state&quot;: [24, 42, 57, 100]<br>}</pre><p>I visualized my c-parameter to ensure that it was evenly spaced out, the graph is displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*Q8rqLLHCNqt66nrRbOAj_g.png" /><figcaption>Graph of my chosen c values</figcaption></figure><p>Also, I had to make a copy of my logistic regression model pipeline to ensure I can compare it with the tuned model.</p><pre>##We are going to create a copy of the CW_LRP and rename it for the purpose of hyperparameter tuning<br><br>HP_LRP= Pipeline([(&quot;spaceImputer&quot;, SpaceImputer(remove_space)),<br>               (&quot;coltrans&quot;, col_pipe),  <br>            (&quot;feature_selection&quot;, SelectKBest(score_func=f_classif, k=10)),<br>               (&quot;model&quot;, LogisticRegression(<br>                   random_state=100,<br>                   class_weight=weight))<br>              <br>              ])</pre><p>After everything was set, I then initialized my GridSearch CV, with the code below:</p><pre>##the scorer is setting log loss as our metric, and also, I am telling it to choose the model with the lowest score<br>## the need_proba is telling it to accept returned values and calculate the probability of each predicted label <br><br>scorer = make_scorer(log_loss, greater_is_better=False, needs_proba=True)<br><br>Grid_HPT= GridSearchCV(estimator=HP_LRP, param_grid=params,scoring=scorer, cv=5)</pre><h3>6. Model Evaluation</h3><p>After the tuning, I decided to evaluate the performance of the tuned model and the unturned model using a log-loss function to see which one is better.</p><p>So, why log loss? Well, when I printed my classification report, I realized there was no difference in performance, even though there was. Therefore I had to resort to using the log loss to evaluate each model’s performance as displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0I5IlZ-kCDU4EdvKteGEg.png" /><figcaption>Log Loss Comparison of Models</figcaption></figure><p>From the above image, it can be seen that the tuned model had a relatively lower log loss than the untuned model</p><p>Therefore, our hyperparameter tuning did help our model’s performance a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zu6k5GfwQdp5dKaFdRHoHA.png" /><figcaption>Classification Report on the performance of tuned vs unturned model</figcaption></figure><h3>7. Hypothesis Testing:</h3><p>My hypothesis is as follows:</p><h4>Null hypothesis:</h4><p>There is no significant relationship between the dependents and their likelihood to churn.</p><h4>Alternative hypothesis:</h4><p>There is a significant relationship between the dependents and their likelihood to churn.</p><h4>Methodology:</h4><p>Since both attributes were categorical, I used the chi-squared test of independence for my hypothesis testing.</p><p>I used the code below</p><pre># Creating a contingency table<br>contingency_table = pd.crosstab(df_copy[&#39;Dependents&#39;], df_copy[&#39;Churn&#39;])<br><br># Performing the chi-square test<br>chi2, p_value, dof, expected = chi2_contingency(contingency_table)<br><br># Printing the test results<br>print(&quot;Chi-square statistic:&quot;, chi2)<br>print(&quot;P-value:&quot;, p_value)<br>print(&quot;Degrees of freedom:&quot;, dof)<br>print(&quot;Expected frequencies:&quot;, expected)<br><br># Setting my significance level (alpha)<br>alpha = 0.05<br><br># Comparing the obtained p-value with alpha<br>if p_value &lt; alpha:<br>    print(&quot;Reject the null hypothesis. There is a significant relationship between dependents and churn.&quot;)<br>else:<br>    print(&quot;Fail to reject the null hypothesis. There is no significant relationship between dependents and churn.&quot;)</pre><p>and at the end, the results were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5z0XtO9C76WbDDjiYh8SpA.png" /></figure><p>Therefore, it can be concluded that the dependent attribute has a significant relationship with Churn.</p><h3>8. Conclusion</h3><h4>8.1. From my EDA</h4><p>I highly recommend that Vodafone’s retainment advertisements and promotions should target:</p><ul><li>Customers have a tenure between 0 to 11 months.</li><li>Female customers</li><li>Senior citizens</li><li>Individuals with no dependants/partners.</li><li>High churn rate was observed for customers on a month-to-month plan who pay a monthly charge between $70 to $110. Therefore Vodafone might want to target those customers as well.</li><li>It was observed that customers that paid a yearly charge between 0 to $200 churned more and this was among customers on a month-to-month plan as well. Therefore, I will recommend that Vodafone finds ways to have its customers subscribe to more long-term plans.</li></ul><p>Also, Vodafone should ensure that they check the service quality of:</p><p>- Their fibre optics plan<br>- Their electronic and paperless billing services</p><p>since customers using these services tend to churn more.</p><h4>8.2 My Modelling:</h4><p>Based on my modelling, the logistic regression model showed a high recall of 79 for the &quot;yes&quot; class in the churners category; this means it has a false negative rate of 21%. Therefore, it may incorrectly classify 21% of churners as non-churners. Additionally, the model has a precision of 51, indicating that 49% of the time it may predict non-churners as churners (false positives).</p><p>Therefore, while the model has a high recall, its low precision means there is a risk that Vodafone may target retention campaigns to non-churners who are unlikely to be churning, and this is a good tradeoff as opposed to the model having a low recall and a high precision where it will miss lots of churners and capture non-churners, defeating the purpose of this project.</p><p><strong>DASHBOARD:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*kNoyvlMclJyOm1Iponpk5Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43640fb5fb0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Accurate Models for Unit Sales Prediction in Favorita Stores using Time Series Forecasting]]></title>
            <link>https://gregoryarthur98.medium.com/building-accurate-models-for-unit-sales-prediction-in-favorita-stores-using-time-series-forecasting-ff4b90eda30b?source=rss-768dee559ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff4b90eda30b</guid>
            <dc:creator><![CDATA[Gregory Kwaku Arthur]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 22:46:22 GMT</pubDate>
            <atom:updated>2023-06-27T11:35:23.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPlPSNFlqVYtBMLYWq8ShQ.jpeg" /><figcaption>image from Clipdrop.io</figcaption></figure><p>Hello everyone, and welcome to my second project. This project is on time series analysis and is one of my favourite projects thus far. This is because everything we do on earth depends on time; therefore, by leveraging the power of time series analysis, we can find more accurate answers to questions than we would with just cross-sectional data.</p><p>From the title, the aim of this project was to create a model that accurately predicts store sales from various stores of Favorita, a large retail shop in Ecuador.</p><p>The outline of this article is as follows:</p><ul><li>Business Understanding</li><li>Data Understanding</li><li>Hypothesis</li><li>Library Importation</li><li>EDA and Questions</li><li>Modelling</li><li>Results</li><li>Notes</li><li>Conclusion</li></ul><p>At the end of this post, you should learn the following:</p><ul><li>How to utilize statistical time series models such as ARIMA and Facebook Prophet for prediction and forecast.</li><li>How to find your p,d, and q parameters</li><li>How to factor in exogenous variables in your modelling to improve a model’s performance.</li><li>How to use pure machine learning models for predictions.</li><li>and many more.</li></ul><h3>1. Business Understanding</h3><p>A time series is a sequence of data points that are indexed and ordered chronologically over time. Time series data can be observed at regular or irregular intervals and can be collected over any time period, ranging from seconds to decades or even centuries. Time series data can be univariate (i.e., a single variable is recorded over time) or multivariate (i.e., multiple variables are recorded over time). Favorita Corporation is an Ecuadorian company that creates and invests in the commercial, industrial and real estate areas. Its subsidiaries have activities in six countries in the region, including Panama, Paraguay, Peru, Colombia, Costa Rica, and Chile. They offer the best products, services, and experiences in an efficient, sustainable, and responsible way to improve the quality of life.</p><p>The aim of this project is to forecast the unit sales of the products across different stores. This is to optimize their inventory management, marketing strategies, and pricing decisions. To achieve these results, we employed the use of time series in collaboration with different machine learning algorithms via the CRISP-DM framework.</p><h3>2. Data Understanding</h3><p>We were provided with 5 different datasets. These included:</p><ul><li>A dataset about the various stores and cities&#39; information</li><li>A dataset about the holidays</li><li>A training dataset</li><li>A test dataset without a target — I mean it’s a Kaggle problem so it&#39;s normal.</li><li>An oil dataset</li></ul><p>Every dataset was intact, with the exception of the oil dataset which had some missing values. We filled this missing row using the backfill (“bfill”) method, which fills a missing row with the value of the subsequent row.</p><p>As shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sbT9YSJStGfxfRthzTZWw.png" /></figure><h3>3.Hypothesis</h3><ul><li>Null Hypothesis: Promotional activities don’t have a significant impact on store sales at Corporation Favorita.</li><li>Alternate Hypothesis: Promotional activities do have a significant impact on store sales at Corporation Favorita.</li></ul><p>We used the Granger causality test to prove the hypothesis, and after the test, we rejected our null hypothesis since the p-value was far less than 0.05.</p><h3>4.Libraries Importation</h3><pre>####data handling<br><br>import pandas as pd<br>import numpy as np<br><br>pd.set_option(&quot;display.max_rows&quot;, 500)<br>pd.set_option(&quot;display.max_columns&quot;, 100)<br><br>##data visualizations<br><br>import matplotlib.pyplot as plt <br>import seaborn as sns <br>import plotly.express as ex<br>import plotly.offline as po<br>from prophet.plot import plot_plotly, plot_components_plotly <br><br>##Algorithms <br>from sklearn.tree import DecisionTreeRegressor<br>from sklearn.ensemble import RandomForestRegressor<br>from statsmodels.tsa.statespace.sarimax import SARIMAX<br>from pmdarima import auto_arima<br>from prophet import Prophet<br>from sklearn.model_selection import train_test_split<br><br>###feature processors <br><br>from sklearn.preprocessing import LabelEncoder<br>from category_encoders.binary import BinaryEncoder<br>from sklearn.preprocessing import OrdinalEncoder<br><br>##Error evaluations<br><br>from sklearn.metrics import mean_absolute_error as MAE<br>from sklearn.metrics import mean_squared_log_error as MSLE<br>from sklearn.metrics import mean_squared_error as MSE<br>from statsmodels.tools.eval_measures import rmse<br><br>##stat models <br>from statsmodels.tsa.stattools import adfuller as adf ##for adf test<br>import statsmodels.api as sma ### for seasonal decomposition <br>from statsmodels.graphics.tsaplots import plot_acf as ACF<br>from statsmodels.graphics.tsaplots import plot_pacf as PACF<br>from statsmodels.tsa.stattools import grangercausalitytests ##grenger causality test<br> <br># Other packages<br>import os<br>import warnings <br>warnings.filterwarnings(&quot;ignore&quot;)<br>from datetime import datetime<br>import logging<br>logging.getLogger(&#39;prophet&#39;).setLevel(logging.WARNING)</pre><h3>5. EDA and Questions</h3><p>With our EDA, we decided to analyze each of the datasets provided carefully to find any useful information we could get.</p><p>We decided to explore each dataset and find answers to the questions we raised. These questions included:</p><p>1. which city had the highest number of stores</p><p>2. which month did Favorita have the highest sale</p><p>3. which store recorded the highest transaction?</p><p>4. which store had the highest sale?</p><p>5. what is the most bought product?</p><p>Q1. For the first question, Quito had the highest number of stores. The results are displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*u3ssRapqaf9hu1jzDkxZhg.png" /><figcaption>Fig.2</figcaption></figure><p>Q2.For the second question, we realized that the highest unit sale was recorded in July as shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*scA5lbUOOa9tqIRk2BWUOA.png" /><figcaption>fig3</figcaption></figure><p>Q3.For the third question, we realized stores 44,47,45,46, and 3 had the highest transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*fTLJJACP0onUIZXxyp__vw.png" /></figure><p>Q4.We realized that 44,45,47,3, and 49 had the highest unit sale. It is interesting to find that store 49 replaced store 47, even though store 47 had a relatively high number of transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*Lo6c6K7CbtApKZXLAuylKA.png" /></figure><p>Q5.From our analysis, we discovered that Bread/Bakery recorded the highest unit sales, while books recorded the least unit sale. The results are shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*jSNtqvkgGCafSkYr8O3wpw.png" /></figure><h3>6. Modeling:</h3><p>The next step was to model our dataset. It is important to note that we approached the modelling in two folds:</p><ul><li>I handled it as univariate forecasting where I tried to build a model using only current and lagged values of the target (sales). For this, I used Facebook Prophet and SARIMA.</li><li>I also considered other exogenous variables from the other datasets and then developed a model to predict sales as well. I used algorithms such as SARIMAX, Facebook Prophet, Decision Tree, and Random Forest.</li></ul><p>Let’s take a look at each modelling approach.</p><h4>6.1.Univariate Modelling</h4><p>With this, the idea was to develop a model without considering any other exogenous variable. The only variable considered was just sales and time.</p><p>So, I started by resampling my train data into daily sales. This helped me get a good idea of the total unit sales across all Favorita stores.</p><p>I achieved this with the code below:</p><pre>train_sales= train_copy.groupby(&quot;date&quot;).agg({&quot;sales&quot;: &quot;sum&quot;})<br><br>##I am grouping by each date and for each day I want the sum of sales across <br>## all stores <br></pre><p>The code above gave me the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*MupZI5Ah98jQYSYP-xnekw.png" /></figure><p>The plot for the code above is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*pd1g63iSdOGZWPD08p3ZJw.png" /></figure><ul><li>From our above image, we can see that there is a drop in sales (seasonality) at the beginning of each year.</li></ul><h4>6.1.1 Univariate Modeling with Autoarima</h4><p>With this, the idea was to forecast sales using the Autoarima algorithm.</p><p>However, before that, I had to use the following methods to help me understand the trends, seasonality, and stationarity of my data:</p><ul><li>A stationarity test</li><li>Decomposition graph</li><li>ACF and a PACF graph</li></ul><p>to help me understand the nature of my data better.</p><p><strong>6.1.1(a) Stationarity Test</strong></p><p>For my stationarity test, I used the Augmented Dickey-Fuller (ADF) test. With this test, the null and alternative hypotheses are as follows:</p><p>Null Hypothesis (H₀): The time series has a unit root, indicating it is non-stationary.</p><p>Alternative Hypothesis (H₁): The time series does not have a unit root, indicating it is stationary.</p><p>If the p-value &gt; 0.05 we accept the null hypothesis.</p><p>After my test, I got the result below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*jtCfBCB2SwryuLByvNk9eg.png" /></figure><p>My p-value was greater than 0.05 (0.08) therefore, the data was non-stationary.</p><p><strong>6.1.1(b) Decomposition Chart</strong></p><p>Since my data was non-stationary, I went ahead to decompose my data to help me understand it better. Since my data was daily data and the seasonality was annual, I choose my period to be 365. Also, I choose the model to be multiplicative since the time series showed some heteroscedastic behaviour.</p><p>I used the code below:</p><pre>decomposed_data= sma.tsa.seasonal_decompose(univar_sale, model= &quot;multiplicative&quot;, period=365 )<br><br>decomposed_data.plot()<br><br>plt.figure(figsize= (20,20))</pre><p>I got the graph below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iz0InuRxtD9mOxeu3mY07Q.png" /></figure><p>So, what does this tell us?</p><p>This chart tells us two things:</p><ul><li>This means when modelling, we can use an m of 365 since 365 gave us a perfect decomposition.</li><li>Also, we can see there is an upward trend therefore, we will have to differentiate our data.</li></ul><p><strong>6.1.1(c) PACF and ACF Chart</strong></p><p>These two charts provide us with in-depth information on our time series. They tell us the AutoRegressive and Moving Averages of our time series.</p><p>To achieve this I used the code below:</p><pre>##setting up my subplot<br>fig, ax = plt.subplots(2, 1, figsize=(8, 6))<br><br># my ACF plot<br>ACF(univar_sale, lags=48, ax=ax[0])<br>ax[0].set_title(&#39;Autocorrelation Function (ACF)&#39;)<br><br># my PACF plot<br>PACF(univar_sale, lags=48, ax=ax[1])<br>ax[1].set_title(&#39;Partial Autocorrelation Function (PACF)&#39;)<br><br>plt.tight_layout()<br>plt.show()</pre><p>For both charts, I got the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*d_tOPJdJmaM48CpeXIUnMQ.png" /></figure><p>So, what does this tell us?</p><p>These charts tell us two things:</p><p>- From our ACF chart (our Moving Average(q)) we can see all our lags above our significance level; however, the strongest lag can be seen at 1,6,7,8.</p><p>- From our PACF chart (our AutoreRegressive part (p)), we can see at see most lags above the significant level; however, a strong lag occurs at 1,3,5,6, and 7.</p><p>Therefore, we can use any combination for our model. However, in this section, we will be using the auto-Arima function.</p><p>It is worth noting that I manually tried fitting SARIMA (6,1,8)(0,1,0)365 with my train dataset; however, my computer kept freezing due to the high computational power requirement. Therefore I used auto-arima with my seasonality period set to 12. I settled for 12 because fitting higher periods such as 52 and above on this type of dataset kept freezing my computer, which is why I settled for 12.</p><ul><li>Therefore if anyone knows how I can leverage virtual machines for such purposes, that will be awesome.</li></ul><p>I used to code below to find the best p,d,q, and PDQ parameters for my modelling.</p><pre>##Importing our algorithm<br><br>model_1= auto_arima(univar_sale, m= 12, seasonal= True, <br>start_p= 0, start_q= 0, max_p= 10, max_q= 15, max_d= 5, d= 1,<br>test= &quot;adf&quot;, error_action= &quot;ignore&quot;,<br>suppress_warnings= True, stepwise= True, trace= True,  information_criterion=&#39;aic&#39;)</pre><p>After fitting the Autoarima model, I had my p,d,q, and PDQ values to be:</p><p>“ ARIMA(7,1,6)(0,0,0)[12]”</p><p>The Auto-Arima model gave us:</p><ul><li>A non-seasonal component of 7 for our Autoregressive component (p)</li><li>A differencing of 1 for our d</li><li>A Moving Average (q) of 6.</li></ul><p>I will share the RMSLE and MAE scores at the end of this post; so, I urge you to keep reading.</p><p>However, this is a visualization of how the model did:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*FdJZ5BUyToNMdeXEMKnTkw.png" /></figure><p>From the above chart, we can see that:</p><ul><li>The model did well in picking up the trend</li><li>It didn’t model the drop in sales at the beginning of the year</li></ul><p>From the modelling above, I was able to make some forecasts as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*7-YqdqGnXiJf-34ezp2ALw.png" /></figure><h4>6.1.2Univariate Modeling with Facebook Prophet</h4><p>I then decided to use Facebook Prophet to predict and forecast my sales based on my train_sales data.</p><p><strong>One thing with FBP is that the target column and the date column had to be renamed to “ds” for the date and “y” for the target column.</strong></p><p>Also, it is worth noting that there is no need to worry about the P, D, Q components of Facebook Prophet since it handles everything.</p><p>The code below shows how I instantiated my model.</p><pre>model_2= Prophet(yearly_seasonality= True, interval_width= 0.95, <br>seasonality_prior_scale= 25)</pre><ul><li>Yearly seasonality means, I am telling the model my seasonality is true</li><li>I set my uncertainty level to 95%</li><li>I am telling the model to prioritize my seasonality</li></ul><p>After fitting and predicting, I got the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*9wAWUg7wITgdzFnowAhU1w.png" /></figure><p>We can see the following:</p><ul><li>Just like with SARIMA, our univariate FBP model did a bad job of picking up the drop in sales at the beginning of 2017.</li><li>However, it did well in modelling occurrences of 2017.</li></ul><p>After modelling, I made some forecasts with Facebook Prophet’s inbuilt plotting feature, and I got the forecast as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*-lGjA2G9tHiPwvvLM6wbJg.png" /></figure><h3>6.2 Multivariate Modelling</h3><p>The idea here is to see how the other datasets and attributes of the training dataset (exogenous variables) affect sales. We believe this will actually improve the accuracy of our models.</p><h4>6.2.1 Merging Datasets</h4><p>I started by merging the datasets provided. I left out the store dataset because it wasn’t a time series column, and also, since we are trying to create a model to predict overall sales, it won’t be necessary.</p><p>Therefore I merged the oil, transaction, and holiday into the training dataset.</p><p><strong>There were a couple of things I had to do:</strong></p><p><strong>a.Merging my datasets</strong></p><p>I joined each data frame using the outer join method. This method is a union of two data frames, which ensures that I do not lose any rows, and for rows that aren’t present in one data frame, it is replaced with a NaN as opposed to dropping it.</p><p>I achieved this with the code below:</p><pre>merged_data1= pd.merge(df_train, transac_train, how= &quot;outer&quot;, on= [&quot;date&quot;, &quot;store_nbr&quot;])<br><br>merged_data2= pd.merge(merged_data1, holiday_train, how= &quot;outer&quot;, on= &quot;date&quot;)<br><br>merged_data3=  pd.merge(merged_data2, oil_train, how= &quot;outer&quot;, on= &quot;date&quot;)</pre><p>After merging, I had to drop the following columns:</p><ul><li>“family”,</li><li>“store_nbr”,</li><li>“month”.</li><li>“locale_name”</li><li>“description”</li></ul><p>These columns weren’t necessary for my analysis, therefore, they were dropped.</p><p><strong>b.Filtering</strong></p><p>Since we have our target(sales) in the transaction column, we are going to filter all other datasets (from 2013–01–01 to 2017–08–15) to match the date of our train dataset. Doing this will help us see how the other variables affect our sales within the same time period.</p><p><strong>c.Missing Values</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*5vbHYPCDps7Z2hVAwraAvQ.png" /></figure><p>I handled these missing values in three ways:</p><ul><li>First, I dropped all rows with missing values for the sales and promotion attributes. Using the code:</li></ul><pre>merged_data= merged_data.dropna(subset=[&quot;sales&quot;, &quot;onpromotion&quot;])</pre><ul><li>For the transaction columns, the missing values I had were due to the fact that no transactions were recorded; therefore, I replaced them 0, as shown in the code below:</li></ul><pre>merged_data[&quot;transactions&quot;]= merged_data[&quot;transactions&quot;].replace(np.nan, 0)</pre><ul><li>For the holiday attributes, (type, locale, and transferred) they were days that weren’t holidays. Therefore, I replaced the first two with “Not Holiday”, and the latter with False. I used the code below:</li></ul><pre><br>merged_data[&quot;type&quot;]=merged_data[&quot;type&quot;].replace(np.nan, &quot;Not Holiday&quot;)<br><br>merged_data[&quot;locale&quot;]=merged_data[&quot;locale&quot;].replace(np.nan, &quot;Not Holiday&quot;)<br><br>merged_data[&quot;transferred&quot;]=merged_data[&quot;transferred&quot;].replace(np.nan, &quot;False&quot;)</pre><ul><li>For the oil dataset (dcoilwtico), I used a backfill method to replace the missing values.</li></ul><p><strong>d.Final Look:</strong></p><p>At the end of the above processes, my data frame looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lwaXca05jd1fWTbFEWnNUQ.png" /></figure><p>Also, there were no missing values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uM_p_UEBzzMsxiqmqVFzdA.png" /></figure><h3>6.2.2 Feature Processing:</h3><p>This is where I optimize my features by:</p><ul><li>Selecting the best features (Feature selection)</li><li>Creating new features (Feature Engineering)</li><li>Converting categorical features to numeric features (Feature Encoding)</li></ul><p>All three above-mentioned methods were employed in this section.</p><h4><strong>a.Granger Causality Test (Prelims Feature Selection)</strong></h4><p>The datasets I merged together were time series datasets; therefore, a correlation test wouldn’t give us enough information as to whether one dataset has a causal effect on the target (sales). To find out the causal relationship between the various time series (“dcoilwtico”, “transactions”, “onpromotions”) to sales, the appropriate test was a Granger causality test.</p><p>Below is the null and alternative hypothesis of the Granger causality test:</p><ul><li>Null Hypothesis: The past values of time series X do not provide any significant information to predict time series Y. In other words, there is no causal relationship between X and Y.</li><li>Alternative Hypothesis: The past values of time series X do provide significant information to predict time series Y. In other words, there is a causal relationship between X and Y.</li></ul><p><strong>Essentially, if the p-value of the test for any lag is greater than 0.05, we accept the null hypothesis.</strong></p><p>The test was performed over 20 lags.</p><ul><li>After the causality test, I realized that after the 14th lag, the oil data had a p-value greater than 0.05; therefore, I had to drop it.</li></ul><p>as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*f9IAx4Gv1my4KFVR4LMkKQ.png" /></figure><ul><li>Also, the causality test validated our alternative hypothesis of the Granger causality test. Hence, “onpromotion” has an effect on sales. This is because, after 20 lags, the p-value was way below 0.05.</li><li>However, it is worth noting that this test also validates the alternative hypothesis of the whole project, which is “Promotional activities have a significant impact on store sales at Corporation Favorita”; therefore, we can reject our null hypothesis of the whole project.</li></ul><p>Below is an image of the test results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7ikneY8RnrCP14MWvnH5Q.png" /></figure><h4>b.Feature encoding</h4><p>Feature encoding involves converting your categorical (non-numeric) features into numeric features.</p><p>My non-numeric features include:</p><ul><li>Holiday (<strong>I renamed the “type” column to holiday</strong>). I realized that it had many unique values; therefore I used a binary encoder.</li><li>The locale feature had some sort of hierarchy such as National, Regional, Local, and Not Holiday; therefore, I used an Ordinal encoder for that.</li><li>The transferred feature had only two values: True and False, therefore, I used a Label encoder to handle the conversion (I replaced True with 1 and False with 0). It is worth noting that some of the “False” values were strings instead of booleans, so I replaced them with the boolean False before encoding.</li></ul><h4>c.Feature Engineering:</h4><p>To enhance my models’ prediction ability, I had to create new features. It is worth noting that I only used the featuring engineering for my pure machine learning models, as opposed to, the statistical models.</p><p>I used the code below to create my features:</p><pre>df_final[&#39;day&#39;]=df_final[&#39;date&#39;].dt.day<br>df_final[&#39;month&#39;]= df_final[&#39;date&#39;].dt.month<br>df_final[&#39;day_of_month&#39;]= df_final[&#39;date&#39;].dt.day<br>df_final[&#39;day_of_year&#39;]= df_final[&#39;date&#39;].dt.dayofyear<br>df_final[&#39;week_of_year&#39;]= df_final[&#39;date&#39;].dt.isocalendar().week.astype(int)<br>df_final[&#39;day_of_week&#39;]= df_final[&#39;date&#39;].dt.dayofweek<br>df_final[&#39;is_weekend&#39;]= np.where(df_final[&#39;day_of_week&#39;] &gt; 4,1,0)<br>df_final[&#39;is_month_start&#39;]= df_final[&#39;date&#39;].dt.is_month_start.astype(int)<br>df_final[&#39;is_month_end&#39;]= df_final[&#39;date&#39;].dt.is_month_end.astype(int)<br>df_final[&#39;quarter&#39;]= df_final[&#39;date&#39;].dt.quarter<br>df_final[&#39;is_quarter_start&#39;]= df_final[&#39;date&#39;].dt.is_quarter_start.astype(int)<br>df_final[&#39;is_quarter_end&#39;]= df_final[&#39;date&#39;].dt.is_quarter_end.astype(int)<br>df_final[&#39;is_year_start&#39;]= df_final[&#39;date&#39;].dt.is_year_start.astype(int)<br>df_final[&#39;is_year_end&#39;]= df_final[&#39;date&#39;].dt.is_year_end.astype(int)</pre><h4>6.2.4 Multivariate Modelling with FaceBook Prophet(FBP)</h4><p>With the exogenous columns available, I decided to use FBP for my modelling.</p><p>To add my exogenous variables, I used the codes below:</p><ul><li>I instantiated my model using the same parameter as before.</li><li>The only difference was to add my external regressors, which I did using the code below:</li></ul><pre>###getting a list of my exogenous variables <br>exo_cols=[ &#39;holiday_0&#39;, &#39;holiday_1&#39;, &#39;holiday_2&#39;, &#39;locale&#39;, &#39;transferred&#39;, &#39;onpromotion&#39;, &#39;transactions&#39;]<br>##using a forloop to add them to my model<br>for cols in exo_cols:<br>    model_3.add_regressor(cols, standardize= True)</pre><p>After fitting, I saw an improvement in the error values. It did well in modelling the low sales during the beginning of the year as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*Ay3PYNWK-cEoyCEhPRWRTw.png" /></figure><p>Alternative chart using Facebook Prophet plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*ixpjD7Om_UiDOxkyPNSVTw.png" /></figure><h4>6.2.5 Multivariate Modelling with SARIMAX</h4><p>I decided to also use SARIMAX (X stands for exogenous) to develop a model. There was an improvement in the model as well.</p><p>I added my exogenous variables using the following process:</p><pre>##my endogenous variable is my sales, therefore I fileted it out from my <br>##test and train<br>train_endog=  sari_multi_train[[&quot;sales&quot;]]<br>test_endog=  sari_multi_test[[&quot;sales&quot;]]<br>##my exogenous variable are every feature but sales, <br>##therefore I fileted it out from my test and train<br>train_exog= sari_multi_train.drop(&quot;sales&quot;, axis= 1)<br>test_exog=  sari_multi_test.drop(&quot;sales&quot;, axis= 1)</pre><p>I fitted my model with the train and test of my endogenous and exogenous dataset:</p><pre>model_4 = SARIMAX(endog=train_endog, exog=train_exog, <br>order=(7, 1, 6), seasonal_order=(0, 0, 0, 12), frequency=&quot;D&quot;).fit()</pre><p>I then made a prediction on my test (eval)set and I got the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*d7aBB5bzBgaudzOEJ4zH_Q.png" /></figure><p>We can see it really improved compared to the previous SARIMA model, since it did well in modelling the drop in yearly sales as well.</p><h4>6.2.6 Multivariate Modelling with Pure Machine Learning Models</h4><p>As stated earlier, I also tried two pure ML models:</p><ul><li>Decision Tree</li><li>Random Forest</li></ul><p>These two didn’t require the date column, so I had to drop it.</p><p>Below are visualizations of the performance of each model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*EBuKjttoES3mIe4N52_NhQ.png" /><figcaption>Decision Tree’s Performance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*PUfKoMqI8q_Kloj6UUbYrw.png" /><figcaption>Random Forest Performance</figcaption></figure><p>Feature Selection:</p><p>Afterwards, I performed feature selection using the intrinsic feature selection feature of the Random Forest and Decision tree models. However, there was no significant improvement</p><h4>7. Results</h4><p>The metric for judging the performance of the models is RMSLE, and per our instructor, any model with an RMSLE of 0.2 and values lesser is an excellent model.</p><p>Below are the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*ViVnKKUDRHw1aWNPhPGq5w.png" /></figure><p>From my modelling, ARIMAX, Decision Tree, and Facebook Prophet were excellent.</p><h3>8. Notes:</h3><ul><li>My ARIMAX was limited by my computer’s feature since I couldn’t model the 365 periods. I will appreciate it if anyone can help me access a virtual machine for such purposes.</li><li>Also, I didn’t perform an AutoArima grid search on the SARIMAX model. I used the p,d, and q parameters provided for my SARIMA mode to fit and train my SARIMAX model.</li></ul><h3>9. Conclusion</h3><ul><li>From the above modelling, exogenous attributes do improve the performance of the model.</li><li>Modelling with pure machine learning models is much easier than statistical time series modelling. However, the two algorithms I chose couldn’t accept dates.</li></ul><p>For the detailed codes, kindly check out the notebook <a href="https://github.com/Greg-Art/LP2_timeseries_repo/blob/main/code/notebooks/LP2_Regression_Project_Submission.ipynb">on my GitHub page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff4b90eda30b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crunching The Numbers: An EDA Of The Indian Startup Ecosystem From 2018 to 2021]]></title>
            <link>https://gregoryarthur98.medium.com/crunching-the-numbers-an-eda-of-the-indian-startup-ecosystem-from-2018-to-2021-380ddd985449?source=rss-768dee559ee2------2</link>
            <guid isPermaLink="false">https://medium.com/p/380ddd985449</guid>
            <dc:creator><![CDATA[Gregory Kwaku Arthur]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 08:43:15 GMT</pubDate>
            <atom:updated>2023-05-05T08:13:02.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51KLXljUDoY9iofUcr6c6Q.png" /><figcaption>Generated with Fotor AI</figcaption></figure><p>As part of Azubi Africa’s data analytics professional program, my team and I were tasked to perform an end-to-end analysis of the Indian startup ecosystem. We were presented with datasets from 2018 to 2021, and I must say, the data was dirty — Whew! However, with days of dedication and brainstorming, we were able to clean the data and come up with meaningful insights that were worth sharing.</p><p>I will like to highlight that some sections of the post have been tweaked per the great comment given by Miss. Racheal Appiah.</p><p>Before diving into the nitty-gritty of the project, I will like to share an overview of the article to help you know what to expect. This post will cover the following:</p><ul><li>Business Understanding of The Indian Startup Market</li><li>Null and Alternate Hypothesis Hypothesis</li><li>Questions We Wanted To Explore</li><li>Library Installation and Importation</li><li>Exploratory Data Analysis</li><li>Hypothesis Testing</li></ul><p>With these out of the way, let’s dive into each of the above-listed subtopics.</p><h4>1. Business Understanding Of The Indian Startup Market</h4><p>To comprehend the factors that lead to start-up success, the problem entails analyzing the funding received by start-ups in India from 2018 to 2021. The objective is to find patterns and trends in the data on financing amounts, investor details, and start-up information and to use these revelations to make inferences about the traits of Indian start-ups that are likely to succeed. Utilizing statistical techniques and methods, the study may look at the effects of start-up performance on funding levels, investor diversity, location, industry specialization, innovation, and founding team experience. Investors, business people, and policymakers who want to comprehend the dynamics of the Indian start-up ecosystem and come up with ideas such as start-up promotion may find the analysis findings helpful.</p><h4>2. Null and Alternate Hypothesis</h4><p><strong>Null Hypothesis:</strong></p><p>Companies whose headquarters are located in the Indian capital city ( Delhi) are more likely to receive high funding than those located in other cities</p><p><strong>Alternate Hypothesis:</strong></p><p>Companies whose headquarters are located in the Indian capital city, (Delhi) do not necessarily receive more funding than those located in other cities</p><h4>3. Questions I Wanted To Explore</h4><p>1- Are start-ups located in specific areas more likely to succeed or to receive more financing than those located in other areas?</p><p>2- Has the amount of investments in the ecosystem increased over the 4 years (the datasets we are looking at), or has it decreased?</p><p>3- What is the median investment amount received by Indian startups at different stages of their growth?</p><p>4- Does the nature of the industry have any impact on the funding received?</p><p>5- Which startup had the highest rate/count of funding (this counts the startup that occurred most but not with duplicate funding)</p><h4>4. Libraries Installation and Importation</h4><pre>##data handling<br><br>import pandas as pd <br><br>import numpy as np<br><br>pd.set_option(&#39;display.max_rows&#39;, None)<br>pd.set_option(&#39;display.max_columns&#39;, None)<br><br>##data visualization<br><br>import seaborn as sns<br><br>import matplotlib.pyplot as plt<br><br>##Others<br><br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;) ##to handle warnings<br><br>##for geolocation<br><br>from geopy.geocoders import Nominatim<br><br>geolocator = Nominatim(user_agent=&quot;my-custom-agent&quot;, timeout=20)<br></pre><h4>5.Data Loading</h4><p>During this stage, I went ahead to load the datasets from my computer onto Jupyter Notebook for my analysis. I had to create a new column that specified the year each row was from. This would help in my analysis, as well as help me identify the year each row was from. The code can be seen below:</p><pre>#Data paths<br>path_2018 = &quot;Desktop/Pandas/india/startup_funding2018.csv&quot; <br>path_2019 =  &quot;Desktop/Pandas/india/startup_funding2018.csv&quot;<br>path_2020 =  &quot;Desktop/Pandas/india/startup_funding2020.csv&quot; <br>path_2021 =  &quot;Desktop/Pandas/india/startup_funding2021.csv&quot; <br><br><br>startup_2018= pd.read_csv(path_2018)<br><br>startup_2019= pd.read_csv(path_2019)<br><br>startup_2020= pd.read_csv(path_2020)<br><br>startup_2021= pd.read_csv(path_2021)</pre><pre>startup_2018[&quot;Year&quot;]= &quot;2018&quot;<br>startup_2019[&quot;Year&quot;]= &quot;2019&quot;<br>startup_2020[&quot;Year&quot;]= &quot;2020&quot;<br>startup_2021[&quot;Year&quot;]= &quot;2021&quot;</pre><h4>6. Exploratory Data Analysis</h4><h4>6.1 Data Overview</h4><p>After loading the data, I want ahead to get an overview of each dataset using the <strong>.info() </strong>method.</p><pre>startup_2018.info()<br><br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 526 entries, 0 to 525<br>Data columns (total 7 columns):<br> #   Column         Non-Null Count  Dtype <br>---  ------         --------------  ----- <br> 0   Company Name   526 non-null    object<br> 1   Industry       526 non-null    object<br> 2   Round/Series   526 non-null    object<br> 3   Amount         526 non-null    object<br> 4   Location       526 non-null    object<br> 5   About Company  526 non-null    object<br> 6   Year           526 non-null    object<br>dtypes: object(7)<br>memory usage: 28.9+ KB</pre><pre>startup_2019.info()<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 89 entries, 0 to 88<br>Data columns (total 10 columns):<br> #   Column         Non-Null Count  Dtype  <br>---  ------         --------------  -----  <br> 0   Company/Brand  89 non-null     object <br> 1   Founded        60 non-null     float64<br> 2   HeadQuarter    70 non-null     object <br> 3   Sector         84 non-null     object <br> 4   What it does   89 non-null     object <br> 5   Founders       86 non-null     object <br> 6   Investor       89 non-null     object <br> 7   Amount($)      89 non-null     object <br> 8   Stage          43 non-null     object <br> 9   Year           89 non-null     object <br>dtypes: float64(1), object(9)<br>memory usage: 7.1+ KB</pre><pre>startup_2020.info()<br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 1055 entries, 0 to 1054<br>Data columns (total 11 columns):<br> #   Column         Non-Null Count  Dtype <br>---  ------         --------------  ----- <br> 0   Company/Brand  1055 non-null   object<br> 1   Founded        843 non-null    object<br> 2   HeadQuarter    961 non-null    object<br> 3   Sector         1042 non-null   object<br> 4   What it does   1055 non-null   object<br> 5   Founders       1043 non-null   object<br> 6   Investor       1017 non-null   object<br> 7   Amount($)      1052 non-null   object<br> 8   Stage          591 non-null    object<br> 9   Unnamed: 9     2 non-null      object<br> 10  Year           1055 non-null   object<br>dtypes: object(11)<br>memory usage: 90.8+ KB</pre><pre>startup_2021.info()<br><br>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>RangeIndex: 1209 entries, 0 to 1208<br>Data columns (total 10 columns):<br> #   Column         Non-Null Count  Dtype  <br>---  ------         --------------  -----  <br> 0   Company/Brand  1209 non-null   object <br> 1   Founded        1208 non-null   float64<br> 2   HeadQuarter    1208 non-null   object <br> 3   Sector         1209 non-null   object <br> 4   What it does   1209 non-null   object <br> 5   Founders       1205 non-null   object <br> 6   Investor       1147 non-null   object <br> 7   Amount($)      1206 non-null   object <br> 8   Stage          781 non-null    object <br> 9   Year           1209 non-null   object <br>dtypes: float64(1), object(9)<br>memory usage: 94.6+ KB</pre><p>I noticed some inconsistencies in some of the datasets together with some of the columns. These inconsistencies included:</p><ul><li>The amount column in all the datasets was an object data type so I had to convert them to an int data type.</li><li>The 2018 dataset had three columns missing, namely: “Founded,” “Founders,” and “Investor”.</li><li>Finally, the 2020 dataset had an odd column with the name: “Unnamed: 9”</li></ul><h4>6.2 Preprocessing</h4><p>After having a fair idea of the structure and datatypes of each dataset, I went ahead to investigate further for any discrepancies and then try to resolve these discrepancies.</p><p>I used four rules — or steps, if I may say — to guide me through this process. These rules included:</p><ul><li>Checking for duplicated rows in each dataset</li><li>Check for any discrepancies in each column of each dataset.</li><li>Use Crunchbase and the Web to find and fill in any missing rows deem fit</li><li>Check the datatype of each column of each dataset to ensure they were accurate.</li></ul><p>NOTE: These rules will be applied to each dataset, and for each dataset, I will check each column for discrepancies.</p><p>Also, for each dataset, I will highlight the inconsistencies I detected and how I handled them.</p><h4>6.1.2. Preprocessing The Dataset</h4><p><strong>6.1.2.1. Handling duplicates</strong></p><p>There were duplicates, which I handled. A similar concept was applied to every other dataset.</p><pre>startup_2018[startup_2018[&quot;Company Name&quot;].duplicated(keep=False)].sort_values(by=&quot;Company Name&quot;)<br><br>##I dropped the first instance of the duplicate I detected<br><br>startup_2018.drop(0, axis= 0, inplace= True)</pre><p><strong>6.1.2.2 Preprocessing the Company Name Attribute</strong></p><p>None of the datasets had any issues with the Company Name attribute.</p><p><strong>6.1.2.3 Preprocessing the Founded Attribute</strong></p><p>Some rows were represented with “ — ”, so I replaced those rows with np.nan to make my analysis easy.</p><p><strong>6.1.2.4 Preprocessing the HeadQaurter Attribute</strong></p><p>The 2018 dataset had some headquarters values consisting of the State and City. The city was the first instance, and since other datasets were represented with just the cities, we went ahead to split and take the first index.</p><pre>1            Mumbai, Maharashtra, India<br>2               Gurgaon, Haryana, India<br>3           Noida, Uttar Pradesh, India<br>4      Hyderabad, Andhra Pradesh, India<br>5           Bengaluru, Karnataka, India<br>6                 Kalkaji, Delhi, India<br>7      Hyderabad, Andhra Pradesh, India<br>8            Mumbai, Maharashtra, India<br>9           Bangalore, Karnataka, India<br>10                  Delhi, Delhi, India<br><br>## I used the code below to get the first instance:<br><br>startup_2018[&quot;Location&quot;]= startup_2018[&quot;Location&quot;].str.split(&quot;,&quot;).str[0]<br><br>## The end results were:<br><br>1              Mumbai<br>2             Gurgaon<br>3               Noida<br>4           Hyderabad<br>5           Bengaluru<br>6             Kalkaji<br>7           Hyderabad<br>8              Mumbai<br>9           Bangalore<br>10              Delhi<br>11          Bengaluru<br>12              India<br>13              Hubli<br>14          Bangalore<br>15          Bengaluru</pre><p><strong>6.1.2.5 Preprocessing the Industry Attribute</strong></p><p>With the Industry attribute, I realized that some datasets contained the sectors and subsectors of each company, and since we only needed the sectors, we decided to take the first occurrence as shown below. I also replaced rows represented with “ — ” with np.nan</p><pre>48     Artificial Intelligence, Machine Learning, Saa...<br>49                                           Hospitality<br>50                                Food and Beverage, Tea<br>51               Media and Entertainment, News, Outdoors<br>52     Broadcasting, Media and Entertainment, Music, ...<br>53     B2B, Information Services, Information Technology<br>54     EdTech, Education, Enterprise Software, Peer t...<br>55                                  Health Care, Medical<br>56                                            E-Commerce<br>57                       Health Care, Hospital, Wellness<br>58                                                     —<br>59                                                Sports<br>60                   Big Data, Consumer Lending, FinTech<br>61              Cloud Computing, Computer, Semiconductor<br>62                  Health Care, Medical, Pharmaceutical<br>63                               Food Processing, Retail<br>64                                      Trading Platform<br>65                      Consumer Goods, Lifestyle, Men&#39;s<br>66                                              Wellness<br>67                                             Education<br>68         Food and Beverage, Food Processing, Nutrition</pre><p>I resolved this by using the code below</p><pre># Fetches the first index of the sectors<br>startup_2018[&quot;Industry&quot;]= startup_2018[&quot;Industry&quot;].str.split(&quot;,&quot;).str[0]<br><br># Replaces all _ with np.nan<br><br>startup_2018[&quot;Industry&quot;]= startup_2018.Industry.replace(&quot;—&quot;, np.nan)</pre><p>The results of the code above were:</p><pre>1                             Agriculture<br>2                                  Credit<br>3                      Financial Services<br>4                    E-Commerce Platforms<br>5                    Cloud Infrastructure<br>6                                Internet<br>7                         Market Research<br>8                    Information Services<br>9                         Mobile Payments<br>10                                    B2B<br>11                               Internet<br>12                                   Apps<br>13                          Food Delivery<br>14                  Industrial Automation<br>15                             Automotive<br>16                                Finance<br>17                             Accounting<br>18                Artificial Intelligence<br>19                     Internet of Things<br>20                     Air Transportation<br>21                     Financial Services<br>22                      Food and Beverage<br>23                    Autonomous Vehicles<br>24                    Enterprise Software<br>25                            Agriculture<br>26                              Logistics<br>27                     Financial Services<br>28                             Automotive<br>29                Artificial Intelligence<br>30                     Internet of Things<br>31                              Insurance<br>32                     Financial Services<br>33                 Information Technology</pre><p><strong>6.1.2.6 Preprocessing the Stage (Round/Series) Attribute</strong></p><p>I used the .unique() method to find any inconsistent rows in the “Round/Series” attribute. I discovered the inconsistencies below:</p><pre>1. https://docs.google.com/spreadsheets/d/1x9ziNeaz6auNChIHnMI8U6kS7knTr3byy_YBGfQaoUA/edit#gid=1861303593<br>2. Undisclosed<br><br>## I fished out rows containing these discrapencies using the codes below:<br><br><br>startup_2018[startup_2018[&quot;Round/Series&quot;]==&quot;Undisclosed&quot;]<br>startup_2018[startup_2018[&quot;Round/Series&quot;]==&quot;https://docs.google.com/spreadsheets/d/1x9ziNeaz6auNChIHnMI8U6kS7knTr3byy_YBGfQaoUA/edit#gid=1861303593&quot;]<br><br>##Went ahead to replace the undisclosed with np.nan and <br>## I replaced the second discrapency with the real values which are:<br><br>##for the first discrapency<br>startup_2018.loc[164, &quot;Round/Series&quot;]= np.nan<br>startup_2018.loc[406, &quot;Round/Series&quot;]= np.nan<br><br>##for the second discrapency<br>startup_2018.loc[178, &quot;Round/Series&quot;]= &quot;Seed&quot;</pre><p><strong>6.1.2.7 Preprocessing the Amount Attribute</strong></p><p>With the Amount attribute of the 2018 dataset, I realized some of the values were in dollars, while some rows were in rupees, and other rows had no currency attached.</p><pre>,500,000&#39;, &#39;300000&#39;, &#39;6830000&#39;, &#39;200000&#39;, &#39;₹150,000,000&#39;,<br>       &#39;4300000&#39;, &#39;364846&#39;, &#39;400000&#39;, &#39;1500000&#39;, &#39;₹7,000,000&#39;,<br>       &#39;₹1,400,000&#39;, &#39;₹10,000,000&#39;, &#39;₹22,500,000&#39;, &#39;13200000&#39;, &#39;50000&#39;,<br>       &#39;₹140,200,000&#39;, &#39;3000000&#39;, &#39;1250000&#39;, &#39;180000&#39;, &#39;₹19,200,000&#39;,<br>       &#39;₹103,000,000&#39;, &#39;4200000&#39;, &#39;175000&#39;, &#39;1450000&#39;, &#39;₹200,000&#39;,<br>       &#39;4500000&#39;, &#39;600000&#39;, &#39;₹16,600,000&#39;, &#39;₹12,000,000&#39;, &#39;15000000&#39;,<br>       &#39;₹33,000,000&#39;, &#39;125000&#39;, &#39;130000&#39;, &#39;₹34,900,000&#39;, &#39;₹72,000,000&#39;,<br>       &#39;17200000&#39;, &#39;₹32,000,000&#39;, &#39;3500000&#39;, &#39;₹135,000,000&#39;, &#39;12000000&#39;,<br>       &#39;$40,000,000&#39;, &#39;$1,100,000&#39;, &#39;$50,000,000&#39;, &#39;₹1,540,000,000&#39;,<br>       &#39;$3,000,000&#39;, &#39;$6,000,000&#39;, &#39;₹140,000,000&#39;, &#39;$41,900,000&#39;,<br>       &#39;₹1,410,000,000&#39;, &#39;$3,530,000&#39;, &#39;$200,000&#39;, &#39;$3,300,000&#39;,<br>       &#39;₹580,000,000&#39;, &#39;₹36,000,000&#39;, &#39;₹340,000,000&#39;, &#39;$210,000,000&#39;,<br>       &#39;$37,680,000&#39;, &#39;$250,000&#39;, &#39;$20,000&#39;, &#39;₹510,000,000&#39;,<br>       &#39;₹2,200,000,000&#39;, &#39;22000000&#39;, &#39;70000&#39;, &#39;10000000&#39;,</pre><p>I made the following assumption:</p><ul><li>I assumed that amounts with no currency were in dollars</li></ul><p>Also, I decided to convert the amounts in rupees to dollars using the code below:</p><pre>##We will get rid of all the &quot;,&quot; to make our cleaning easier<br><br>startup_2018[&quot;Amount&quot;]= startup_2018.Amount.apply(lambda x:str(x).replace(&quot;,&quot;, &quot;&quot;))<br>## next we will filter out all the rows in the amount column containting &quot;₹&quot;<br><br>rupees_mask = startup_2018[&#39;Amount&#39;].str.contains(&#39;₹&#39;)<br><br>## we convert it to a dataframe<br><br>rupees_df = startup_2018[rupees_mask].copy()<br><br>rupees_df[&#39;Amount&#39;] = rupees_df[&#39;Amount&#39;].str.replace(&#39;₹&#39;, &#39;&#39;)<br><br><br>rupees_df[&#39;Amount&#39;] = rupees_df[&#39;Amount&#39;].astype(float)<br><br>##we will conver it to dollars using the 2018 dollar rate since the dataset is from 2018<br><br>dollar_rate_2018= 68.4113<br><br>rupees_df[&#39;Amount&#39;] = round(rupees_df[&#39;Amount&#39;] /dollar_rate_2018 , 0)<br><br>##we will convert it back to a string to reattach it to our original dataframe <br><br>rupees_df[&#39;Amount&#39;] = rupees_df[&#39;Amount&#39;].astype(str)<br><br>## Now let&#39;s replace the columns with rupees in our original dataset with the converted one<br><br>startup_2018.loc[rupees_mask, &#39;Amount&#39;] = rupees_df[&#39;Amount&#39;].values<br><br>##Now let&#39;s strip the dollar sign from the rows with it<br><br>startup_2018[&#39;Amount&#39;] = startup_2018[&#39;Amount&#39;].str.replace(&#39;$&#39;, &#39;&#39;)</pre><p>I eventually realized some rows were represented with “ — ”, so, I went ahead to represent those rows with “np.nan” using the code below:</p><pre>startup_2018[&quot;Amount&quot;]=startup_2018[&quot;Amount&quot;].replace(&quot;—&quot;, np.nan)<br><br>##This resulted in a cleaned version of the amount attribute as displayed below:<br><br>12             NaN<br>13             NaN<br>14             NaN<br>15       1461747.0<br>16          150000<br>17         1100000<br>18             NaN<br>19          7309.0<br>20         6000000<br>21          650000<br>22        511611.0<br>23        935518.0<br>24             NaN</pre><p>Also, some rows were represented with “Undisclosed” and other variations together with misspellings of the word “Undisclosed”. I replaced all those rows with “np.nan”</p><p><strong>6.1.2.8 Preprocessing the What It Does Attribute</strong></p><p>There were no discrepancies detected.</p><p><strong>6.1.2.9 Preprocessing the Founders&#39; Attribute</strong></p><p>Some rows had their Founders&#39; attribute values interchanged with that of the investors and investment amount as opposed to the founders.</p><p>Some examples include:</p><pre>We realized some rows had the following issues:<br><br>- http://100x.vc/<br>- Morgan Stanley Private Equity Asia\t<br>- ah! Ventures High Tables<br>- 2000000<br>- 1000000\t#REF!</pre><p>We found all these rows and replaced each column of each row with their respective value.</p><p><strong>6.1.2.10 Preprocessing the Investors&#39; Attribute</strong></p><p>There was one misspelling I identified whiles going through the investors&#39; attribute. So, I filtered the row out and fixed the misspelling.</p><pre> &gt;Vikram Sud<br><br>startup_2020.loc[192, &quot;Investor&quot;]=&quot;Vikram Sud&quot;</pre><p><strong>6.1.2.11 Checking and Changing the Datatypes</strong></p><p>For most of the datasets, the founded and Amount column were in float 64 and object datatypes respectively. Therefore, we had to change both to int for easy analysis.</p><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>Int64Index: 88 entries, 0 to 88<br>Data columns (total 10 columns):<br> #   Column         Non-Null Count  Dtype  <br>---  ------         --------------  -----  <br> 0   Company/Brand  88 non-null     object <br> 1   Founded        60 non-null     float64<br> 2   HeadQuarter    70 non-null     object <br> 3   Sector         83 non-null     object <br> 4   What it does   88 non-null     object <br> 5   Founders       85 non-null     object <br> 6   Investor       88 non-null     object <br> 7   Amount($)      76 non-null     object <br> 8   Stage          42 non-null     object <br> 9   Year           88 non-null     object </pre><p>We applied the code below to enact the changes</p><pre>##First, we will deal with the Amount column:<br><br>#-We will strip all the &quot;,&quot; and $<br><br>startup_2019[&quot;Amount($)&quot;]= startup_2019[&quot;Amount($)&quot;].apply(lambda x:str(x).replace(&quot;,&quot;, &quot;&quot;))<br>startup_2019[&quot;Amount($)&quot;]= startup_2019[&quot;Amount($)&quot;].apply(lambda x:str(x).replace(&quot;$&quot;, &quot;&quot;))<br><br>##We will replace all np.nan with 0 and convert the column to int<br><br>startup_2019[&quot;Amount($)&quot;]= startup_2019[&quot;Amount($)&quot;].apply(lambda x:str(x).replace(&quot;nan&quot;, &quot;0&quot;))<br><br>startup_2019[&quot;Amount($)&quot;]=startup_2019[&quot;Amount($)&quot;].astype(int)<br><br>##For changing the Founded column to Int, we applied the code below:<br><br><br>startup_2019[&quot;Founded&quot;]=startup_2019[&quot;Founded&quot;].replace(np.nan, 0)<br><br>startup_2019[&quot;Founded&quot;]=startup_2019[&quot;Founded&quot;].astype(int)</pre><p>These gave the output below:</p><pre>&lt;class &#39;pandas.core.frame.DataFrame&#39;&gt;<br>Int64Index: 88 entries, 0 to 88<br>Data columns (total 10 columns):<br> #   Column         Non-Null Count  Dtype <br>---  ------         --------------  ----- <br> 0   Company/Brand  88 non-null     object<br> 1   Founded        88 non-null     int32 <br> 2   HeadQuarter    70 non-null     object<br> 3   Sector         83 non-null     object<br> 4   What it does   88 non-null     object<br> 5   Founders       85 non-null     object<br> 6   Investor       88 non-null     object<br> 7   Amount($)      88 non-null     int32 <br> 8   Stage          42 non-null     object<br> 9   Year           88 non-null     object</pre><h4>6.3 Univariate Analysis</h4><p>Before performing the univariate analysis, we renamed all our attributes since the 2018 dataset attributes had a different name from the rest of the dataset.</p><p>After renaming, we went ahead to concatenate everything together.</p><p>We started by taking a statistical description of the whole dataset using the <strong>startup.describe(include= “all”) </strong>method. This resulted to the output below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQQTMBjz-nc7EsW_iIX1bg.png" /></figure><p>We all printed a summary of the various columns and their respective datatypes.</p><p>We decided to drop the following under-listed columns since they will not be relevant to our analysis:</p><ul><li>Founded</li><li>Founders</li><li>Investor</li></ul><p>Also, they didn’t have their corresponding attribute in the 2019,2020, and 2021 datasets; hence I decided to drop them. I could have replaced them with the mode and mean, but dropping them worked for me.</p><pre># We will start by plotting a histogram of the whole dataset to view the distrubution of the various numeric columns of the dataset<br><br>startup.hist(<br>    figsize=(15,15),<br>    layout=(4,3),<br>    bins=20<br>    );</pre><p>The output of the code was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*g7cWCFAQUZmKb1xrwssacA.png" /></figure><p>I also went ahead to plot a boxplot of the whole dataset to visualize my outliers.</p><pre># Used a boxplot to show distributions of the numeric data values.<br>startup.boxplot(figsize= (10,10))</pre><p>The output of the code was</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ZWKnjBfGqBcPd2TXx4rgTQ.png" /></figure><p>I made the following deductions from the univariate analysis:</p><p>- The Sector, Stage and HeadQuater attributes had missing values. Since they are all categorical attributes we will fill the missing values with the mode.</p><p>- From the descriptive analysis, the standard deviation for the amount column was high, which meant there were extreme values from the average. This was evident in the boxplot. Due to this, the median value will be used in our analysis.</p><h4>6.3.1 Filling The Missing Values</h4><p><strong>6.3.1.1 Handling the Sector and Stage Attribute</strong></p><p>We visualized the top ten values:</p><pre>plt.title(&quot;Sector vs Counts Charts&quot;)<br>plt.xlabel(&quot;Counts&quot;)<br>plt.ylabel(&quot;Sector&quot;)<br>startup[&quot;Sector&quot;]=startup[&quot;Sector&quot;].str.lower()<br>startup[&quot;Sector&quot;].value_counts().iloc[:10].plot.barh(figsize= (5,5));</pre><p>The output was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*9Q7nJOKstNzY97tKJknkIg.png" /></figure><p>We went ahead to fill in the missing values with the mode, which is fintech.</p><pre>startup[&#39;Sector&#39;] = startup[&#39;Sector&#39;].fillna(&quot;fintech&quot;)<br>startup[&#39;Sector&#39;]</pre><p>The same idea was repeated for the Stage attribute.</p><p><strong>6.3.1.2 The HeadQuarter Column:</strong></p><p>To fill in the missing values, I used the geolocator library to find and fill in the missing values.</p><p>I used the code below:</p><pre>geolocator = Nominatim(user_agent=&quot;Seville_LP1_&quot;)<br><br># loop over rows and fill in missing values for Location column<br>for index, row in startup.iterrows():<br>    if pd.isna(row[&#39;HeadQuarter&#39;]):<br>        # use geocoding service to find location based on company name<br>        HeadQuarter = geolocator.geocode(row[&#39;Company/Brand&#39;])<br>        if HeadQuarter is not None:<br>            startup.at[index, &#39;HeadQuarter&#39;] = HeadQuarter.address<br><br># print the updated dataset<br>print(startup)</pre><p>The output of this code filled the values of 46 rows. Some of the rows were dirty, so I had to clean them.</p><p>For example:</p><pre> &#39;Shaving Brush, Sant Savata Marg, Byculla East, E Ward, Zone 1, Mumbai, Mumbai City, Maharashtra, 400027, India&#39;,<br>       &#39;telangana&#39;, nan,<br>       &#39;Secret Trail Bamboo Stop, Lancaster - Open Canal Road, Navarro, Pasong Camachile I, General Trias, Cavite, Calabarzon, 4107, Philippines&#39;,<br>       &quot;Byju&#39;s, Hosur Road, Adugodi, South Zone, Bengaluru, Bangalore South, Bangalore Urban, Karnataka, 560030, India&quot;,<br>       &#39;gurugram&#39;, &#39;Springboard, Benton County, Oregon, United States&#39;,<br>       &#39;Bijak, Bada Malhera Tahsil, Chhatarpur, Madhya Pradesh, India&#39;,<br>       &#39;Trume Lane, East Penn Township, Carbon County, Pennsylvania, 18122, United States&#39;,</pre><p>I cleaned them by selecting their respective cities.</p><p>For the remaining rows the geolocator couldn’t find, I replaced them with the modal value of the HeadQuarter attribute.</p><h4>6.4 Bivariate Analysis</h4><p>Since our questions involved analyzing two columns, I went ahead to used them for my bivariate analysis.</p><p><strong>6.4.1 Question 1:</strong></p><p>Are start-ups located in specific areas more likely to succeed or to receive more financing than those located in other areas?</p><p>For this, we tried to look at companies that are based in India and to help us achieve this, we used the code below.</p><pre>df_q1= df_q1.groupby(&#39;HeadQuarter&#39;)[&#39;Amount($)&#39;].median().reset_index()<br>df_q1_sorted_top15 = df_q1.sort_values([&#39;Amount($)&#39;],ascending=False)[:15]<br>plt.figure(figsize= (10,5))<br>rects1 = plt.bar(df_q1_sorted_top15[&#39;HeadQuarter&#39;], df_q1_sorted_top15[&#39;Amount($)&#39;])<br># plt.ylim(0,615900000)<br>bar_ax1 = plt.gca()<br>for rectangle, size_ in zip(rects1,df_q1_sorted_top15[&#39;Amount($)&#39;].to_list()):<br>    if rectangle==rects1[0] or rectangle==rects1[1]: #check if this is first or second bar<br>        height_ = rectangle.get_height()*0.4<br>    else:<br>        height_ = rectangle.get_height()<br>    <br>    bar_ax1.text(rectangle.get_x() + rectangle.get_width()/2.0,height_,<br>                 &quot; $&quot;+str(size_),ha=&#39;center&#39;, va=&#39;bottom&#39;, ma=&#39;left&#39;,rotation=90)<br><br>plt.title(&#39;Median funding amounts per Top 15 Headquaters&#39;)<br>plt.xlabel(&#39;Headquater&#39;)<br>plt.ylabel(&#39;Average amount&#39;)<br>plt.xticks(rotation=90)<br>plt.show()</pre><p>The output of this code was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*Jar2snyMIJ0pWcqSuIigBQ.png" /></figure><p><strong>6.4.2 Question 2</strong></p><p>Has the amount of investments in the ecosystem increased over the 4 years (the datasets we are looking at), or has it decreased?</p><p>For this question, I used the code below:</p><pre>df_q2 = startup_2[[&#39;Year&#39;,&#39;Amount($)&#39;]]<br>df_q2[&quot;Amount($)&quot;]= pd.to_numeric(df_q2[&quot;Amount($)&quot;].astype(&quot;int64&quot;))<br>df_q2[&quot;Year&quot;]= pd.to_numeric(df_q2[&quot;Year&quot;].astype(&quot;int64&quot;))<br><br>df_q2_grouped = df_q2.groupby(&#39;Year&#39;).agg({&quot;Amount($)&quot;: &quot;sum&quot;}).reset_index()<br><br>plt.plot(df_q2_grouped[&#39;Year&#39;], df_q2_grouped[&#39;Amount($)&#39;])<br>plt.title(&#39;Total funding amounts per Year&#39;)<br>plt.xlabel(&#39;Year&#39;)<br>plt.ylabel(&#39;Total funding amount&#39;)<br>plt.xticks(list(range(int(df_q2_grouped[&#39;Year&#39;].min()), int(df_q2_grouped[&#39;Year&#39;].max())+1)), rotation=90)<br>plt.show()</pre><p>The output of the code is displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*Q_gEk1MboASu3cm6XvvhTw.png" /></figure><p>From there was a slight decrease in investment in the late part of 2018 and then an increase from 2019 to 2020 and an exponential increase from 2020 to 2021.</p><p><strong>6.4.3 Question 3</strong></p><p>What is the average investment amount received by Indian startups at different stages of their growth?</p><p>For this question, I used the code below</p><pre>df_q3 = startup[[&#39;Stage&#39;,&#39;Amount($)&#39;]]<br>df_q3[&quot;Amount($)&quot;] = pd.to_numeric(df_q3[&quot;Amount($)&quot;].astype(&quot;int64&quot;))<br>df_q3 = df_q3.groupby(&#39;Stage&#39;)[&#39;Amount($)&#39;].median().reset_index()<br>df_q3_sorted_top15 = df_q3.sort_values([&#39;Amount($)&#39;],ascending=True)[-5:]<br>df_q3.info()<br><br>plt.figure(figsize= (10,5))<br>plt.barh(df_q3_sorted_top15[&#39;Stage&#39;], df_q3_sorted_top15[&#39;Amount($)&#39;], color=&#39;brown&#39;)<br>plt.title(&#39;Top 5 Median funding amounts per Stage&#39;)<br>plt.xlabel(&#39;Stage&#39;)<br>plt.ylabel(&#39;Average funding amount&#39;)<br>plt.xticks(rotation=90)<br>plt.show()</pre><p>The output of the code was:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*N9A7PA_oqp3_pxjqYTkq_Q.png" /></figure><p><strong>6.4.4 Question 4</strong></p><p>Does the nature of the industry have any impact on the amount of funding received?</p><pre>df_q4 = startup[[&#39;Sector&#39;,&#39;Amount($)&#39;]]<br>df_q4[&quot;Sector&quot;]= df_q4[&quot;Sector&quot;].apply(lambda x:str(x).lower())<br>df_q4[&quot;Amount($)&quot;] = pd.to_numeric(df_q4[&quot;Amount($)&quot;].astype(&quot;int64&quot;))<br>df_q4 = df_q4.groupby(&#39;Sector&#39;)[&#39;Amount($)&#39;].sum().reset_index()<br>df_q4_sorted_top10 = df_q4.sort_values([&#39;Amount($)&#39;],ascending=True)[-10:]<br>df_q4.info()<br><br>plt.figure(figsize= (10,5))<br>plt.barh(df_q4_sorted_top10[&#39;Sector&#39;], df_q4_sorted_top10[&#39;Amount($)&#39;], color=&#39;#233&#39;)<br># plt.pie(df_q4_sorted_top10[&#39;Amount($)&#39;].tolist(), labels=df_q4_sorted_top10[&#39;Sector&#39;].tolist(), autopct=&#39;%1.1f%%&#39;)<br>plt.title(&#39;Top 10 total funding amounts per sector&#39;)<br>plt.xlabel(&#39;Total funding amount&#39;)<br>plt.ylabel(&#39;Sector&#39;)<br>plt.xscale(&#39;log&#39;) #Using log scale in order to fit all bars in view<br># plt.xticks(rotation=90)<br>plt.show()</pre><p>The output of the code is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*AWSknNpAYf84pwKivLDS9g.png" /></figure><p><strong>6.4.5 Question 5</strong></p><p>Q: Which startup (s) had the highest rate/count of funding (this counts the startup that occurred most but not with duplicate funding)?</p><p>For this question, I used the code below:</p><pre>df_q5 = startup[[&#39;Company/Brand&#39;,&#39;Amount($)&#39;]]<br>df_q5 = df_q5.groupby(&#39;Company/Brand&#39;).count().reset_index().rename(columns={&#39;Amount($)&#39;:&#39;Funding count&#39;})<br>df_q5_sorted_top10 = df_q5.sort_values([&#39;Funding count&#39;],ascending=False)[:10]<br>df_q5.info()<br><br>plt.figure(figsize= (10,5))<br><br>rects = plt.bar(df_q5_sorted_top10[&#39;Company/Brand&#39;], df_q5_sorted_top10[&#39;Funding count&#39;], color=list(&#39;rgbkymc&#39;))<br>bar_ax1 = plt.gca()<br>for rectangle, size_ in zip(rects,df_q5_sorted_top10[&#39;Funding count&#39;].to_list()):<br>    height_ = rectangle.get_height()<br>    bar_ax1.text(rectangle.get_x() + rectangle.get_width()/2.0,height_,<br>                 str(size_),ha=&#39;center&#39;, va=&#39;bottom&#39;, ma=&#39;left&#39;)<br><br>plt.title(&#39;Total funding count per company&#39;)<br>plt.xlabel(&#39;Company Name&#39;)<br>plt.ylabel(&#39;Total funding count&#39;)<br>plt.xticks(rotation=45)<br>bar_ax1 = plt.gca()<br>plt.show()</pre><p>The output of the code above is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hkp0sRr1VoRBvWORbEQvOQ.png" /></figure><p><strong>6.4.5 Question 6</strong></p><p>What Are the Top 5 Countries Outside India Dominating the Startup Market?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*-DoHiCubQlz-hj66ATxAzQ.png" /></figure><ul><li>Companies in the USA with presence in India had the most funding.</li></ul><h4>7.Hypothesis Testing</h4><p><strong>Null Hypothesis: </strong>Companies whose headquarters are located in the Indian capital city ( Delhi) are more likely to receive high funding than those located in other cities</p><p><strong>Alternate Hypothesis: </strong>Companies whose headquarters are located in the Indian capital city, (Delhi) do not necessarily receive more funding than those located in other cities</p><p>To prove this, I used the median test to find the median investments between companies in Delhi and those outside Delhi. After the test, I had to reject the null hypothesis and accept the alternate hypothesis.</p><p>I used the code below:</p><pre><br># subsetting the data for Delhi-based companies and non-Delhi-based companies<br>delhi_companies = startup_2[startup_2[&quot;HeadQuarter&quot;] == &quot;Delhi&quot;]<br>non_delhi_companies = startup_2[startup_2[&quot;HeadQuarter&quot;] != &quot;Delhi&quot;]<br><br># calculating the median funding amounts for each group<br>delhi_median = np.median(delhi_companies[&quot;Amount($)&quot;])<br>non_delhi_median = np.median(non_delhi_companies[&quot;Amount($)&quot;])<br><br># conduct a median test to compare the medians of the two groups<br>stat, p_val, med, tbl = median_test(delhi_companies[&quot;Amount($)&quot;], non_delhi_companies[&quot;Amount($)&quot;])<br><br>#print(&quot;P-value: {:.4f}&quot;.format(p_val))<br><br># draw a conclusion based on the p-value<br>if p_val &lt; 0.05:<br>    print(&quot;We reject the null hypothesis.&quot;)<br>else:<br>    print(&quot;We fail to reject the null hypothesis.&quot;)<br><br></pre><p>For the full code, ensure to check out the <a href="https://github.com/Greg-Art/EDA-of-Indian-Startup-Market/blob/main/code/notebooks/Seville_LP1_Final%20Version%20(2).ipynb">GitHub repository</a> for this notebook.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=380ddd985449" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>