<?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 Kodwo Amissah-Mensah on Medium]]></title>
        <description><![CDATA[Stories by Kodwo Amissah-Mensah on Medium]]></description>
        <link>https://medium.com/@kodwoam?source=rss-7dbd0a8ea794------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*J1iIcjgGQfHnWzT8tVzU6w.jpeg</url>
            <title>Stories by Kodwo Amissah-Mensah on Medium</title>
            <link>https://medium.com/@kodwoam?source=rss-7dbd0a8ea794------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:33:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kodwoam/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 Sepsis Prediction App Using FastApi]]></title>
            <link>https://medium.com/@kodwoam/building-a-sepsis-prediction-app-using-fastapi-5b07e074c57d?source=rss-7dbd0a8ea794------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b07e074c57d</guid>
            <dc:creator><![CDATA[Kodwo Amissah-Mensah]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 15:53:58 GMT</pubDate>
            <atom:updated>2023-12-05T02:24:08.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*eSsukhJu3rM_kDWA.png" /><figcaption>image credit:tiangolo.com</figcaption></figure><h3>1.INTRODUCTION</h3><p>In the ever-evolving landscape of healthcare technology, innovations that save lives and enhance patient care stand out as beacons of progress.</p><p>Sepsis, often referred to as the “silent killer,” is a medical emergency that arises when the body’s response to infection goes haywire, leading to severe inflammation and organ failure. Recognizing the critical importance of early detection in combating this formidable adversary, we embark on a journey into the realm of predictive healthcare with our Sepsis Prediction App built using the cutting-edge FastAPI framework.</p><h4><strong>Harnessing the Power of FastAPI:</strong></h4><p>At the heart of our endeavor lies FastAPI, a modern and efficient web framework for building APIs with Python 3.7+. Renowned for its speed, simplicity, and automatic interactive documentation capabilities, FastAPI empowers our application to deliver real-time predictions with unparalleled efficiency.</p><h3>2.Importing Libraries</h3><p>The code commences by importing crucial libraries, including FastAPI, uvicorn, and Query for app deployment, pandas for data manipulation, and joblib for loading the pre-trained model.</p><pre>##import libraries<br>from fastapi import FastAPI, Query<br>import uvicorn<br>import joblib<br>import pandas as pd</pre><h3>3. Loading the Model</h3><p>The best_rf_model.joblib pre-trained model is loaded using joblib, a widely-used library for serializing Python objects. This model, presumably utilizing the random forest algorithm, has undergone training to make predictions regarding sepsis based on specific input features.</p><pre>##load the model<br>model = joblib.load(&quot;Model/best_rf_model.joblib&quot;)</pre><h3>4. Defining the API with FastAPI</h3><p>FastAPI is used to define the API,but in our code it has to be instantiated.You can use any variable to instantiate fastapi here we used the variable called <strong>app</strong></p><pre>##create app object<br>app = FastAPI()</pre><p>Our code snippet establishes two main endpoints:</p><ul><li><strong>GET Endpoint: </strong>A get endpoint is used to retrieve information from a server.In our code,we use a basic welcome message that serves as a health check or an introduction to the API.</li></ul><pre>@app.get(&#39;/&#39;)<br>def home():<br>    return{&#39;message&#39;:&#39;Welcome to Sepsis Prediction Using Fastapi&#39;}</pre><ul><li><strong>POST Endpoint:</strong> A post endpoint is to send information to a server.It is more complex endpoint that predicts sepsis based on input parameters.</li></ul><pre>@app.post(&quot;/predict&quot;)<br>def predict_sepsis(<br>    Plasma_glucose: int = Query(..., description=&quot;Plasma_glucose&quot;),<br>    Blood_Work_R1: int = Query(..., description=&quot;Blood_Work_R1&quot;),<br>    Blood_Pressure: int = Query(..., description=&quot;Blood_Pressure&quot;),<br>    Blood_Work_R2: int = Query(..., description=&quot;Blood_Work_R2&quot;),<br>    Blood_Work_R3: int = Query(..., description=&quot;Blood_Work_R3&quot;),<br>    BMI: float = Query(..., description=&quot;BMI&quot;),<br>    Blood_Work_R4: float = Query(..., description=&quot;Blood_Work_R4&quot;),<br>    Age: int = Query(..., description=&quot;Age&quot;)</pre><p>The POST endpoint, defined under /predict/, takes in various parameters, including Plasma_glucose, Blood_Pressure, BMI, and other blood work-related variables.With these variables you can see in the code i used a query.</p><p>This query is used to define query parameters.These query parameters are used to send or add additional information when sending a request.</p><p>To use a query you do the following:</p><ul><li>State your variable</li><li>State your data type</li><li>define your query</li><li>input a default value in my code i used(…….)</li><li>add a description for the variable</li></ul><p>These are then processed into a DataFrame, which is fed into the model for prediction.</p><pre># Convert input data to the format expected by the model<br>        input_data = pd.DataFrame([{<br>            &quot;Plasma_glucose&quot;: Plasma_glucose,<br>            &quot;Blood_Work_R1&quot;: Blood_Work_R1,<br>            &quot;Blood_Pressure&quot;: Blood_Pressure,<br>            &quot;Blood_Work_R2&quot;: Blood_Work_R2,<br>            &quot;Blood_Work_R3&quot;: Blood_Work_R3,<br>            &quot;BMI&quot;: BMI,<br>            &quot;Blood_Work_R4&quot;: Blood_Work_R4,<br>            &quot;Age&quot;: Age<br>        }])<br><br>        # Make prediction<br>        prediction = model.predict(input_data)[0]<br><br>        sepsis_status = &quot;Patient has sepsis&quot; if prediction == 1 else &quot;Patient does not have sepsis&quot;<br><br>        # Return the prediction<br>        return {&quot;prediction&quot;: sepsis_status}</pre><h3>5. Running the Application</h3><p>Finally, the application is run using Uvicorn when executed as a standalone script.</p><p>To use the uvicorn to run your code, in your cmd type:</p><p><strong>uvicorn main:app</strong></p><p>Main here is the name i used to save my fast api file and the app is what i use to instantiate the fastapi</p><p>You can view my deployed fastapi app <a href="https://kodwo11-sepsisapp.hf.space/docs">by using the link</a></p><h3>6.Conclusion</h3><p>FastAPI plays a pivotal role by offering a user-friendly and efficient means to deploy the model, ensuring its accessibility to various systems and front-end applications. It serves as an excellent demonstration of how Python libraries effectively connect the realms of machine learning research and practical, real-world applications.</p><p>The integration of this API into hospital systems or healthcare applications provides an immediate and indispensable tool for doctors and medical professionals. This tool has the potential to play a critical role in the early detection and treatment of sepsis, potentially leading to life-saving interventions.</p><p>Feel free to visit <a href="https://github.com/KodwoAmissah/Sepsis-Modelling-Using-FastAPI">my github</a> for extra information</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b07e074c57d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Pre-trained Models to Predict Twitter Sentiments]]></title>
            <link>https://medium.com/@kodwoam/using-pre-trained-models-to-predict-twitter-sentiments-41895f4051c9?source=rss-7dbd0a8ea794------2</link>
            <guid isPermaLink="false">https://medium.com/p/41895f4051c9</guid>
            <dc:creator><![CDATA[Kodwo Amissah-Mensah]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 17:20:39 GMT</pubDate>
            <atom:updated>2023-11-10T17:20:56.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*-Yak8F1YerefkEd0" /><figcaption>Image credit:TurboLab</figcaption></figure><p>Hello and welcome to another interesting and informative article.In this article, we will explore the process of fine-tuning a pre-trained model for text classification. Specifically, our focus will be on fine-tuning the model using a dataset consisting of COVID-19-related tweets.</p><p>The COVID-19 pandemic has redefined our world. From the moment the virus emerged, to the chaos of the early days, through lockdowns, vaccine distributions, and debates about how to move forward, the pandemic has provided an unceasing narrative of human emotions. These emotions, as diverse and unpredictable as the virus itself, have found a voice on social media platforms, with Twitter being a vital arena for individuals to express their fears, hopes, frustrations, and solidarity.</p><p>With the amount of COVID-19 related tweets that are generated each day, there is a golden opportunity to harness the power of natural language processing and deep learning to analyze and predict the sentiments embedded within these messages.</p><p>As an aspiring data scientist, I was given the responsibility of analyzing these tweets using pre-trained transformer models.We will delve into the realm of pretrained language models and their application in predicting sentiments from COVID-19-related tweets.</p><p>Before we dive into the analysis, it’s important to mention that for this sentiment analysis, I fine-tuned two pre-trained models: Distilbert Base Uncased and Roberta Base. You can access and explore these deployed models below:</p><ul><li><a href="https://huggingface.co/Kodwo11/Kodwo-Finetuned-distilbert-model"><strong>Distilbert Base Uncased</strong></a></li><li><a href="https://huggingface.co/Kodwo11/Roberta-Sentiment-Classifier"><strong>Roberta Base</strong></a></li></ul><p>As usual, this article will be using the CRISP-DM framework.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>With that being said you view <a href="https://huggingface.co/spaces/Kodwo11/Sentiment_Analysis"><strong>my deployed app</strong></a><strong>.</strong></p><p>Now let’s begin with the article.</p><h3>1.Business Understanding</h3><p>Twitter, as a global platform for real-time discussions, plays a pivotal role in shaping public sentiment, especially during significant events like the COVID-19 pandemic. Analyzing the sentiments expressed in COVID-19 related tweets has become crucial for businesses and decision-makers to navigate these challenging times effectively.Below are some objectives for businesses.</p><p>1.Businesses intend to identify emerging trends and topics within the COVID-19 conversation. This insight can be valuable for adjusting marketing strategies, product offerings, and customer engagement.</p><p>2. Monitoring public sentiment helps in identifying potential risks, such as negative sentiment towards specific industries, products, or services. Timely detection of such risks allows businesses to take preventive measures.</p><p>3. Positive sentiment can uncover opportunities. For instance, recognizing a surge in positive sentiment towards remote work can drive businesses to cater to the changing needs of remote workers.</p><p>Here are the benefits for the business</p><p><strong>Benefits:</strong></p><ol><li><strong>Enhanced Customer Understanding</strong>: By analyzing sentiment, businesses can gain a deeper understanding of how their customers feel about the pandemic and the products or services offered.</li><li><strong>Adaptive Strategies:</strong> Insights from sentiment analysis enable businesses to adapt their strategies to meet changing customer needs and concerns.</li><li><strong>Risk Mitigation</strong>: Identifying and addressing negative sentiment early can prevent potential issues from escalating and protect a brand’s reputation.</li><li><strong>Data-Driven Decision-Making:</strong> Using pre-trained models for sentiment analysis empowers organizations to make data-driven decisions and stay responsive to the evolving public sentiment.</li></ol><p>In conclusion, by understanding the sentiments expressed on social media, businesses can make informed decisions, manage risks, and identify emerging opportunities.</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 had 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>: The tweets were labeled by three people. Agreement indicates the percentage of the three reviewers that agreed on the given label.It shows the confidence level for each sentiment.</li></ul><h4>2.2 Libraries Used:</h4><p>I used these libraries for preprocessing and visualizations</p><pre>### Load Libraries<br>%%capture<br>##for data handling<br>import pandas as pd<br>import numpy  as np<br>import os<br><br>##visualizations<br>import matplotlib.pyplot as plt<br>import plotly.express as px<br>import seaborn as sns<br><br><br>#NLP<br>import re<br>import nltk<br>from collections import Counter</pre><h4>2.2.1 Data Overview and EDA</h4><p>In this section we will explore the data to see if there any inconsistencies or irregularities that may be present.</p><h4>2.2.2 Checking for Missing Values</h4><p>I started by checking for missing values using the code below.</p><pre>#checking for missing values in train data<br>df_train.isnull().sum()<br><br>#check for missing values in test data<br>df_test.isnull().sum()</pre><p>The results are shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*TkCHH2CvpXZHJIozGtWwrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*oF99qe4021QOlK0Q51ST1A.png" /></figure><p>These missing values will be handled in the data preparation stage.</p><h4>2.2.3 Visualizations</h4><p>The next step is to use visuals to better understand my data</p><p>i. Checking the distribution of the Label</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*dO11GtiVc6UObJwiW5lk9Q.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></ul><p><strong>ii. Visualizing Word Count:</strong></p><p>I aimed to create visualizations that illustrate the lengths of tweets related to COVID-19.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyGYjjIO_XOnPY3qi3VIDA.png" /></figure><p>From the image,most tweets are between 15–20 words with 18 being the highest.</p><h3>3. Data Preparation</h3><p>Upon conducting a thorough exploration and gaining deeper insights into the data, we will then proceed to perform data preprocessing and cleaning. This step is essential to ensure that the data is appropriately prepared for training, and it involves applying various Natural Language Processing (NLP) techniques to make the data compatible for the model.</p><p>To achieve this,i performed the following steps</p><ul><li>I renamed the “safe_text” feature to “tweets for easier readability and understanding”</li><li>I decided to eliminate the “tweet_id” feature, as it didn’t provide any significant value to the analysis.</li><li>To ensure uniformity and facilitate text processing, I converted all text to lowercase.</li></ul><h4>3.1 Handling Missing Values</h4><p>As mentioned earlier in the article, there are a few missing values in the dataset. However, since there are just a few missing values, we opted to handle this by simply removing the missing values.</p><pre>##dropping missing values<br>df_train.dropna(inplace=True)<br>df_test.dropna(inplace=True)</pre><p>The code above gave me this result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*8mEQSOv8bRHhwsJP-xIwIQ.png" /></figure><p>You can clearly see the absence of missing values</p><h4>3.2 Removing Punctuations or Special Charcaters</h4><p>Taking out punctuation and special characters from text makes it simpler and easier to work with. This helps ensure that the analysis and processing of text are consistent, as the essential meaning of a sentence is conveyed through its words, not punctuation marks or symbols.</p><p>These special characters include:</p><ol><li>!- Exclamation mark</li><li>@ — At symbol</li><li>#- Hashtag</li><li>$ — Dollar sign</li><li>% — Percent sign</li><li>&amp; — Ampersand</li><li>*-Asterisk</li><li>{ } — Braces</li><li>&lt; &gt; — Angle brackets</li></ol><p>To remove these special characters and punctuation&#39;s i used the code below</p><pre>def remove_characters(characters):<br>  #remove special chracters<br>  characters=re.sub(r&#39;#\w+&#39;, &#39;&#39;, characters)<br>  ##removing punctuations<br>  characters= re.sub(&quot;[^\w\s]&quot;,  &quot;&quot;, characters)<br>  return characters</pre><p>The image below will show the texts that include the special characters</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*coybw47qwkwe3HOxvwMpEg.png" /><figcaption>special characters in text</figcaption></figure><p>We will apply the function to our train and test to remove these special characters</p><pre># Apply the function to df_train<br>df_train[&quot;tweets&quot;] = df_train[&quot;tweets&quot;].apply(remove_characters)<br><br># Apply the function to df_test<br>df_test[&quot;tweets&quot;] = df_test[&quot;tweets&quot;].apply(remove_characters)</pre><p>The result of the above code is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*nKdrgDlfZOtuc6kGifB5oQ.png" /><figcaption>special characters removed</figcaption></figure><p>With the above image,we can clearly see the special characters have been removed.</p><h4>3.3 Removing Unnecessary Words and Numbers</h4><p>I observed that certain words, such as “user” and “url,” were prevalent in the text data. “User” typically indicated instances where someone was tagged, and “url” was used when a user included an external web link in their tweet. However, for our analysis, these words didn’t provide any meaningful information, so we decided to remove them.</p><p>Additionally, we eliminated numerical digits from the text because they didn’t contribute to the content of the tweets.</p><pre>#removing url and user word<br>def remove_words(text, words_to_remove):<br>    words = text.split()<br>    # Remove specified words<br>    filtered_words = [word for word in words if word not in words_to_remove]<br>    # Join the filtered words back into a string<br>    filtered_text = &quot; &quot;.join(filtered_words)<br>    return filtered_text<br><br># Define the words to remove<br>words_to_remove = [&quot;user&quot;, &quot;url&quot;]<br><br># Apply the remove_words function to the &quot;tweets&quot; column<br>df_train[&quot;tweets&quot;] = df_train[&quot;tweets&quot;].apply(lambda x: remove_words(x, words_to_remove))<br>df_test[&quot;tweets&quot;] = df_test[&quot;tweets&quot;].apply(lambda x: remove_words(x, words_to_remove))<br><br>#remove 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>#Apply to train and test<br>df_train[&quot;tweets&quot;]= df_train[&quot;tweets&quot;].apply(number_remover)<br>df_test[&quot;tweets&quot;]=df_test[&quot;tweets&quot;].apply(number_remover)</pre><p>When the above code is applied,the unnecessary words and numbers are removed.</p><p>I then went ahead to visualize the top 10 most frequent words in our dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*ou5JMRGW288Sy-6W_7qadw.png" /></figure><h3>4.Modelling</h3><p>Using my preprocessed dataset, the next stage involved model development. I proceeded to fine-tune a pre-trained model. Pre-trained models are algorithms, often referred to as transformers, that have undergone training on extensive datasets. These pre-trained models can then be harnessed for a range of Natural Language Processing (NLP) tasks.</p><p>I choose to fine-tune two pre-trained models:</p><ul><li><strong>DistilBert base uncased</strong></li><li><strong>Roberta base</strong></li></ul><p>Both of these models were obtained from Hugging Face.</p><p>I fine tuned both these models and realized that Roberta base gave the lowest eval lowest and accuracy which is a metric we will use to determine the best model</p><p>With that being said in this section i will show you how i fine tuned my <strong>Roberta</strong> base model.</p><p><strong>NB:To train these models it requires a very high computational power and since our local machines do not posses this computational power we used google colab since it gives a free GPU which will be suitable to train these models.</strong></p><p>Having said that, below are the libraries I used for my modelling:</p><pre>## Load Libraries<br>%%capture<br>##for data handling<br>import pandas as pd<br>import numpy  as np<br>import os<br><br>##visualizations<br>import matplotlib.pyplot as plt<br>import plotly.express as px<br>import seaborn as sns<br><br><br>#NLP<br>from transformers import TrainingArguments<br>from scipy.special import softmax<br>import torch<br>from transformers import Trainer<br>import torch<br>from transformers import AutoTokenizer, AutoModelForSequenceClassification<br><br>## Modellling<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import f1_score<br>import transformers<br>from datasets import load_dataset<br>from datasets import load_metric<br>from torch import nn<br>##for handling path of my datasets<br>import os<br># Disabe W&amp;B<br>os.environ[&quot;WANDB_DISABLED&quot;] = &quot;true&quot;<br>from google.colab import drive<br>from huggingface_hub import notebook_login</pre><h4>4.1. Fine-Tuning A Pre-trained Model (RoBerta)</h4><p><strong>i.Reloading my Data</strong></p><p>Following the data cleaning process, I saved the cleaned dataset. However, upon reloading it in a new notebook for modeling, I encountered some unexpected issues. Specifically, I noticed missing values and an additional column. I suspect that these discrepancies may have arisen from encoding problems during the save and reload operation.</p><p>Therefore to avoid these issues i just dropped the missing values and this column.</p><p><strong>ii. Splitting my Data</strong></p><p>Upon reloading the data, the next task was to divide it into two distinct sets: the training set and the evaluation set. I opted for an 80/20 split, and I also utilized the<strong> stratify</strong> feature. In this classification project, stratification ensures that the labels are evenly distributed between the split, maintaining a balanced representation of each sentiment category.</p><p>iii<strong>. Using the “datasets” Library</strong></p><p>This library provides a module called <strong>load_dataset</strong>, which allows us to load our datasets in a structured format.I accomplished this using the following code:</p><pre>dataset= load_dataset(&quot;csv&quot;, data_files= { &quot;train_set&quot;:&quot;train_set.csv&quot;, &quot;eval_set&quot;:&quot;eval_set.csv&quot;})</pre><p><strong>iv. Tokenization</strong></p><p>With our dataset prepared, the next stage involves tokenizing the sentences. This process entails breaking down the sentences into words and then encoding or converting them into numerical representations, as required by the model for understanding.</p><p>Before proceeding, I ensured that I transformed my labels from -1, 0, 1 to 0, 1, 2, respectively. This adjustment is made because most pre-trained models typically associate 0 with negative, 1 with neutral, and 2 with positive sentiment. Therefore, this transformation is generally recommended.</p><p>The initial step in tokenization involves importing a tokenizer that is tailored to the specific model we’re using. In my case, I used the AutoTokenizer. However, it’s important to note that some models have their own custom tokenizers.</p><p>I used the code below:</p><pre>##instantiate model<br>robert= &quot;roberta-base&quot;<br><br>##use tokenizer on model<br>tokenizer = AutoTokenizer.from_pretrained(robert)</pre><p>I proceeded by then creating a function to facilitate the tokenization process and handle the label mapping I mentioned previously. This mapping assigns 0 for negative sentiment, 1 for neutral, and 2 for positive sentiment.</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(label):<br><br>    label = label[&#39;label&#39;]<br>    num = 0<br>    if label == -1: #&#39;Negative&#39;<br>        num = 0<br>    elif label == 0: #&#39;Neutral&#39;<br>        num = 1<br>    elif label == 1: #&#39;Positive&#39;<br>        num = 2<br><br>    return {&#39;labels&#39;: num}<br><br>def tokenize_data(example):<br>    return tokenizer(example[&#39;tweets&#39;], padding=&#39;max_length&#39;)</pre><ul><li>I am telling my tokenizer to target the tweets 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></ul><p>After implementing the function above, the dataset had its final structure, depicted as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*RDPd_bMUg5sgowlejrvSmA.png" /></figure><p><strong>v.Importing Model</strong></p><p>The next step was to import the model using the code below:</p><pre># Loading a pretrain model while specifying the number of labels in our dataset for fine-tuning<br><br>model = AutoModelForSequenceClassification.from_pretrained(robert, num_labels=3)</pre><p><strong>vi.Dealing with class imbalance</strong></p><p>Addressing the issue of class imbalance, I assigned class weights based on the distribution of each class. To handle the imbalance, the class with a lower distribution was assigned a higher weight, while the class with a higher distribution received a lower weight. Our exploratory data analysis (EDA) revealed that the -1 class, which now corresponds to our 0 class, was imbalanced, and we will address this concern with the code below.</p><pre># Calculate class weights<br>class_weights= (1-(df[&quot;label&quot;].value_counts().sort_index() /len(df))).values</pre><p>Following the assignment of class weights, we needed to transfer the class_weights to the CPU because we were working in a Google Colab environment. To achieve this, we utilized the code snippet below:</p><pre># uploading class weights to GPU<br>class_weights = torch.from_numpy(class_weights).float().to(&quot;cuda&quot;)</pre><p>It is worth noting that I also set my evaluation metric to accuracy since after adding class weights we have balanced the dataset.</p><pre>metric = load_metric(&quot;accuracy&quot;)<br><br>def compute_metrics(eval_pred):<br>    logits, labels = eval_pred<br>    predictions = np.argmax(logits, axis=-1)<br>    return metric.compute(predictions=predictions, references=labels)</pre><p><strong>vii.Defining Training Arguments</strong></p><p>A “training argument” typically refers to a set of configuration or hyper parameters that define how a machine learning model should be trained. These arguments provide instructions to the training process, such as the number of training epochs, learning rate, batch size, and more. Training arguments are essential for controlling the training process and fine-tuning a model.</p><p>With that being said these are training arguments we used for our model and they are shown in the code below:</p><pre> #Configure the trianing parameters like `num_train_epochs`:<br>training_args = TrainingArguments(output_dir=&quot;Roberta-Sentiment-Classifier&quot;,<br>                                  learning_rate=1e-05,<br>                                  num_train_epochs=5,<br>                                  load_best_model_at_end=True,<br>                                  evaluation_strategy=&quot;steps&quot;,<br>                                  save_strategy=&quot;steps&quot;,<br>                                  push_to_hub=True)</pre><ol><li><strong>output_dir: </strong>This parameter specifies the directory where the trained model and associated files will be saved once the training is complete. It&#39;s where the model checkpoints, configuration files, and other artifacts will be stored.</li><li><strong>learning_rate</strong>: Learning rate is a crucial hyperparameter in machine learning and deep learning. It determines the step size at which the model updates its parameters during training. A smaller learning rate results in slower and more stable training, while a larger learning rate can speed up training but may make it less stable.</li><li><strong>num_train_epochs</strong>: This parameter defines the number of times the training data will be passed through the model. Each pass through the entire training dataset is known as an epoch. The number of epochs is a key factor in determining how long the model will be trained.</li><li><strong>load_best_model_at_the_end</strong>: This setting specifies whether to load and save the best model based on the evaluation metric at the end of training. It&#39;s a useful feature to ensure that the best-performing model is saved.</li><li><strong>evaluation_strategy</strong>: This parameter defines how often the model&#39;s performance is evaluated on the validation dataset during training. &quot;steps&quot; means that evaluation is performed at regular intervals specified by the eval_steps parameter, while other options like &quot;epoch&quot; would mean evaluation after each training epoch.</li><li><strong>save_strategy</strong>: Similar to the evaluation strategy, this parameter determines when model checkpoints are saved. &quot;steps&quot; means that checkpoints are saved at regular intervals defined by the save_steps parameter.</li><li><strong>push_to_hub</strong> : When set to <strong>True,</strong>this option allows you to push your trained model to the Hugging Face Model Hub. The Model Hub is a platform for sharing, discovering, and using pre-trained models and resources.</li></ol><p>Finally, I used the seed shuffle to have a fixed batch size throughout the training and eval process.</p><p>To accurately train the model,I created a custom class to feed the class weight to the model.</p><pre>#since I will be leveraging the class_weights, I am creating a custom trainer<br>class CustomTrainer(Trainer):<br>    def compute_loss(self, model, inputs, return_outputs=False):<br>        labels = inputs.pop(&quot;labels&quot;)<br>        # forward pass<br>        outputs = model(**inputs)<br>        logits = outputs.get(&quot;logits&quot;)<br>        loss_fct = nn.CrossEntropyLoss(weight=class_weights)<br>        loss = loss_fct(logits,labels)<br>        return (loss, outputs) if return_outputs else loss</pre><p><strong>viii.Instantiating my train</strong></p><p>Now we instantiate our train and train our model.The code below will show this</p><pre>#instantiating my trainer<br><br>trainer = CustomTrainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=train_dataset,<br>    eval_dataset=eval_dataset,<br>    tokenizer= tokenizer,<br>    compute_metrics=compute_metrics<br><br>)<br>##training my model<br>trainer.train()</pre><p>This was the performance of the model afterwards:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*3G_G5pweBxFPbXbmes14Hg.png" /></figure><p>We followed the same process for the Distilbert base uncased model. Our choice of the Roberta base model as the superior one was based on its higher accuracy and lower training loss. To provide a clearer picture, here are the training loss and accuracy metrics for both models:</p><p><strong>For the Roberta base model:</strong></p><ul><li>Training Loss: [0.6644]</li><li>Accuracy: [0.7593]</li></ul><p><strong>For the Distilbert base uncased model:</strong></p><ul><li>Training Loss: [0.6743]</li><li>Accuracy: [ 0.749 ]</li></ul><p>These metrics highlight the superior performance of the Roberta base model in terms of accuracy and training loss when compared to the Distilbert base uncased model.</p><h3>5. Deployment</h3><p>The fine-tuned model was pushed to HuggingFace using this code</p><pre>## push to hub<br>trainer.push_to_hub()</pre><p>Then I created an app using Streamlit which i eventually deployed on hugging face.</p><p>Kindly do well to <a href="https://github.com/KodwoAmissah/Sentiment-Analysis"><strong>check out the GitHub repository</strong></a><strong> </strong>of the project.</p><p>You can visit <a href="https://huggingface.co/Kodwo11"><strong>my hugging face profile</strong></a><strong>.</strong></p><p>You can check out the <a href="https://huggingface.co/spaces/Kodwo11/Sentiment_Analysis"><strong>app by using this link</strong></a><strong>.</strong></p><p>I also used docker to deploy the app which can also be <a href="https://huggingface.co/spaces/Kodwo11/Sentiment_app"><strong>viewed here.</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41895f4051c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Deploying a Machine Learning App Using Gradio to Predict if a Customer will Churn or…]]></title>
            <link>https://medium.com/@kodwoam/building-and-deploying-a-machine-learning-app-using-gradio-to-predict-if-a-customer-will-churn-or-2fd3ae3cb2b2?source=rss-7dbd0a8ea794------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fd3ae3cb2b2</guid>
            <dc:creator><![CDATA[Kodwo Amissah-Mensah]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 15:05:55 GMT</pubDate>
            <atom:updated>2023-10-10T15:26:36.203Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building and Deploying a Machine Learning App Using Gradio to Predict if a Customer will Churn or Not</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*KpDeA-urMZBVLs3W6sno4Q.jpeg" /></figure><p>Hello and welcome, everyone. Before we delve into this article, I recommend reading my <a href="https://medium.com/@kodwoam/churn-prediction-analysis-for-customer-retention-at-vodafone-ae8774d22c09">second article</a> as it relates to the topic. However, feel free to continue reading this article, as it will provide valuable insights on its own.</p><p>So, what is the focus of this article? This article aims to guide you through the process of creating a user interface for my classification model. In my previous article, I discussed the training of various models, and I have chosen to build an interface for the model that performed the best.</p><p>If you simply want to experience the app, you can access it by following <a href="https://huggingface.co/spaces/Kodwo11/Churn_prediction">this link.</a></p><p>Shall we begin with this article</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 Python library that allows you to quickly create user interfaces for your machine learning models. It simplifies the process of building interactive web-based interfaces for your models, enabling users to interact with your models without writing code. Gradio provides a simple API for defining the input and output components of your interface, making it easy to create interactive demos, share your models, or gather user feedback. It supports various input types, such as text, images, audio, and video, and offers a range of UI components for displaying results. Gradio is particularly useful for showcasing your models, creating prototypes, and making machine learning models more accessible to non-technical users.</p><p>To create a gradio interface you need three parameters</p><ul><li>Your Function (fn)</li><li>Your Input (inputs)</li><li>Your Output (outputs)</li></ul><p>These three parameters are mainly the building blocks you need for your interface.</p><h3>2.Backend</h3><p>How did my app operate? It’s rather straightforward. I constructed a pipeline to streamline the modeling process, making it more convenient for deployment.</p><h4>Step 1:Dumping and Loading My Pipeline</h4><p>Below is an image of my pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*h87xJZhvae2RaCiadqkllQ.png" /></figure><p>As you can see in the image, my pipeline includes the scaler, encoder, and the model itself. Consequently, when I load my model, the pipeline encompasses all these components, eliminating the need to separately load the scaler and encoder.</p><p>I began by saving (or “dumping”) my model from my notebook using Joblib. Here’s the code for this process:</p><pre># Specify the directory path where you want to save the files<br>save_directory = &#39;C:\\Users\\User\\Desktop\\Models\\&#39;<br><br># Save the best model<br>joblib.dump(best_model, save_directory + &#39;best_model.pkl&#39;)</pre><h3>Step 2: Creating my Function</h3><p>To set up the functions for making predictions:</p><ul><li>I defined the function parameters, ensuring that it accepted the same number and had the same names for inputs as the ones used during the model training process. Additionally, I implemented a line of code that displays the message “Please fill in all input values” when the user does not enter a value for any of the input fields.</li></ul><pre># Create a Gradio interface<br>def predict_churn(SeniorCitizen, Partner, Dependents, tenure, InternetService,<br>                  OnlineSecurity, OnlineBackup, DeviceProtection, TechSupport,<br>                  StreamingTV, StreamingMovies, Contract, PaperlessBilling,<br>                  PaymentMethod, MonthlyCharges, TotalCharges):<br># Check if any of the inputs are missing<br>    if any([SeniorCitizen is None, Partner is None, Dependents is None, tenure is None,<br>            InternetService is None, OnlineSecurity is None, OnlineBackup is None,<br>            DeviceProtection is None, TechSupport is None, StreamingTV is None,<br>            StreamingMovies is None, Contract is None, PaperlessBilling is None,<br>            PaymentMethod is None, MonthlyCharges is None, TotalCharges is None]):<br>        error_message = &#39;&lt;span style=&quot;color: red;font-size:25px;&quot;&gt;Please fill in all the input fields.&lt;/span&gt;&#39;<br>        return error_message</pre><ul><li>Next, I proceeded to build a dictionary to correspond with the input parameters. Given that my model was trained using a dataframe, I compiled a list containing my input parameters and subsequently converted this list into a dataframe, which I named input_df as shown below:</li></ul><pre># Create a dictionary with input features<br>    input_data = {<br>        &#39;SeniorCitizen&#39;: SeniorCitizen,<br>        &#39;Partner&#39;: Partner,<br>        &#39;Dependents&#39;: Dependents,<br>        &#39;tenure&#39;: tenure,<br>        &#39;InternetService&#39;: InternetService,<br>        &#39;OnlineSecurity&#39;: OnlineSecurity,<br>        &#39;OnlineBackup&#39;: OnlineBackup,<br>        &#39;DeviceProtection&#39;: DeviceProtection,<br>        &#39;TechSupport&#39;: TechSupport,<br>        &#39;StreamingTV&#39;: StreamingTV,<br>        &#39;StreamingMovies&#39;: StreamingMovies,<br>        &#39;Contract&#39;: Contract,<br>        &#39;PaperlessBilling&#39;: PaperlessBilling,<br>        &#39;PaymentMethod&#39;: PaymentMethod,<br>        &#39;MonthlyCharges&#39;: MonthlyCharges,<br>        &#39;TotalCharges&#39;: TotalCharges<br>    }<br>    <br>    # Create a DataFrame from the input data<br>    input_df = pd.DataFrame([input_data])</pre><ul><li>The next step was to make my prediction, and with this, I simply pass the input_df through my model.</li></ul><pre># Make predictions<br>    prediction = model.predict(input_df)</pre><ul><li>Finally, I went ahead to use the prediction for the output of my function</li></ul><pre># Determine the churn prediction<br>    if prediction[0] == 0:<br>        churn_result = &#39;&lt;span style=&quot;color: limegreen;font-size:20px;&quot;&gt;Customer will not churn&lt;/span&gt;&#39;<br>    else:<br>        churn_result = &#39;&lt;span style=&quot;color: red;font-size:20px;&quot;&gt;Customer will churn&lt;/span&gt;&#39;<br>    <br>    return churn_result</pre><p>In the output shown in the image above, I utilized a span style to select a color that indicates whether a customer will churn or not.</p><h3>3.Front End</h3><p>In this section, I’ll guide you through the process of crafting my visually appealing output. For this purpose, I harnessed the power of 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><li>Gradio Dropdown:gr.dropdown()</li></ul><h4>Creating My Front-End Gradio Blocks:</h4><p>In Gradio, the gr.interface() function is typically used to create a default interface that arranges user inputs vertically. However, if you want to change the layout to a row and column order, you can achieve this by using gr.blocks().</p><p>Gradio Blocks is a feature in Gradio, an open-source Python library for building interfaces for machine learning models. Gradio Blocks allows you to create complex and customizable user interfaces by arranging different UI components (blocks) in a grid-like layout. These blocks can include input components like text boxes, sliders, and buttons, as well as output components for displaying results, images, or charts. By using Gradio Blocks, you can design interactive and user-friendly interfaces for your machine learning models with ease.</p><p>To use gradio blocks this is what you do:</p><ul><li>Begin by creating an instance of the blocks class and save it as a variable. Once you&#39;ve done this, you can select your preferred theme to apply and customize the colors for your app.</li></ul><pre>with gr.Blocks(theme=gr.themes.Base(primary_hue=&quot;stone&quot;,neutral_hue=&quot;stone&quot;)) as block:</pre><ul><li>Within the blocks, you can apply Markdown, which acts like a title. To change the appearance from the default horizontal layout in gr.Interface(), you can define your inputs within a combination of gr.Row()`and gr.Column()` This setup allows you to have a single row of inputs, and depending on how many gr.Column() instances you use, it will determine the number of columns for your interface.</li></ul><pre>gr.Markdown(<br>        &quot;&quot;&quot;# 👋 Welcome to Team Cape Cod&#39;s Churn Prediction App<br><br>                This App predicts whether a customer will churn or not&quot;&quot;&quot;)<br>    <br>    with gr.Row():<br>        with gr.Column():<br>            SeniorCitizen = gr.Radio([&quot;Yes&quot;, &quot;No&quot;], label=&quot;Are you a Senior Citizen?&quot;)<br>            Partner = gr.Radio([&quot;Yes&quot;, &quot;No&quot;], label=&quot;Do you have a partner?&quot;)<br>            Dependents = gr.Radio([&quot;Yes&quot;, &quot;No&quot;], label=&quot;Do you have dependents?&quot;)<br>            tenure = gr.Number(label=&quot;Tenure (months): How long have you been at the company&quot;,minimum=0)<br>            InternetService = gr.Radio([&quot;DSL&quot;, &quot;Fiber optic&quot;, &quot;No&quot;], label=&quot;What Internet Service Do You Use?&quot;)<br>            OnlineSecurity = gr.Radio([&quot;Yes&quot;, &quot;No&quot;, &quot;No internet service&quot;], label=&quot;Do You Have Online Security?&quot;)<br>            <br>        with gr.Column():<br>            OnlineBackup = gr.Radio([&quot;Yes&quot;, &quot;No&quot;, &quot;No internet service&quot;], label=&quot;Do You Have Any Online Backup Service?&quot;)<br>            DeviceProtection = gr.Radio([&quot;Yes&quot;, &quot;No&quot;, &quot;No internet service&quot;], label=&quot;Do You Use Any Device Protection?&quot;)<br>            TechSupport = gr.Radio([&quot;Yes&quot;, &quot;No&quot;, &quot;No internet service&quot;], label=&quot;Do You Use TechSupport?&quot;)<br>            StreamingTV = gr.Radio([&quot;Yes&quot;, &quot;No&quot;, &quot;No internet service&quot;], label=&quot;Do You Stream TV?&quot;)<br>            StreamingMovies = gr.Radio([&quot;Yes&quot;, &quot;No&quot;, &quot;No internet service&quot;], label=&quot;Do You Stream Movies?&quot;)<br>            <br>        with gr.Column():<br>            Contract = gr.Radio([&quot;Month-to-month&quot;, &quot;One year&quot;, &quot;Two year&quot;], label=&quot;What Is Your Contract Type?&quot;)<br>            PaperlessBilling = gr.Radio([&quot;Yes&quot;, &quot;No&quot;], label=&quot;Do You Use Paperless Billing?&quot;)<br>            PaymentMethod = gr.Dropdown([&quot;Electronic check&quot;, &quot;Mailed check&quot;, &quot;Bank transfer (automatic)&quot;, &quot;Credit card (automatic)&quot;], label=&quot;What Payment Method Do You Use?&quot;)<br>            MonthlyCharges = gr.Number(label=&quot;What is your Monthly Charge?&quot;,minimum=0)<br>            TotalCharges = gr.Number(label=&quot;What are your Total Charges?&quot;,minimum=0)</pre><p><strong>Note</strong>:The number of arguments used in your function should be equal to the number of inputs</p><ul><li>I implemented a clear button to allow users to clear all entered inputs. To achieve this, I created a variable named input_components to store the inputs I intended to use with my gr.ClearButton()</li></ul><pre> #create a variable that clear button will clear<br>            input_components = [SeniorCitizen, Partner, Dependents, tenure,<br>                                InternetService, OnlineSecurity, OnlineBackup, DeviceProtection,<br>                                TechSupport, StreamingTV, StreamingMovies, Contract, PaperlessBilling,<br>                                PaymentMethod, MonthlyCharges, TotalCharges]<br>            <br>             #Create a button user will click to clear inputs selected<br>            gr.ClearButton(input_components) </pre><ul><li>Next, I defined my output section. I utilized a markdown component to create a heading for the output. To display the churn prediction clearly, I used gr.HTML() since i used html for for the prediction.</li></ul><pre>#create markdown for ouput<br>    text = gr.Markdown(&quot;## Churn Status&quot;)<br>    <br>    # Define Gradio outputs<br>    output = gr.HTML(&quot;Awaiting Prediction&quot;)</pre><ul><li>Subsequently, I added a button to enable users to visualize their prediction when clicked. This button, named “Predict,” was configured so that the output would only be displayed upon clicking it.</li></ul><pre># Create a button<br>    button = gr.Button(&quot;Predict&quot;)<br><br>    # Create Gradio interface<br>    button.click(fn=predict_churn,inputs=input_components, outputs=output)</pre><ul><li>We are nearing completion. To enhance user-friendliness, I incorporated an example dataframe to facilitate user input and demonstrate how the app functions. I utilized gr.Examples() for this purpose.Each value in the example dataframe corresponds to a value in the user input.</li></ul><pre> #create an example dataframe<br>    gr.Markdown(&quot;## Input Examples&quot;)<br><br>    gr.Examples([[&#39;No&#39;, &#39;No&#39;, &#39;No&#39;, &#39;12&#39;, &#39;Fiber optic&#39;, &#39;No&#39;, &#39;No&#39;, &#39;No&#39;, &#39;No&#39;, &#39;Yes&#39;, &#39;No&#39;, &#39;Month-to-month&#39;, &#39;Yes&#39;, &#39;Electronic check&#39;, &#39;84.45&#39;, &#39;1059.55&#39;],<br>                 <br>                      [&#39;No&#39;, &#39;No&#39;, &#39;No&#39;, &#39;9&#39;, &#39;No&#39;, &#39;No internet service&#39;, &#39;No internet service&#39;, &#39;No internet service&#39;, &#39;No internet service&#39;, &#39;No internet service&#39;, &#39;No internet service&#39;, &#39;Month-to-month&#39;, &#39;No&#39;, &#39;Mailed check&#39;, &#39;20.40&#39;, &#39;181.80&#39;],<br>                      <br>                      [&#39;No&#39;, &#39;No&#39;, &#39;No&#39;, &#39;27&#39;, &#39;DSL&#39;, &#39;Yes&#39;, &#39;No&#39;, &#39;Yes&#39;, &#39;Yes&#39;, &#39;Yes&#39;, &#39;Yes&#39;, &#39;One year&#39;, &#39;No&#39;, &#39;Electronic check&#39;, &#39;81.70&#39;, &#39;2212.55&#39;]],<br>                      <br>                      inputs=input_components)</pre><ul><li>We have successfully completed the setup. Now, to launch the app, as previously mentioned, I instantiated my gr.blocks() as “block.” Therefore, I will use this “block” to initiate the launch.</li></ul><pre>#start gradio app<br>block.launch()</pre><h3>4.Model Deployment</h3><p>Lastly, I deployed the graphical user interface (GUI) on HuggingFace, and you can access the app by <a href="https://huggingface.co/spaces/Kodwo11/Churn_prediction">clicking on this link.</a></p><p>Check out the <a href="https://github.com/KodwoAmissah/Gradio-App-for-Customer-Churn">GitHub repo</a> for this project as well</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fd3ae3cb2b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building and Deploying a Streamlit App for Time Series Forecasting With a Regression Model]]></title>
            <link>https://medium.com/@kodwoam/building-and-deploying-a-streamlit-app-for-time-series-forecasting-with-a-regression-model-65cd1847e47d?source=rss-7dbd0a8ea794------2</link>
            <guid isPermaLink="false">https://medium.com/p/65cd1847e47d</guid>
            <dc:creator><![CDATA[Kodwo Amissah-Mensah]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 15:05:27 GMT</pubDate>
            <atom:updated>2023-10-10T15:32:02.837Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75UyADmzp3-OEjaX8qyvEg.jpeg" /></figure><p>Hello everyone, and welcome to my fourth article. In my previous articles, I delved into the development of machine learning models, which typically catered to individuals with a background in data science. This time around, I’ve embarked on a new journey to create a user-friendly Streamlit app. This app comes complete with an intuitive interface and a deployable model, making it accessible to a broader audience. Whether you’re an experienced data scientist or someone new to the field, this article will guide you through the process of building and deploying a Streamlit app that’s designed to be user-friendly for all.</p><p>For those with a background in data science, this article will provide you with detailed insights into the process of developing and deploying the app. However, if you’re new to the technical aspects of data science and just want to use the app directly, you can simply click on the provided link to access it.</p><p>Here is the <a href="https://timeseriesprediction.streamlit.app/">link to the app</a>.</p><p>Let us begin with the article shall we?</p><p>The outline for this article is as follows:</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>Streamlit<strong> </strong>is a Python library that simplifies the process of building interactive web applications for data science. It allows developers to create intuitive user interfaces with minimal effort, enabling seamless exploration and presentation of data and models. Streamlit provides a wide range of interactive widgets and visualization tools, allowing users to customize and manipulate data on the fly. With its simplicity and ease of use, Streamlit enhances the iterative and collaborative nature of data science projects, enabling rapid prototyping, sharing, and deployment of data-driven applications.</p><p><strong>Why Streamlit?</strong></p><p>Currently, real-world applications are in high demand and developers are developing new libraries and frameworks to make on-the-go dashboards easier to build and deploy. Streamlit is a library that reduces your dashboard development time from days to hours. Following are some reasons to choose the Streamlit:</p><p>1. It is a free and open-source library.</p><p>2. Installing Streamlit is as simple as installing any other python package</p><p>3. It is easy to learn because you won’t need any web development experience, only a basic understanding of Python is enough to build a data application.</p><p>4. It is compatible with almost all machine learning frameworks, including Tensorflow and Pytorch, Scikit-learn, and visualization libraries such as Seaborn, Altair, Plotly, and many others.</p><p>In summary, Streamlit offers a rapid and efficient approach to constructing and distributing apps. It allows you to encapsulate your model and its components within a range of features, enabling users to engage with it interactively.</p><h3>2.Backend</h3><p>Backend in the context of my article, refers to all the operations that occur behind the scenes to ensure the functionality of my model.</p><p><strong>Important Note</strong>: Before we delve further into this guide, I recommend reading my previous article on <a href="https://medium.com/@kodwoam/using-time-series-forecasting-to-build-models-for-sales-prediction-8e713ab54612">time series</a>. It will provide valuable insights into the steps I followed to develop the model used in this app.</p><p>Now, let’s move forward</p><h4>2.1 Making the Model Work</h4><p>In order to make my model and encoders operational, I utilized the saving and loading mechanism provided by Joblib. You can access the stored model in the “model” folder and the encoders in the “encoders”of my repository.</p><p>The code below will show how i saved the model and encoders</p><pre># Specify the file path where you want to save the model<br>model_file_path = &#39;C:\\Users\\User\\Desktop\\hub\\Streamlit-App-for-Time-Series-Analysis\\Model\\model.pkl&#39;</pre><pre># Save the model to the specified file path<br>joblib.dump(model_lin, model_file_path)</pre><pre># Save the encoders to files<br>joblib.dump(LE, &#39;label_encoder.pkl&#39;)<br>joblib.dump(BE, &#39;binary_encoder.pkl&#39;)<br>joblib.dump(OE, &#39;ordinal_encoder.pkl&#39;)</pre><p>After securing the model and encoders, I implemented the backend code within the “forecast.py” page. If you’re seeking more insights, feel free to explore it. To encapsulate everything, here’s a brief summary of my actions:</p><p><strong>a.Defined my inputs</strong></p><p>In simple terms, I wanted to make sure my model could take in information from users.</p><p>I used Streamlit, to create an expander that will contain all the user inputs.</p><p>To get data from users, I employed a variety of Streamlit widgets:</p><ul><li>“st.number_input” helped gather details on promotions.</li><li>“st.date_input” allowed users to input dates for forecasting.</li><li>“st.radio” let users pick between different options for the locale and transferred.</li><li>“st.selectbox” was useful for handling a large number of holiday choices.</li></ul><p>I added a “Predict” button for users, and when it’s clicked, the output is displayed using st.button.</p><p>The code is below:</p><pre># Set up prediction container<br>with st.expander(&quot;Make a prediction&quot;, expanded=True):<br> <br> # Define Streamlit inputs<br> date = st.date_input(label=&quot;Enter a date&quot;)<br> holiday = st.selectbox(label=&quot;Select a category of holiday&quot;, options=[&#39;Holiday&#39;, &#39;Not Holiday&#39;, &#39;WorkDay&#39;, &#39;Additional&#39;, &#39;Event&#39;, &#39;Transfer&#39;, &#39;Bridge&#39;])<br> locale = st.radio(label=&quot;Select a holiday type&quot;, options=[&#39;National&#39;, &#39;Not Holiday&#39;, &#39;Local&#39;, &#39;Regional&#39;], horizontal=True)<br> transferred = st.radio(label=&quot;Select whether the holiday was transferred or not&quot;, options=[&quot;True&quot;, &quot;False&quot;], horizontal=True)<br> onpromotion = st.number_input(label=&quot;Please enter the total number of expected items to be on promotions&quot;)<br><br># Create a button<br>    predicted = st.button(&quot;Predict&quot;)</pre><p><strong>Note:</strong>The app will only be accepting input for the features I used when training my model.</p><p><strong>b.Converting input to Dataframe</strong></p><p>I initially formed a dictionary to associate the input features, and later, I converted it into a dataframe. This step was necessary because I trained my model using a dataframe. I used the following code to perform this operation.</p><pre># Format for inputs<br>        input_dict = {<br>            &quot;date&quot;: [date],<br>            &quot;holiday&quot;: [holiday],<br>            &quot;locale&quot;: [locale],<br>            &quot;transferred&quot;: [transferred],<br>            &quot;onpromotion&quot;: [onpromotion]<br>        }<br><br>        # Convert inputs into a DataFrame<br>        input_df = pd.DataFrame.from_dict(input_dict)</pre><p><strong>c.Using the encoders and extracting date features</strong></p><p>Now that the data is in a dataframe, we will utilize our encoders, just as we did during training, to encode our variables. If you have read the previous article, you’re aware that our model is a linear regression model. Linear regression can not handle datetime data, therefore you need to extract relevant features from it. In this step, we perform a similar process to what we did during training.</p><p>The code below will show this</p><pre># Encode categorical inputs<br>        input_df[&quot;transferred&quot;] = LE.transform(input_df[&quot;transferred&quot;])<br>        input_df = BE.transform(input_df)<br>        input_df[&quot;locale&quot;] = OE.transform(input_df[[&quot;locale&quot;]])<br><br>        # Convert date to datetime<br>        input_df[&quot;date&quot;] = pd.to_datetime(input_df[&quot;date&quot;])<br><br>        # Extract date features and add to input_df<br>        input_df[&#39;year&#39;] = input_df[&#39;date&#39;].dt.year<br>        input_df[&#39;month&#39;] = input_df[&#39;date&#39;].dt.month<br>        input_df[&#39;day&#39;] = input_df[&#39;date&#39;].dt.day<br>        input_df[&#39;day_of_week&#39;] = input_df[&#39;date&#39;].dt.dayofweek<br>        input_df[&#39;day_of_year&#39;] = input_df[&#39;date&#39;].dt.dayofyear<br>        input_df[&#39;week_of_year&#39;] = input_df[&#39;date&#39;].dt.isocalendar().week<br>        input_df[&#39;quarter&#39;] = input_df[&#39;date&#39;].dt.quarter<br>        input_df[&#39;is_weekend&#39;] = (input_df[&#39;date&#39;].dt.dayofweek // 5 == 1).astype(int)<br>        input_df[&#39;day_of_month&#39;] = input_df[&#39;date&#39;].dt.day<br><br>        # Drop date after extracting<br>        input_df.drop(columns=[&#39;date&#39;], inplace=True)</pre><p><strong>d. Making the Prediction</strong></p><p>With the data prepared, our model is ready to make predictions. To achieve this, I passed the “inputs” variable through my model. Here’s the code for this step:</p><pre>     # Make predictions<br>        model_output = model.predict(input_df)<br><br>        # Round the model output to 2 significant figures<br>        rounded_output = np.round(model_output, 2)<br><br>        # Add rounded predictions to the input_dict<br>        input_dict[&quot;Total Sales($)&quot;] = rounded_output<br><br>        # Format the rounded output with bold and a dollar sign<br>        formatted_output = f&quot;&lt;b&gt;${rounded_output[0]}&lt;/b&gt;&quot;<br><br># Display prediction message inside the expander with HTML formatting<br>        st.write(f&quot;Your total predicted sales will be {formatted_output}&quot;, unsafe_allow_html=True)<br></pre><p>I used the “input_dict” to ensure that the output for the date would match the format in the dictionary, even though we had dropped the date column from the “input_df.” This way, the final prediction would maintain the original date format.</p><p>Below is a picture of my forecast page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_zgzbXfyS9VP2z7Mamdww.png" /></figure><h3>3.Front-End</h3><p><strong>3.1 Streamlit Features</strong></p><p>In the front end of my app, I utilized several Streamlit attributes to enhance the user interface, including:</p><ul><li>st.title(): Used for creating titles.</li><li>st.write(): Employed for displaying various types of outputs, such as images and text.</li><li>st.plotly_chart(): Utilized to showcase interactive plotly charts.</li><li>st.subheader(): Implemented to create subheaders.</li><li>st.button(): Employed to generate clickable buttons.</li><li>st.expander(): Utilized to create expandable sections.</li></ul><p>You can use the <a href="https://streamlit.io/">streamlit documentations</a> to more detailed information.</p><p><strong>3.2 Using Multiple pages</strong></p><p>First, let me demonstrate how my multi-page app appears, and then I’ll guide you through the steps to achieve the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G191W5RIion6BbE8YS67VQ.jpeg" /><figcaption>Multi-page</figcaption></figure><p>To achieve this multipage as shown above,you can follow the steps below:</p><ul><li>To start, create a file named “home.py.” This file will serve as your welcome page for the multipage app. You have the flexibility to name this file as you prefer. In “home.py,” it’s crucial to define your sidebar.I also added some css styles.You can achieve this by using the following code:</li></ul><pre>st.set_page_config(<br>    page_title=&quot;Welcome To Amissah&#39;s Time Series App&quot;,<br>    page_icon=&quot;😃&quot;,<br>    layout=&quot;wide&quot;<br>)<br><br># Add content to your Streamlit app<br>st.markdown(&quot;# 👋 Welcome To Team Cape Cod&#39;s Sales Forecasting App Of Products Across Favorita stores&quot;)<br><br># Display the waving GIF<br>st.image(&quot;https://www.animatedimages.org/data/media/1645/animated-waving-image-0090.gif&quot;)<br><br># Add CSS for animation<br>st.write(&quot;&quot;&quot;<br>    &lt;style&gt;<br>        @keyframes slide-in {<br>            0% {<br>                transform: translateX(-100%);<br>            }<br>            100% {<br>                transform: translateX(0);<br>            }<br>        }<br>        .slide-in-animation {<br>            animation: slide-in 1.5s ease-in-out;<br>        }<br>    &lt;/style&gt;<br>&quot;&quot;&quot;, unsafe_allow_html=True)<br><br><br># Text with animation<br>st.write(&#39;&lt;div class=&quot;slide-in-animation&quot;&gt;Favorita Corporation is an Ecuador based company engaged in the organization, installation and administration of stores, markets and supermarkets. The company has a business presence in many international countries also. This app with the help of a linear regression model will enable you to predict sales across Favorita Stores.&lt;/div&gt;&#39;, unsafe_allow_html=True)<br><br>#add a sidebar to select pages<br>st.sidebar.success(&quot;Select a page above.&quot;)</pre><ul><li>After you’ve finished the initial setup, make sure to create a folder named “pages.” This folder will serve as a container for all your additional web pages. To add an auxiliary web page to your app, simply move it into this “pages” directory. Here’s a visual representation of how I structured my project:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*E2EfLl-ul1s6tIPabHfVpg.png" /></figure><p>As you can see in the image, the “Home.py” file serves as the main page of my app, while the “Forecast Page,” “Explore,” and “About” are auxiliary pages that I’ve included in my app.</p><p>To run this app, you’ll need to start with the main page, which is “home.py.” This main page acts as the entry point for the app and provides access to all the other pages within the application.</p><p>Now, I’ll proceed to show you images of the Explore and About auxiliary pages since I’ve already displayed the Forecast page earlier.</p><p>Below is the explore page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWox9DIrupREgI_k6LeH_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fFUu5Tr_2ZD3ddOBKiwaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2c37xMef73v_zEp7ZjyfJA.png" /></figure><p>Let’s view the About page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DDoO9ihSdR-yq2cPkJmGeQ.png" /></figure><p>For further design and better understanding of the app, please consult my <a href="https://github.com/KodwoAmissah/Streamlit-App-for-Time-Series-Analysis">GitHub repository </a>for this project.</p><h3>4.Deployment</h3><p>I’ve deployed my app on <a href="https://streamlit.io/">Streamlit Cloud</a>, and you can access it by clicking <a href="https://timeseriesprediction.streamlit.app/">here</a> to view it on the Streamlit Cloud-hosted website.</p><p>The deployment process is straightforward and involves these steps:</p><p><strong>1. Register for a Streamlit Cloud Account</strong></p><p>You can sign up for a Streamlit Cloud account using either your GitHub credentials or your email. I strongly recommend using your GitHub account as it simplifies repository access and deployment.</p><p><strong>2. Navigate to the “New App” Feature</strong></p><p>After creating your account, it’s time to deploy your app. To get started, click on the “New App” feature as indicated in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NeqFBaD3Ag-Lby8rn50uGw.jpeg" /></figure><p><strong>3.Enter the necessary information</strong></p><p>After clicking the “New App” button, you will be directed to a page that resembles the one shown below. Please provide the required information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9f1ug1XIP9DG3ZUKLlq4vQ.png" /></figure><p>To fill the information above you have do the following:</p><ul><li>To get started, you’ll need to insert the link to the repository for which you want to create an app. Make sure you have your requirements.txt file ready.</li><li>Next, choose the branch. It should automatically switch from “master” to “main,” but you can manually change it if needed.</li><li>Now, specify the path for your app. Enter the name of the Python file where your interface is built. If you’re working on a multi-page app, make sure to use your main Python file.</li><li>Finally, provide the URL you’d like for your site. The URL should be between 6 to 67 characters in length. Once you see the message “URL available,” you’re all set to proceed.</li><li>Then you click on create app</li></ul><h3>5.Conclusion:</h3><p>Streamlit simplifies the process of building websites, making it an excellent choice for data scientists interested in creating a minimum viable product (MVP) or a straightforward graphical user interface (GUI) for their models. It’s a powerful tool that can streamline web development tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65cd1847e47d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Time Series Forecasting To Build Models For Sales Prediction]]></title>
            <link>https://medium.com/@kodwoam/using-time-series-forecasting-to-build-models-for-sales-prediction-8e713ab54612?source=rss-7dbd0a8ea794------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e713ab54612</guid>
            <dc:creator><![CDATA[Kodwo Amissah-Mensah]]></dc:creator>
            <pubDate>Fri, 15 Sep 2023 21:57:25 GMT</pubDate>
            <atom:updated>2023-09-15T21:57:25.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*EZ91dCZYDOevG9DYTvqKfg.jpeg" /></figure><p>Hello everyone and welcome to my third project.In this project, our primary focus revolves around time series analysis. You might be curious about what exactly a time series is.A time series is a sequence of data points collected or recorded at successive, equally spaced intervals over time. Each data point in a time series corresponds to a specific moment in time, making it a valuable tool for analyzing and forecasting trends, patterns, and variations that may occur over time.</p><p>The objective of this project is to create accurate sales prediction models, and this article aims to provide insights into the utilization of these models for sales forecasting.</p><p>Here is the structure for this article:</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>Upon completing this article, you will have gained the following insights:</p><ul><li>How to use statistical models such as ARIMA and SARIMA for univariate modelling and SARIMAX for multivariate modelling using endogenous and exogenous variables</li><li>How to use traditional Machine learning Models such as Linear Regression,Decision Tree and Random Forest Regressor for predictions.</li></ul><p>Now let’s begin this article.</p><h3>1. Business Understanding</h3><p>As stated earlier,Time series data is a sequence of observations recorded at regular intervals over time. These observations are typically ordered chronologically and can be collected hourly, daily, monthly, or at other fixed time intervals.So then why time series ?Time series analysis is crucial for various applications, as it allows us to uncover patterns, trends, and dependencies within temporal data. This knowledge is invaluable for making informed decisions, especially in forecasting future events or trends.</p><p>Our primary goal in this project is to construct highly accurate sales prediction models that predicts store sales for a wide range of products across Favorita stores by leveraging historical sales data and relevant supplementary information. The model will aim to provide reliable forecasts that enable Favorita to optimize its inventory management, resource allocation, and marketing strategies. The successful implementation of this model will contribute to improved operational efficiency, enhanced decision-making, and increased profitability for the retailer.</p><p>To attain these outcomes, we applied time series analysis in conjunction with various machine learning algorithms following the CRISP-DM framework.</p><h3>2. Data Understanding</h3><p>We were provided with 5 datasets namely:</p><ul><li>A dataset containing information about the stores and their respective cities.</li><li>A dataset pertaining to holidays.</li><li>A training dataset.</li><li>A test dataset lacking a target variable.</li><li>An oil dataset</li></ul><p>These datasets resided in 3 places namely:</p><ul><li>A database</li><li>Onedrive</li><li>Github</li></ul><p>An overwiew was done on each of the datasets to see what each contain.This is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*_XhnDu2wmBfa3SjM_zLa9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*yNztK2A-sRM4cjYJnzNJ4A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*AGedP4tQgAQYRZCH1pOjeQ.png" /></figure><p>Upon reviewing our data, we observed that all our datasets were complete, except for the oil dataset, which contained some missing values.</p><p>The missing values contained a certain pattern and consistency.Therefore the backfill (“bfill”) method was used to fill the missing row with the subsequent row value.</p><p>As shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*LO-Ti5XYOAaQzNm-8AXvNg.png" /><figcaption>oil data with missing values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*lJMBGrcEmKq1HAhzmSthWw.png" /><figcaption>After using back fill to fill the missing value</figcaption></figure><h3>3.Hypothesis</h3><p>Null Hypothesis (H0): The intensity of promotion (onpromotion) does not have a significant impact on the average sales of products.</p><p>- Alternative Hypothesis (H1): The intensity of promotion (onpromotion) has a significant impact on the average sales of products.</p><p>For the hypothesis,a t-test was used.This is shown in the code below</p><pre>Split onpromotion variable into promoted products and non-promoted products<br>promoted_data = merged_data_copy[merged_data_copy[&#39;onpromotion&#39;] &gt;= 1]<br>non_promoted_data = merged_data_copy[merged_data_copy[&#39;onpromotion&#39;] &lt; 1]</pre><pre># Calculate average sales for promoted and non-promoted products<br>average_sales_promoted = promoted_data[&#39;sales&#39;].mean()<br>average_sales_non_promoted = non_promoted_data[&#39;sales&#39;].mean(</pre><pre># Perform a t-test<br>t_statistic, p_value = stats.ttest_ind(promoted_data[&#39;sales&#39;], non_promoted_data[&#39;sales&#39;], equal_var=False)<br><br># Determine the significance level (alpha)<br>alpha = 0.05<br><br># Check if the p-value is less than the significance level<br>if p_value &lt; alpha:<br>    result = &quot;Reject the null hypothesis&quot;<br>else:<br>    result = &quot;Fail to reject the null hypothesis&quot;<br><br># Print the results with p-value formatted to three decimal places<br>print(&quot;Average sales for promoted products:&quot;, average_sales_promoted)<br>print(&quot;Average sales for non-promoted products:&quot;, average_sales_non_promoted)<br>print(&quot;T-statistic:&quot;, t_statistic)<br>print(f&quot;P-value: {p_value:.3f}&quot;)  # Format p-value to three decimal places<br>print(&quot;Conclusion:&quot;, result)</pre><p>Upon executing the provided code, we rejected our null hypothesis due to the significantly low p-value, which was well below the threshold of 0.05.</p><h3>4.Libraries Importation</h3><pre>### Install required packages<br><br>#Libraries for sql<br>import pyodbc <br>from dotenv import dotenv_values #import the dotenv_values function from the dotenv package<br>import warnings <br>warnings.filterwarnings(&#39;ignore&#39;)<br><br>#libraries for handling data<br>import pandas as pd<br>import numpy as np<br>pd.set_option(&#39;display.max_rows&#39;, None)<br><br>##data visualizations<br>from scipy import stats<br>import matplotlib.pyplot as plt <br>import seaborn as sns <br>import plotly.express as px<br><br>##stat models <br>from statsmodels.tsa.stattools import adfuller  ##for adf test<br>from statsmodels.graphics.tsaplots import plot_acf <br>from statsmodels.graphics.tsaplots import plot_pacf <br>from statsmodels.tsa.ar_model import AutoReg<br>from statsmodels.tsa.arima.model import ARIMA<br>from statsmodels.tsa.statespace.sarimax import SARIMAX<br>from statsmodels.tsa.stattools import kpss<br>from statsmodels.tsa.seasonal import seasonal_decompose<br>import statsmodels.api as sm<br>from statsmodels.tsa.stattools import grangercausalitytests##grenger causality test<br><br><br>##Error evaluations<br>from sklearn.metrics import mean_squared_error, mean_squared_log_error,mean_squared_log_error<br>from scipy.stats import boxcox<br><br>## Algorithms<br>from pmdarima import auto_arima<br>from sklearn.tree import DecisionTreeRegressor<br>from sklearn.ensemble import RandomForestRegressor<br>from sklearn.linear_model import LinearRegression<br><br>#Feature processing libraries<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import LabelEncoder<br>from category_encoders.binary import BinaryEncoder<br>from sklearn.preprocessing import OrdinalEncoder</pre><h3>5. EDA and Questions</h3><p>The primary goal of this article is to construct a sales prediction model. Consequently, while this exploratory data analysis (EDA) will feature graphical representations addressing key questions, the actual code can be found in my GitHub repository. A link to the repository will be furnished at the conclusion of this article.</p><p>In our EDA process, we conducted a thorough examination of each of the provided datasets to extract valuable insights.We chose to delve into each dataset to address the questions we had posed.</p><p>These questions include:</p><p>1. Which dates have the lowest and highest sales for each year?</p><p>2. Which stores are among the top 10 in terms of total sales?</p><p>3. Did the sales data show any noticeable changes in sales patterns around the time of the 2016 earthquake?</p><p>4. Which product families were the most frequently purchased (Top 5)?</p><p>5. Is there a relationship between transactions and sales?</p><p>6. Is there any association between oil prices and sales?</p><p>Let us begin with the answering of these questions</p><ol><li>Which dates have the lowest and highest sales for each year?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*aWk0kuVS3iKX2wCMdx85jw.png" /></figure><p>The depicted graph illustrates the highest sales values for each corresponding year. This data holds significance in comprehending sales trends and pinpointing significant events or promotions that contributed to these remarkable sales figures.</p><p>2. Which stores are among the top 10 in terms of total sales?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*yXSOlVs-0OHCpgxB4KVuKA.png" /></figure><p>his information gives us insight into the stores that have generated the highest total sales, helping us understand the distribution of sales among the top-performing stores.</p><p>3. Did the sales data show any noticeable changes in sales patterns around the time of the 2016 earthquake?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*MXzPJpHhPb1HHgOm7CtZeA.png" /></figure><p>The sales data showed some noticeable changes in sales patterns after the 2016 earthquake. Sales patterns changed significantly after the 2016 earthquake, with a noticeable spike in sales immediately following the event. This observation indicates that the earthquake might have had a significant impact on consumer behavior and purchasing patterns.</p><p>4. Which product families were the most frequently purchased (Top 5)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*D262fu64zjPsQdAnnwxnBg.png" /></figure><p>The “GROCERY I” family has the highest total sales, followed by “BEVERAGES,” “PRODUCE,” “CLEANING,” and “DAIRY.” These product families have significantly higher total sales compared to other families in the dataset. This information can be valuable for understanding customer preferences and optimizing product offerings in these top-performing categories.</p><p>5. Is there a relationship between transactions and sales?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*wekpNt4aWKqaEXDK8IZcbA.png" /></figure><p>The points on the scatter plot show a general trend of increasing sales with increasing transactions, but there is also a significant amount of variability in the data points, indicating that other factors may be influencing sales as well.</p><p>6. Is there any association between oil prices and sales?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*DJ1dptoruzum5bTzJaFLdA.png" /></figure><p>The points on the plot are scattered without a clear linear trend, indicating a weak relationship between these two variables.</p><h3>6. Modeling</h3><p>During this phase, our primary focus was on modeling the dataset. We approached the dataset modeling process from two distinct angles:</p><ul><li>For certain statistical models such as Auto regressive (AR), SARIMA, and ARIMA, they lack the capability to accommodate multiple features. In such cases, I approached the problem as univariate forecasting, where I aimed to construct a model solely based on the current and lagged values of the target variable, which is sales.</li><li>I performed multivariate forecasting where i used a statistical model(SARIMAX) capable of handling exogenous variables which are variables apart from the target that add additional meaning and information to the dataset and traditional machine learning models such as Random Forest,Decision Tree and Linear Regression.</li></ul><p>Let’s proceed to see how each modeling approach was handled</p><h4>6.1.Univariate Modelling</h4><p>Here we will develop a model where the only variables we will consider are sales and time.Let’s see how our model will perform.To begin i dropped all other variables and kept only the sales and time.This is shown in the code below</p><pre># #create univariate data for modelliing<br>univar_sale= train_c.drop([&quot;id&quot;, &quot;store_nbr&quot;, &quot;family&quot;, &quot;onpromotion&quot;], axis=1)</pre><p>After dropping the other variables this is the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*HHVO9Zc7uy-gp3PIhOfY0g.png" /></figure><p>With only the variables “sales” and “time” at our disposal, we conducted a stationarity test.</p><p>So what then is a staionarity test?<strong>A stationarity test</strong> is a test employed to examine a dataset for the presence of trends and seasonality or a stationarity test is a test where the standard deviation and mean are consatnt or equal to zero. If these patterns are absent, the data is considered stationary; otherwise, it is non-stationary.</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>Before performing the test,since The goal of this project is to forecast the general sales for Favorita, we are interested in aggregating and analyzing the total sales for each day.This is show below</p><pre># Grouping by date and aggregating sales<br>univar_sale= univar_sale.groupby(univar_sale.index).agg({&quot;sales&quot;: sum})</pre><p>The code above gave me the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*XQyY7XB8DxAQ4DUfXRt3Yw.png" /></figure><p>The plot for the above code is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*wiw8d7s-EpbAaKhHWhp-XA.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 this already indicates that our data is not stationary but to further confirm this,I used the <strong>Augmented Dickey-Fuller (ADF) test.</strong></li></ul><p>The code below show how the Augmented Dickey-Fuller (ADF) test was used</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*IGpJkOTzA5cf6fMoXuFYfg.png" /></figure><p>After my test, I got my p-value to be greater than 0.05 (0.08) therefore, the data was non-stationary.</p><h4>6.1.1 Univariate Modeling with AutoRegressive model</h4><p>After performing the stationarity, the idea was to forecast sales using the AutoRegressive algorithm.</p><p>However, before that, I had to use the following methods to help me understand the trends and seasonality</p><ul><li>ACF and a PACF graph</li></ul><p><strong>6.1.1(a) PACF and ACF Chart</strong></p><p>These two charts offer detailed insights into our time series. They depict the AutoRegressive and Moving Average components of our time series data.</p><p>To achieve this I used the code below:</p><pre># Create a figure with two subplots<br>fig, axes = plt.subplots(2, 1, figsize=(10, 8))<br><br># Plot the autocorrelation on the first subplot<br>plot_acf(univar_sale,lags=30, ax=axes[0])<br>axes[0].set_title(&#39;Autocorrelation Plot(ACF)&#39;)<br>axes[0].set_xlabel(&#39;Lag&#39;)<br><br># Plot the partial autocorrelation on the second subplot<br>plot_pacf(univar_sale,lags=30, ax=axes[1])<br>axes[1].set_title(&#39;Partial Autocorrelation Plot(PACF)&#39;)<br>axes[1].set_xlabel(&#39;Lag&#39;)<br><br># Adjust spacing between subplots<br>plt.tight_layout()<br><br># Show the combined plot<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/984/1*o89Po0ax23UD-EtKXLTryA.png" /></figure><ul><li>In our ACF chart (representing Moving Average, denoted as q), we observe that all lags are above our significance level. However, the most prominent lags are at 1, 6, 7, and 8.</li><li>In our PACF chart (representing Autoregressive, denoted as p), we can see that most lags exceed the significance level, with particularly strong lags at 1, 3, 5, 6, and 7.</li></ul><p>Therefore, we can use any combination for our model.</p><p>The next step is to split our data into train and test and fit it on our model,and use it to make predictions.</p><p>This is shown below</p><pre>#we split the data into train and test<br>train_1=univar_sale[0:1347]<br>test_1=univar_sale[1347:]</pre><pre>#fit our AR model<br>model= AutoReg(train_1, lags=10).fit()</pre><pre>## we use our model to predict<br>AR_pred = model.predict(start=len(train_1), end=len(train_1) + len(test_1) - 1, dynamic=False)</pre><p>After predicting we plot our predicted,training and test data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*wuDIWww-q1geRpv_-Uc2eg.png" /></figure><p>The evaluation of the Ar model with it’s metrics will be shown below as compared to the others so please hold on till the end.</p><h4>6.1.2 Univariate Modeling with ARIMA Model</h4><p>Before constructing the ARIMA model, we employ a stepwise approach to identify the optimal values for p, d, and q, aiming to minimize the AIC (Akaike Information Criterion).<strong>The Akaike Information Criterion</strong> (AIC) is a measure used in statistics to evaluate the goodness of fit of a statistical model while penalizing for its complexity. It balances how well a model fits the data with how many parameters it uses.Therefore, Lower AIC values indicate a better balance between model fit and complexity, suggesting a preferable model.</p><p>The code below shows how this was done</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*maddCxwbmwjfP9ayoumd-Q.jpeg" /></figure><p>From the above image you can see the best model with the lowest AIC</p><p>Now we fit our model with the order(5,1,5),predict and plot .This is show with the subsequent codes</p><pre>#fit our model<br>model1=ARIMA(train_1,order=(5,1,5)).fit()<br>model1.summary()</pre><pre>#we use our model to predict<br>ARIMA_pred=model1.predict(start=len(train_1), end=len(train_1) + len(test_1) - 1, typ=&quot;levels&quot;)<br>print(ARIMA_pred)</pre><pre># Plot the actual values (training and testing data)<br>plt.figure(figsize=(12, 6))<br>plt.plot(train_1.index, train_1, label=&#39;Training Data&#39;)<br>plt.plot(test_1.index, test_1, label=&#39;Testing Data&#39;)<br><br># Plot the predictions<br>plt.plot(test_1.index, ARIMA_pred, label=&#39;Predictions&#39;)<br><br># Add labels and legend<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend(loc=&#39;best&#39;)<br>plt.title(&#39;ARIMA Model Forecast&#39;)<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*dPqwiFjeqWLkh8fiz2J5cw.png" /></figure><p>We can see a better prediction in our graph as compared to our AR model</p><h4>6.1.3 Univariate Modeling with SARIMA Model</h4><p>This is the just an extension of the ARIMA model but incorporates seasonality into the forecasting o time series data.</p><p>With this model, I employed an order selection process similar to ARIMA. However, instead of relying on an automated method, I manually selected an order. If we recall, the Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF) plots provided me with some candidate values for p and q. These values could be used in various combinations to specify the order of the model.So i used the order (6,1,7) and a seasonal order of (0,0,0,12). The seasonal order (0, 0, 0, 12) means:</p><ul><li>P = 0: There are no seasonal autoregressive terms in the model.</li><li>D = 0: There is no seasonal differencing applied to the data.</li><li>Q = 0: There are no seasonal moving average terms in the model.</li><li>s = 12: The seasonal period is 12, which indicates that there is a yearly seasonality in the data.</li></ul><p>So, in summary, the SARIMA model is not including any seasonal autoregressive, differencing, or moving average terms but is taking into account the yearly seasonality with a seasonal period of 12 months. This means the model will capture patterns that repeat annually in the time series data.</p><p>Let’s continue with our model</p><p>We will fit with our order and seasonal order,predict and plot to see the model’s predictive performance.This is shown below</p><pre>#fit our model<br>model2=SARIMAX(train_1,order=(6,1,7),seasonal_order=(0,0,0,12)).fit()<br>model2.summary()</pre><pre>##we predict with our model<br>SARIMA_pred=model2.predict(start=len(train_1), end=len(train_1) + len(test_1) - 1, typ=&quot;levels&quot;)<br>print(SARIMA_pred)</pre><pre># Plot the actual values (training and testing data)<br>plt.figure(figsize=(12, 6))<br>plt.plot(train_1.index, train_1, label=&#39;Training Data&#39;)<br>plt.plot(test_1.index, test_1, label=&#39;Testing Data&#39;)<br><br># Plot the predictions<br>plt.plot(test_1.index, SARIMA_pred, label=&#39;Predictions&#39;)<br><br># Add labels and legend<br>plt.xlabel(&#39;Date&#39;)<br>plt.ylabel(&#39;Sales&#39;)<br>plt.legend(loc=&#39;best&#39;)<br>plt.title(&#39;SARIMA Model Forecast&#39;)<br><br># Show the plot<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*VsJIyugBSABt3Lj5nGH7DA.png" /></figure><p>Let’s compare the performance of all our univariate statistical models.The metrics used are Mean square error(MSE),Mean square log error(MSLE),Root mean square error(RMSE) and Root mean log square error(RMSLE).Our focus is on our RMSLE because based on the rubric for this project an excellent model is a model with an RMSLE value of 0.2 and a good model is a model with and RMSLE of 0.3.</p><p>Let’s view the metrics below to see how our model performed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*FGtxoemHFOzOdrm91o9eYw.png" /></figure><p>From our metrics our SARIMA model was able to produce the lowest RMSLE of 0.29</p><p>Before we move on to the next step in this article, which involves multivariate forecasting, it’s crucial to address the issue of non-stationarity in our data. As demonstrated earlier in this article, our data exhibits non-stationary behavior. Therefore, it’s imperative that we take steps to transform it into a stationary form.</p><h4>6.1.4 Making our data stationary</h4><p>To make the series stationary we will perform box cox trasformation to make variance constant there are other approaches like differencing but the box cox was suitable for me.</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.</p><p>I used the code below to before decomposition</p><pre># Decompose the time series<br>decomposed_data = sm.tsa.seasonal_decompose(univar_sale, model=&#39;multiplicative&#39;, period=365)<br><br># Plot the decomposed components<br>plt.figure(figsize=(12, 8))<br>plt.subplot(411)  # 4 rows, 1 column, subplot 1 (original data)<br>plt.plot(univar_sale, label=&#39;Original Data&#39;)<br>plt.legend()<br><br>plt.subplot(412)  # subplot 2 (trend component)<br>plt.plot(decomposed_data.trend, label=&#39;Trend Component&#39;)<br>plt.legend()<br><br>plt.subplot(413)  # subplot 3 (seasonal component)<br>plt.plot(decomposed_data.seasonal, label=&#39;Seasonal Component&#39;)<br>plt.legend()<br><br>plt.subplot(414)  # subplot 4 (residuals)<br>plt.plot(decomposed_data.resid, label=&#39;Residuals&#39;)<br>plt.legend()<br><br>plt.tight_layout()<br>plt.show()</pre><p>I got the graph below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hEoe_oGj0Wc5HGLg35aDog.png" /></figure><p>As depicted in the chart, clear trends and seasonality patterns are evident, confirming the non-stationarity of the data.</p><p>Next, we will employ the <strong>Box-Cox transformation</strong> to induce stationarity in our data. To illustrate the impact of this transformation, we will provide visualizations comparing the data before and after applying Box-Cox.</p><p>Below is the code to show visual before the box cox transformation</p><pre>#performing box cox<br>data_boxcox=pd.Series(boxcox(univar_sale[&quot;sales&quot;],lmbda=0),index=univar_sale.index)<br>plt.figure(figsize=(12,4))<br>plt.plot(data_boxcox,label=&#39;Before Box Cox Transformation&#39;)<br>plt.legend(loc=&#39;best&#39;)<br>plt.title(&#39;Before Box Cox Transformation&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*KG8nu_TzZY6gYk-lPh_RoA.png" /><figcaption>Before box cox</figcaption></figure><p>The graph above still depicts a trend</p><p>The code below shows after box cox was applied</p><pre># we difference to remove trend<br>data_boxcox_diff=pd.Series(data_boxcox-data_boxcox.shift(),univar_sale.index)<br>plt.figure(figsize=(12,4))<br>plt.plot(data_boxcox_diff,label=&#39;After Box Cox Transformation And Differencing&#39;)<br>plt.legend(loc=&#39;best&#39;)<br>plt.title(&#39;After Box Cox Transformation And Differencing&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*1hx-yRGCwFRdcWBC_RkMfQ.png" /><figcaption>after Box cox</figcaption></figure><p>We can clearly see with box cox applied,the data show no presence of trend but to further confirm the stationarity status of the data,we will perform another stationarity test this is shown in the code below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*evQ_7quOpc99nx36DuwSPg.png" /></figure><p>Since our p-value is below our significance value of 0.05 as shown above,stationarity has been achieved.</p><h3>6.2 Multivariate Modelling</h3><p>The goal is to analyze how the remaining columns(exogenous variables) influence or impact sales. This approach is expected to enhance the precision of our forecasting models.</p><h4>6.2.1 Merging Datasets</h4><p>The initial step involved merging the provided datasets. To ensure consistency in the time frame, we filtered all other datasets to match the date range of our train dataset, spanning from January 1, 2013, to August 15, 2017. Notably, we excluded the store dataset from this process, as it didn’t contain time series data. Moreover, since our objective is to develop a model for predicting total sales, the store-specific information was not deemed unnecessary.</p><p>For data integration, I employed the outer join method. This method combines two data frames in a way that preserves all rows, preventing any loss of data. In cases where a row is absent in one data frame but present in the other, it is represented as NaN rather than being discarded, ensuring comprehensive data inclusion.</p><p>I achieved this with the code below:</p><pre># Merge the dataframes<br>merge_data = pd.merge(train, trans, how=&#39;outer&#39;, on=[&#39;date&#39;, &#39;store_nbr&#39;])<br>merge_data1 = pd.merge(merge_data, oil, how=&#39;outer&#39;, on=&#39;date&#39;)<br>merge_data2= pd.merge(merge_data1, holidays_events, how=&#39;outer&#39;, on=&#39;date&#39;)</pre><pre># Filter the merged dataframe to the desired date range<br>start_date = &#39;2013-01-01&#39;<br>end_date = &#39;2017-08-15&#39;<br>merge_data3 = merge_data2[merge_data2[&#39;date&#39;].between(start_date, end_date)]</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>The rationale behind excluding these columns is elaborated in my notebook, which can be accessed via the GitHub repository provided at the conclusion of this article.</p><p>After these columns were dropped,the next step was to check for missing values.This is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*eSzuwPk7jX-4WlVJy6rMeQ.png" /></figure><p>The following are the procedures used in handling the missing values</p><ul><li>Initially, I removed all rows containing missing values in the ‘sales’ and ‘promotion’ attributes. This was accomplished through the following code:</li></ul><pre>#for sales and onpromotion we will drop the missing values<br>final_merge= final_merge.dropna(subset=[&quot;sales&quot;, &quot;onpromotion&quot;])</pre><ul><li>Regarding the ‘transaction’ columns, the missing values were primarily a result of zero recorded transactions. To address this, I employed a straightforward imputation approach, replacing the missing values with zeros. This operation is demonstrated in the following code snippet:</li></ul><pre>#For transactions, we will replace the na values with 0 since it means no transaction was recorded on the said date<br><br># Create a SimpleImputer instance with the strategy set to &#39;constant&#39; and fill_value set to 0<br>imputer = SimpleImputer(strategy=&#39;constant&#39;, fill_value=0)<br><br># Fit the imputer on your data and transform the column<br>final_merge[&quot;transactions&quot;] = imputer.fit_transform(final_merge[[&quot;transactions&quot;]])</pre><ul><li>Concerning the holiday-related attributes (type, locale, and transferred), there were days that did not qualify as holidays. To handle this, I assigned the values “Not Holiday” for the ‘type’ and ‘locale’ attributes, and ‘False’ for the ‘transferred’ attribute to indicate non-holiday status. This transformation was implemented using the following code:</li></ul><pre>final_merge[&quot;type&quot;]=final_merge[&quot;type&quot;].replace(np.nan, &quot;Not Holiday&quot;)<br><br>final_merge[&quot;locale&quot;]=final_merge[&quot;locale&quot;].replace(np.nan, &quot;Not Holiday&quot;)<br><br>final_merge[&quot;transferred&quot;]=final_merge[&quot;transferred&quot;].replace(np.nan, &quot;False&quot;)<br></pre><ul><li>For the oil dataset (dcoilwtico), I used a backfill method to replace the missing values.</li></ul><pre>final_merge[&quot;dcoilwtico&quot;]= final_merge[&quot;dcoilwtico&quot;].fillna(method= &quot;bfill&quot;)</pre><p>After applying the aforementioned data cleaning and preprocessing steps, the resulting data frame took on the following structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*O1cssmPMJJThl58kw4Ffdg.png" /></figure><p>Also, there were no missing values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*GZFhblRxBmVEf4wfdqZQ9A.png" /></figure><h4>6.2.2 Feature Processing</h4><p>This is the stage where I enhance my features by…</p><ul><li>Choosing the most suitable features (Feature selection)</li><li>Generating new features (Feature Engineering)</li><li>Transforming categorical features into numerical ones (Feature Encoding)</li></ul><p>All three methods mentioned above were utilized in this section. —</p><p><strong>a.Feature Selection Using Granger Causality Test</strong></p><p>The datasets I merged together were time series datasets,and from research i discovered that one test used to determine whether one time series variables has an effect on the other is the granger causality test.It also helps to find out the causal relationship between the various time series.Granger causality test is done for numerical variables so we will perform this test on our numeric columns.</p><p>In this context, our numeric columns include ‘dcoilwtico’ and ‘onpromotion’. We excluded the ‘transactions’ column because our ultimate goal is to use our best model to predict on our test dataset. The test dataset does not contain the ‘transactions’ column, so it wouldn’t be prudent to train our model on this feature.</p><p>Below is the null and alternative hypothesis of the Granger causality test:</p><ul><li>Null Hypothesis: The historical data of time series X does not offer any substantial information to forecast time series Y. In simpler terms, there is no cause-and-effect relationship between X and Y.</li><li>Alternative Hypothesis: The historical data of time series X does provide meaningful information to forecast time series Y. In simpler terms, there is a causal link between X and Y.</li></ul><p><strong>In essence, if the p-value of the test for any lag exceeds 0.05, we conclude that the null hypothesis is valid.</strong></p><p>The test was performed over 30 lags.</p><ul><li>After performing the granger causality test on the <strong>onpromtion column</strong> over the span of 30 lags, our p-values consistently remain below the 0.05 threshold. This consistent result leads us to reject the null hypothesis in favor of Granger causality.</li><li>Moreover, since our p-value is below the 0.05 threshold, we confirm the central hypothesis of our study: the presence of promotions significantly influences sales.</li></ul><p>as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*qCsUzNlhQqBW0MUr0ldwrA.png" /></figure><ul><li>After the causality test, I realized that after the 20th lag, the dcoilwtico had a p-value greater than 0.05; therefore, I had to drop it.</li></ul><p>This is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*WxnCIkKp0SHcPUQzbd1J4g.png" /></figure><h4>b.Feature encoding</h4><p>Feature encoding is the process of transforming categorical features, which are non-numeric in nature, into numerical representations.</p><ul><li><strong>Holiday (Type Feature)</strong>: This feature had numerous unique values. To handle it, I applied binary encoding.</li><li><strong>Locale Feature</strong>: The locale feature exhibited a hierarchical structure with categories like National, Regional, Local, and Not Holiday. To encode it appropriately, I utilized an Ordinal encoder.</li><li><strong>Transferred Feature</strong>: With only two values, True and False, I used a Label encoder for this feature. True was replaced with 1, and False with 0. It’s important to note that some “False” values were in string format rather than booleans, so I converted them to booleans before encoding.</li></ul><h4>c.Feature Engineering</h4><p>In order to improve the predictive capabilities of my machine learning models, I embarked on feature engineering. It’s important to highlight that feature engineering was exclusively applied to my machine learning models and not the statistical ones.</p><p>I used the code below to create my features:</p><pre>m_train[&#39;year&#39;] = m_train[&#39;date&#39;].dt.year<br>m_train[&#39;month&#39;] = m_train[&#39;date&#39;].dt.month<br>m_train[&#39;day&#39;] = m_train[&#39;date&#39;].dt.day<br>m_train[&#39;day_of_week&#39;] = m_train[&#39;date&#39;].dt.dayofweek<br>m_train[&#39;day_of_year&#39;] = m_train[&#39;date&#39;].dt.dayofyear<br>m_train[&#39;week_of_year&#39;] = m_train[&#39;date&#39;].dt.isocalendar().week<br>m_train[&#39;quarter&#39;] = m_train[&#39;date&#39;].dt.quarter<br>m_train[&#39;is_weekend&#39;] = (m_train[&#39;date&#39;].dt.dayofweek // 5 == 1).astype(int)<br>m_train[&#39;day_of_month&#39;] = m_train[&#39;date&#39;].dt.day</pre><h4>6.2.3 Multivariate Modelling with SARIMAX</h4><p>SARIMAX, an extension of SARIMA, is utilized for multivariate forecasting. It specifically addresses the incorporation of exogenous variables denoted by ‘X’ in SARIMAX.Exogenous variables are get any other variables apart from the target that add additional information to the model.</p><p>I added my exogenous variables using the following process:</p><pre>#### getting my exogenous and endogenous features<br>train_endog=sari_train[[&quot;sales&quot;]]#### endogenous train<br>test_endog=sari_test[[&quot;sales&quot;]]### endogenous test<br><br>train_exog=sari_train.drop(&quot;sales&quot;, axis= 1)### exogenous train<br>test_exog=sari_test.drop(&quot;sales&quot;, axis= 1)### exogenous test</pre><p>I fitted my model with the train and test of my endogenous and exogenous dataset and predicted on my test</p><pre># Define your SARIMAX model and fit the model<br>model4= sm.tsa.SARIMAX(train_endog, exog=train_exog, order=(6, 1, 7), seasonal_order=(0, 0, 0, 12)).fit()</pre><pre># Make forecasts for the test set<br>SARIMAX_pred= model4.get_forecast(steps=len(test_endog), exog=test_exog)</pre><p>The graph below is a result of the prediction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*YfayKnFUSllGXOVz9F8Jag.png" /></figure><p>We can see it really improved compared to the previous SARIMA model</p><h4>6.2.4 Multivariate Modelling with Traditional Machine learning Models</h4><p>The traditional machine learning models used are:</p><ul><li>Linear Regression</li><li>Decision Tree</li><li>Random Forest</li></ul><p>These models didn’t require the date column, so I had to drop it</p><p>The graphs below the performance of each model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*QfMSJrgGJSbtkqp_ITt-PQ.png" /><figcaption>Linear Regression Performance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*5491wFO9Bodq7xx8zHxjGA.png" /><figcaption>Decision tree performance</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*4oOPYlWNpbhiD6YhryJlwQ.png" /><figcaption>Random Forest Performance</figcaption></figure><p>Following the visualization of each multivariate analysis model, we proceed to compare the performance metrics of all the models.</p><p>This is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*CFIWjaniYFGAoRKd19NCkQ.png" /></figure><p>Our linear regression exhibits the lowest RMSLE making it our best model.As stated earlier an excellent model is a model with an RMSLE value of 0.2 and a good model is a model with and RMSLE of 0.3.</p><p>Following our multivariate modeling approach, we conducted feature importance analysis on our machine learning models. Surprisingly, this analysis didn’t yield any improvement. In fact, in some cases, like with linear regression, we observed a higher Root Mean Squared Log Error (RMSLE) compared to previous models.</p><p>This is because certain variables, when considered individually, may not exhibit significant importance. However, when they are combined with other variables, they contribute to enhancing the model’s performance. Consequently, removing these variables can lead to a reduction in model performance.</p><p>The models labeled with “FS” indicate that feature importance was applied. Please note that feature importance can only be performed on traditional machine learning models.</p><p>The metrics for all our models is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*rYq78sP9gSOIHNZvdsS5HQ.png" /></figure><p>Despite applying feature importance, it’s apparent that our linear regression model continues to outperform the others.</p><h4>7.Model Evaluation</h4><p>Now we have our best model,we proceeded to utilize this model for making predictions on our previously unseen data which is our test dataset.</p><p>We follow the same feature encoding procedure on our test dataset as we did on our training dataset. Then, we utilize our best-performing model to make predictions.</p><p>Once the model is used to make predictions on the test dataset, the resulting predictions are added as a new column named “sales” in the test DataFrame. This data frame will be have some columns removed to resemble our submission file.</p><p>The following code snippet illustrates the process:</p><pre>#use your best model to predict<br>final_pre=model_lin.predict(final_merge_test</pre><pre>#Create a new DataFrame to store the results<br>result_df = pd.DataFrame(final_pre, columns=[&quot;sales&quot;])</pre><pre># Define the columns to drop from the &#39;test&#39; DataFrame<br>columns_to_drop = [&#39;date&#39;, &#39;store_nbr&#39;, &#39;family&#39;, &#39;onpromotion&#39;]</pre><pre># Create a new DataFrame with the specified columns dropped<br>test_without_columns = test.drop(columns=columns_to_drop)<br><br># Concatenate the modified &#39;test&#39; DataFrame with &#39;result_df&#39;<br>final_test_with_sales = pd.concat([test_without_columns, result_df], axis=1)</pre><h3>8. Conclusion</h3><ul><li>Based on the modeling results above, it’s evident that the inclusion of exogenous attributes enhances the model’s performance.</li><li>Building models with pure machine learning techniques is generally more straightforward compared to statistical time series modeling. However, the machine learning algorithms I selected couldn’t directly handle date features, so I had to extract relevant features from the date information.</li></ul><p>For the detailed code implementations, please refer to the notebook available on my <a href="https://github.com/KodwoAmissah/Time-Series-Forecasting-LP3-project-/blob/main/Code/Notebooks/project.ipynb">GitHub page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e713ab54612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Churn Prediction Analysis For Customer Retention at Vodafone]]></title>
            <link>https://medium.com/@kodwoam/churn-prediction-analysis-for-customer-retention-at-vodafone-ae8774d22c09?source=rss-7dbd0a8ea794------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae8774d22c09</guid>
            <dc:creator><![CDATA[Kodwo Amissah-Mensah]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 14:04:08 GMT</pubDate>
            <atom:updated>2023-08-21T11:08:28.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*XGocqrE-t8eNjTzINCEigg.jpeg" /></figure><p>Hi everyone and welcome to my second project.This project focuses on customer churn.As the team lead for this project,me and my team were focused on building a machine learning model that will leverage the dataset and be able to predict if a client will churn or not and also investigate and display the data to uncover patterns and trends in customer churn.This will inturn provide insights to increase revenue.</p><p>The outline for this project will follow the CRISP-DM framework but will not include deployment stage.The outline is a follows:</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>In addition to following the framework as a reference, I will also address the following aspects:</p><ul><li>Hypothesis Testing</li><li>Drawing Conclusions</li></ul><p>Please find a link to:</p><ul><li><a href="https://github.com/KodwoAmissah/Churn-Analysis-LP2-Project-/blob/main/Code/Notebook/project.ipynb">Github Notebook</a></li><li><a href="https://app.powerbi.com/links/6G7B7C1M2e?ctid=4487b52f-f118-4830-b49d-3c298cb71075&amp;pbi_source=linkShare">PowerBi Dashboard</a>: A screenshot of the dashboard will be provided below</li></ul><p>Now let us begin with the project.</p><h3>1. Business Understanding</h3><p>Customer churn which which refers to the rate at which customers stop using their services of a particular and switch to competitors has always been a concern for businesses, but its significance has grown with the rise of subscription-based services and the increased competition in the market. Understanding and managing customer churn is crucial for companies to maintain profitability, sustain growth, and build long-term relationships with their customers.</p><p>The aim of this project,is to find the likelihood of customers leaving the organisation(Churning),the key indicators of the churn as well as strategies that can be implemented to avoid this problem.</p><h3>2. Data Understanding</h3><p>In this project, the dataset resides in 3 places. For ease of access and security we have made the datasets available there in the GitHub Repository</p><h4><strong>- First Data Set</strong></h4><p>The data called LP2_Telco_churn_First_3000 was extracted from a database.</p><h4>- Second Data Set</h4><p>The data called Telco-churn-second-2000.xlsx was found in OneDrive which is our test dataset</p><h4>- Third Data Set</h4><p>The third part of the data called LP2_Telco-churn-last-2000.csv is hosted on a GitHub Repository</p><p>Since we were provided with 3 datasets,and third dataset out of the three will be used for test of future predictions ,we will concatenate the first and last dataset namely LP2_Telco_churn_First_3000 and LP2_Telco-churn-last-2000.</p><p>Before we explore each of the datasets we will want to know what the columns in the dataset represent.</p><h4><strong>Column names and description</strong></h4><p><strong>Gender</strong> — Whether the customer is a male or a female</p><p><strong>Senior Citizen</strong> — Whether a customer is a senior citizen or not</p><p><strong>Partner</strong> — Whether the customer has a partner or not (Yes, No)</p><p><strong>Dependents</strong> — Whether the customer has dependents or not (Yes, No)</p><p><strong>Tenure</strong> — Number of months the customer has stayed with the company</p><p><strong>Phone Service</strong> — Whether the customer has a phone service or not</p><p>(Yes, No)</p><p><strong>Multiple Lines</strong> — Whether the customer has multiple lines or not</p><p><strong>Internet Service</strong>— Customer’s internet service provider (DSL, Fiber</p><p>Optic, No)</p><p><strong>Online Security*</strong>— Whether the customer has online security or not</p><p>(Yes, No, No Internet)</p><p><strong>Online Backup</strong> — Whether the customer has online backup or not (Yes,</p><p>No, No Internet)</p><p><strong>Device Protection</strong> — Whether the customer has device protection or</p><p>not (Yes, No, No internet service)</p><p><strong>Tech Support</strong>— Whether the customer has tech support or not (Yes,</p><p>No, No internet)</p><p><strong>Streaming TV</strong> — Whether the customer has streaming TV or not (Yes,</p><p>No, No internet service)</p><p><strong>Streaming Movies</strong> — Whether the customer has streaming movies or not</p><p>(Yes, No, No Internet service)</p><p><strong>Contract</strong>— The contract term of the customer (Month-to-Month, One</p><p>year, Two year)</p><p><strong>Paperless Billing</strong> — Whether the customer has paperless billing or</p><p>not (Yes, No)</p><p><strong>Payment Method</strong> — The customer’s payment method (Electronic check,</p><p>mailed check, Bank transfer(automatic), Credit card(automatic))</p><p><strong>Monthly Charges</strong> — The amount charged to the customer monthly</p><p><strong>Total Charges</strong> — The total amount charged to the customer</p><p><strong>Churn</strong> — Whether the customer churned or not (Yes or No)</p><p>Since we know the datasets content we will load all three.This is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*RyWaFuptn93UQWNOOtwxsQ.png" /><figcaption>loading data</figcaption></figure><p>After loading the datasets,we perform exploratory data analysis where will we investigate and analyse the datasets.</p><h4><strong>2.1 Exploratory Data Analysis</strong></h4><p>The following section presents the exploratory data analysis (EDA) conducted on the different datasets. We will initiate the analysis with the first dataset.</p><p><strong>EDA On Telco Churn 3000</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*qlNgthEBmY1WgeXrjZXGNw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*e2OHQmItWnsFTAQ_HPNppQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*ckcEXQUk_wOoCJS7KhWn1Q.png" /></figure><p>After performing eda on this dataset this were some things i noticed namely:</p><ul><li>We have a total of 3000 rows</li><li>We have a total of 21 columns</li><li>Our target variable has true/false attributes, therefore it is a binary classification problem</li><li>Online Security,Online Backup,Device Protection,tech support,streaming tv,streaming movies all have 651 missing values and multiple lines has 269 missing values</li><li>There are no duplicated values</li></ul><p><strong>EDA On Telco Churn last 2000</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*HEDhXUybxDbucUQSpThpyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*QVDLTEld32mz-avWoYLdcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*sjNIs6-tr-gsnq1zATjjdA.png" /></figure><p><strong>Notes on Telco Churn last 2000</strong></p><ul><li>We have a total of 2043 rows</li><li>We have a total of 21 columns</li><li>Our target variable has yes/no attributes, therefore it is a binary classification problem</li><li>The Total Charges column is an object data type, so we will check that.</li><li>There are no missing values</li><li>There are no duplicated values</li></ul><p>We will assess the proportion of missing values in the columns of the Telco Churn dataset, which contains 3000 records. This analysis aims to determine the significance of the missing data in relation to our dataset.The process used to assess this is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*S3bbzv0mHxsTJBrMg704CA.png" /><figcaption>Percentage of missing values</figcaption></figure><p>The percentage of the missing values was further visualised on a graph with the code below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*0GboAlMYwk6IvKIiCdSr8A.png" /></figure><p>After identifying the presence of missing values, the next step involves delving deeper into strategies for handling these gaps in the data through imputation techniques.Given that the dataset “telco churn last 2000” exhibits no missing values, our objective is to investigate whether this dataset can provide valuable insights for effectively imputing the missing values present in the “telco churn first 3000” dataset.</p><p>The following steps illustrate the process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*Uopu5-YSp1kWHeMAHHMjYQ.png" /></figure><p>Upon comparing the unique values between the two datasets, several patterns emerged:</p><ol><li>Multiple Lines: In the first dataset, “True,” “False,” and “None” were observed, while the second dataset contained “Yes,” “No,” and “No Phone Service.” Consequently, we deduced that missing values for “Multiple Lines” in the first dataset could be imputed as “No Phone Service,” mirroring the second dataset.</li><li>Online Security, Online Backup, Device Protection, Tech Support, Streaming TV, Streaming Movies: Similar to “Multiple Lines,” the presence of “True,” “False,” and “None” in the first dataset and “Yes,” “No,” and “No Internet Service” in the second dataset led us to infer that missing values in these attributes should be imputed as “No Internet Service.”</li></ol><p>In summary, by leveraging the consistent patterns in attribute values observed between the two datasets, we formulated imputation strategies for handling the missing values in the “telco churn first 3000” dataset. This approach allows us to utilize insights from a complete dataset to enhance the accuracy and reliability of imputed values in the dataset with missing entries.</p><p>Once the imputation strategies for handling missing values have been established, the next step involves merging the dataset from the local database (“Telco Churn First 3000”) with the data sourced from the GitHub repository (“Teleco Churn Last 2000”). This concatenation of datasets aims to combine the enriched information from both sources into a unified dataset for comprehensive analysis and modeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*Q9mRb2uenBkDgKHcYmuMEA.png" /><figcaption>Merged dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*chU3RexPPrNH6jSjutA48w.png" /></figure><p>Examine the testing dataset</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*3innBBc1mQ-MCTi1-W9pBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*O30ZB6BGSgeSAekWmR9eKA.png" /></figure><p>From the overview, it’s evident that both the test dataset and the concatenated dataset have the “Total Charges” column represented as an object data type, which needs to be converted into numerical values.</p><p>Below show the process how</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*yqCs8P6B-n2HyoI0EYjzng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*2hxT54DTN7n9ut7z589CWA.png" /></figure><p>Upon reviewing the concatenated dataset, telco_churn, it becomes evident that there are instances of missing values within the data.</p><p>The approach to handling missing values involves filling the “Churn” column with the mode (most common value), and for other columns with missing values, imputing will be performed based on the previously mentioned strategy of utilizing data from the “Phone Service” and “Internet Service” columns. The provided link to my GitHub repository will offer a deeper insight into the code implementations I utilized for imputing the missing values..Notably, the “Total Charges” column was imputed using the mean, as demonstrated in the following code.</p><p>It’s important to note that a similar methodology was applied to address missing values in the “Total Charges” column of the test dataset as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*IzPIWm7WlcVZlX8c3eQP8w.png" /><figcaption>imputing missing values in churn column</figcaption></figure><p>Upon successfully imputing all missing values and ensuring data cleanliness, I made the decision to exclude the “CustomerID” column from the dataset, as it did not contribute any pertinent information to my analysis.</p><h3>2.2 Data Exploration:</h3><p>In this segment, I will employ a range of visualizations to extract valuable insights from the data, thereby enhancing my understanding of its nuances.</p><h3>2.2.1 Univariate Analysis</h3><h4>2.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.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*LQJwtQEI-BjDGHCP1aHF9Q.png" /></figure><p>From the description, I gained some insights, which included:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*50yT2H4aO-m0Dc4DJMiLHA.png" /></figure><p><strong>2.2.2(a) Checking the distribution of attributes of the dataset</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*7_TdQKUOLjus9ow37l_t2Q.png" /><figcaption>Distribution of the various numeric attributes of the dataset</figcaption></figure><ul><li>Most customers stay on the network for zero months</li><li>Most customers that are charged 25 per month are the highest</li><li>For customers that have zero total charges have the highest frequency.</li></ul><p><strong>2.2.2(b)Univariate analysis for churn column which is our target or label</strong></p><p>I initiated my analysis by examining the “Churn” column. My objective was to visualize the distribution between “Yes” and “No” labels in this column, which represents the target variable for prediction. To achieve this, I created a pie chart using Plotly Express, resulting in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*e9rx3IY5pFGB6GCDTzpcxA.png" /></figure><p>Based on the visual representation, it’s evident that the number of non-churners is higher than the number of churners. This observation highlights a data imbalance issue that needs to be addressed. Given that the project’s objective is to predict churners, handling this data imbalance is crucial.</p><p><strong>2.2.2(c) Univariate of Numerical Features with Respect To Churn</strong></p><p>i)<strong>Monthly Charges</strong></p><p>I proceeded to create visualizations that illustrate the relationship between my numerical features and the target label.</p><p>The image below represents the analysis of Monthly Charges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNqBzPQz5OfRiBEe4OXZXA.png" /><figcaption>Monthly Charges with respect to Churn</figcaption></figure><ul><li>Customers with a monthly charge ranging from $0 to $30 exhibit strong brand loyalty.</li><li>Conversely, a notable proportion of churners were observed among customers who paid a monthly charge in the range of $70 to $110.</li></ul><p>ii)<strong>Total Charges</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBe6zwuAENhxbeL022diGQ.png" /><figcaption>Total charges with respect to churn</figcaption></figure><p>The visual representation above illustrates that a majority of Vodafone’s loyal customers tend to make total charges within the range of $0 to $2000. Likewise, a significant portion of churners also falls within the total charge bracket of $0 to $2000.</p><p><strong>2.2.2 d) Univariate of Categorical Columns with Respect To Churn</strong></p><p><strong>i) Streaming Tv</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*DQCzbKhSf-tsICo4kULGug.png" /><figcaption>Streaming Tv with respect to churn</figcaption></figure><p>After visualising ,i noticed:</p><ul><li>Streaming TV was a common feature among the most loyal customers, while customers who churned tended to have no streaming TV.</li></ul><p>ii)Multiple lines</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*4rKz0intFM2JsDU3UPZsjA.png" /></figure><p>From the visual,For multiple lines the customers that churned and those that did not are almost the same</p><p>iii) Online Security</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*LhQCPp3fiqPNwJgPaB1heg.png" /></figure><ul><li>Customers with No Online Security churned the most</li><li>From the visual customers with no internet service churned the least showing that customers are more interested with the online security</li></ul><h3>2.3. Bivariate Analysis</h3><p>In this context, we explore the interrelationship between two variables by investigating how fluctuations in one variable correspond to shifts in another. Bivariate analysis strives to unveil patterns, correlations, and interdependencies between these two variables, providing insights into their interactions and the potential influence they exert on each other.</p><p>2.3.1 i)<strong>Monthly Charges vs Total Charges</strong></p><p>I generated a scatterplot to visualize the relationship between monthly charges and total charges. The plot reveals a positive correlation between these two attributes.</p><p>In simpler terms, as monthly charges increase, the total charges also increase. Additionally, the scatter plot indicates that as total charges rise, instances of churn (represented by the red dots) decrease.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*epaqkW_E3kY2HbpOK5p5ng.png" /></figure><p>ii) <strong>Relationship Between Tenure and Monthly Charges</strong></p><p>I also investigated the impact of tenure on total charges, revealing a positive correlation between the two variables.</p><p>To put it simply, as the tenure duration increases, the total charges also show an upward trend. However, it’s worth noting that concerning tenure, the occurrence of churn is more prevalent within the initial 19 months, gradually decreasing as customers establish a longer relationship with the company.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*fJm-oDV9_I7MVr3CS83clQ.png" /></figure><p><strong>iii) Relationship Between Total Charges and Churn With Respect To Contract</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*ZMEbGQvEAQT_I9buI6f09g.png" /></figure><h3>Notable Observations</h3><ul><li>Churners tend to have higher expenditure compared to non-churners.</li></ul><h4>For No Churn:</h4><ul><li>Non-churning month-to-month customers spend within the range of $234 to $2,242.</li><li>Non-churning one-year plan customers spend between $961 and $4,692.</li><li>Non-churning two-year plan customers spend within the range of $1,218 to $5,897.</li></ul><h4>For Yes Churn:</h4><ul><li>Churning month-to-month customers have spending ranging from $98 to $1,711.</li><li>Churning one-year plan customers show expenditures between $2,405 and $5,918.</li><li>Churning two-year plan customers have spending spanning from $4,759 to $7,856.</li></ul><h4>For Outliers:</h4><ul><li>Among non-churners, a significant number of month-to-month plan customers spend above $5,222, surpassing the average spending within that sample.</li><li>Similarly, a substantial number of churners on a month-to-month plan spend more than $4,113, considerably higher than the average spending within that sample.</li><li>Notably, only one customer, on a two-year plan, spent less than $740.</li></ul><p>iv) <strong>Relationship Between Churn and Monthly Charges with Respect to Contract</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*71sfB9NWnAmQOHSRYQW5Gg.png" /></figure><h3>Key Findings</h3><ul><li>Churners tend to have higher monthly charges than non-churners.</li></ul><h4>No Churn:</h4><ul><li>Non-churning month-to-month customers have monthly charges ranging from $39.3 to $85.3.</li><li>Non-churning one-year plan customers pay monthly charges between $26 and $93.</li><li>Non-churning two-year plan customers pay monthly charges between $21 and $90, indicating a trend of lower charges with longer tenure.</li></ul><h4>For Yes Churn:</h4><ul><li>Churning month-to-month customers are charged monthly fees ranging from $56 to $92.</li><li>Churning one-year plan customers pay monthly charges between $70 and $118.</li><li>Churning two-year plan customers have monthly charges ranging from $93 to $116.</li></ul><h4>Outliers:</h4><ul><li>Among churners, only six customers on a two-year plan paid monthly charges less than $93.</li></ul><h3><strong>2.4 Multivariate Analysis</strong></h3><p><strong>Heatmap of All Numeric Features</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*CqAG7T3z78hEb_O4fVKsuw.png" /></figure><ul><li>There is a high correlation between tenure and total charges and also between Monthly charges and total charges</li><li>There is a low correlation between tenure and monthly charges</li></ul><h3><strong>2.5 Questions</strong></h3><p>I used a copy of my dataset to answer these questions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*dIkpbBR50caXyKb-vXA-ag.png" /></figure><p>Subsequently, I formulated seven intriguing questions that I sought to explore and uncover answers for:</p><p><strong>Question 1: Which gender exhibited the highest churn?</strong></p><p>i used the code below to answer this question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*4dktln3ocSWovOeVmWn4vA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*yEGBzmSHn3iKWLh9lNhgCw.png" /></figure><p>The churn rate for females is approximately 26.61%, while for males, it stands at approximately 26.38%. The churn rates for both genders are relatively similar, with females having a slightly higher churn rate than males.</p><p>In simpler terms, observing the gender distribution indicates that females tend to have a slightly higher tendency to churn compared to males.</p><p><strong>Question 2: Is the a significant association between gender and churn?</strong></p><p>The <strong>Chi-Square test</strong> can assess whether there is a significant association between the two categorical variables.</p><p>For this question i used the code below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*HbeIcr4llxM7HBaFrQ0aYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*jiBprjk6Squxt_p689u4zw.png" /></figure><p>The code above gives this chart</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*zAlX6XPzC4pSf2Xgb1tvyQ.png" /></figure><p>Hence, considering this analysis, it is not possible to draw a conclusive inference that gender significantly influences the probability of churn within the customer base of the telecommunications company. The variations observed in churn rates between genders might likely be attributed to random fluctuations rather than a definitive correlation.</p><p><strong>Question 3: Does the presence of dependents affect customer churn?</strong></p><p>Below shows the code to answer this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*G8C3cR6KrIA8mXSnFvaUGw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*mF33sFrJi6J8FFDEGriYRA.png" /></figure><p>The resulting code resulted in this graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*31lY1zYbSmJIoq-lrTK1hg.png" /></figure><p>The Chi-Square statistic is 147.65, indicating that there is a significant discrepancy between the observed and expected frequencies of the ‘Dependents’ and ‘Churn’ variables. The P-value is 0.000, which is significantly smaller than the significance level of 0.05. This suggests a significant relationship between the presence or absence of dependents and customer churn. In other words, the presence of dependents does have a significant impact on customer churn in the telecommunications company.For customers with Dependents, the expected count of churn customers is approximately 922.46, and the expected count of non-churn customers is approximately 2559.54.</p><p>For customers with no Dependents, the expected count of churn customers is approximately 413.54, and the expected count of non-churn customers is approximately 1147.46.</p><p>Customers with dependents tend to exhibit different churn behavior compared to those without dependents Therefore, understanding how customer churn behavior varies for customers with and without dependents can help in designing targeted retention strategies for each segment.</p><p><strong>Question 4: Which gender pays more monthly charges?</strong></p><p>This question was answered with this code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*WD291BAXSL-j7SMO6niJdQ.png" /></figure><p>This graph was generated from this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*hPKSXmOHse_abEuwLJvuAg.png" /></figure><p>Averagely, female customers tend to have a slightly higher monthly charges compared to male customers. This could be a valuable insight for the telecommunication company in understanding the spending behavior of its customer base and potentially tailoring marketing strategies or offers based on gender-specific preferences and needs.</p><p><strong>Question 5: Does the presence of dependents affect monthly charges?</strong></p><p>The code below was used to answer this question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*USRMsgVwA5RNoZjtYPkZSQ.png" /></figure><p>Resulting graph is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*-Olypcwnc6mdZda6D-UcGQ.png" /></figure><p>On the average, customers without dependents have higher monthly charges compared to customers with dependents. This insight can be valuable for the telecommunication companies in understanding the spending behavior of different customer segments. It may help them tailor their marketing strategies or offers based on customers’ family status and financial preferences.</p><p><strong>Question 6: Do paperless billing and payment methods influence churn?</strong></p><p>For this question, I used the code below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*ZxusaXUq33jG1Vbp8jbu1g.png" /></figure><p>This graph was generated as a result of the above code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*7VSqhiDv9ld4Ga7GKwaBVg.png" /></figure><p>The graph clearly illustrates that customers who choose paperless billings and opt for electronic check payments tend to experience a higher churn rate in comparison to those who use credit cards, which demonstrate the lowest churn rate. Likewise, even among customers not using paperless billings, those who make electronic check payments exhibit a higher churn rate than credit card users. Notably, within the group of electronic check users, customers who embrace paperless billings are more prone to churn than those who do not opt for paperless billing.</p><p>In summary, it is advisable for the telecommunications company to emphasize the promotion of paperless billing, particularly in conjunction with credit card payments. Additionally, enhancing the electronic check payment experience should be a focal point to address the challenge of elevated churn rates.</p><p><strong>Question 7: Is there a correlation between senior citizens and churn?</strong></p><p>This question uses the code below to answer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*LLhh-qdcT-vQEnYXYPSofw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*0uzz7grRWrvj4LpSnpEySA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*sp9U9D3WnAOgWdMoC9E4nw.png" /></figure><p>This graph was the result</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*v49KcKpl9hHNQfX-mLzYUA.png" /></figure><p>A substantial correlation exists between being a Senior Citizen and the phenomenon of churn. The p-value of 0.000, which is lower than the chosen significance threshold, suggests that the observed association is unlikely to have occurred by chance. This substantiates the significant influence of Senior Citizen status on customer churn.</p><p>For the group labeled as “Not Senior Citizen,” the anticipated count for no Churn is roughly 3105, while for Churn it is around 1119. In contrast, for the “Senior Citizen” group, the expected count for no Churn is approximately 602, and for Churn, it is approximately 217. This dissimilarity in expected frequencies between the two groups, in relation to churn, indicates that being a Senior Citizen indeed wields a substantial impact on churn behavior.</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.</p><h4>3.1 Primary Feature Selection</h4><p>I initiated the process by eliminating specific features that exhibited negligible correlation with the target column (label). As some columns were categorical in nature, I employed the phi-k test for this selection, an extension of phi correlation. This test generates a correlation matrix, quantifying the correlation values among categorical variables. A higher value indicates a more robust association between the variables.</p><p>I used the code below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*gd-LKQ8Yy0ewqMakqxn_MA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*G-umGmAc8oy-vMB78vBzNg.png" /></figure><p>This gave me the chart below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*hCU8r-fo4TJOZd2n7fJ_5w.png" /></figure><p>In this correlation visualization, darker shades represent lower correlation between a specific column and churn.</p><p>Hence, the columns Gender, Multiple lines, and Phone Service exhibit the weakest correlation with churn, all measuring below 0.1. Consequently, these columns will be excluded from further analysis using the code below.</p><pre>## drop columns<br>Telco_churn= Telco_churn.drop([&quot;gender&quot;, &quot;PhoneService&quot;, &quot;MultipleLines&quot;], axis= 1)</pre><h4>3.2 Data Splitting</h4><p>I proceeded to segregate the label (y) — the column to be predicted — from the features (X). Furthermore, I partitioned the data into two distinct subsets: the training set and the evaluation set, which I’ll denote as the test set.</p><p>To accomplish this, I employed the following code snippets:</p><pre>## create features and label<br>X= Telco_churn.drop(&quot;Churn&quot;, axis=1)<br>y= Telco_churn.Churn<br><br></pre><pre>we unpack the data and split it into training and test sets<br><br># Split the data into training and testing sets, with stratification<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)</pre><p>In essence, this indicates my intention to allocate 20% of the dataset for evaluation purposes, while reserving 80% for training the model. The inclusion of “stratify” ensures a balanced distribution of the y variable, guaranteeing an equitable representation of classes.</p><p>Furthermore, I employed a Label Encoder to transform my labels, assigning 0 to represent “No” and 1 to denote “Yes.”</p><pre># Create a LabelEncoder instance<br>LE = LabelEncoder()</pre><pre># Convert the categorical label to numeric<br>num_y_train = LE.fit_transform(y_train)##fit and transform train data<br>num_y_test= LE.transform(y_test)##transform test data</pre><h4><strong>3.3 Preprocessing Pipeline</strong></h4><p>In constructing the pipeline, I addressed both numeric and categorical values by implementing the following steps:</p><h4>For Numeric Values:</h4><p>To address differing magnitudes between the monthly and total transactions, as well as to cater to models sensitive to unscaled data, scaling becomes necessary.</p><h4>For Categorical Values:</h4><p>Conversely, for categorical features, a transformation is required to convert them into numerical representations using a one-hot encoder.</p><p>The provided code snippet illustrates the process of scaling our numeric values and encoding our categorical values.</p><pre># we create a numerical and categorical pipeline <br>num_pipeline= Pipeline([(&quot;scaler&quot;, StandardScaler())])<br><br>cat_pipeline= Pipeline([(&quot;one_hot&quot;, OneHotEncoder())])</pre><p>We are consolidating our numerical and categorical pipelines using a Column Transformer.</p><p>This is illustrated with the code below</p><pre>col_pipe= ColumnTransformer([(&quot;num_pipe&quot;, num_pipeline, num_cols),(&quot;cat_pipe&quot;, cat_pipeline, cat_cols)])</pre><h3>4. Data Modelling</h3><p>Given our binary classification problem, we will employ models specifically designed for binary classification tasks, including:</p><p>* <strong>LogisticRegression Classifier</strong></p><p><strong>* DecisionTree Classifier</strong></p><p><strong>* RandomForest Classifier</strong></p><p><strong>* Gradient Boosting (XGBoost)</strong></p><p><strong>* Support Vector Machines (SVM)</strong></p><p>When assessing each model’s performance, I took into account the following factors:</p><ul><li><strong>Precision</strong></li><li><strong>The f-1 score</strong></li><li><strong>Recall</strong></li><li><strong>Accuracy</strong></li></ul><p>As we center our attention on predicting churners, these metrics will play a crucial role in identifying the optimal model to effectively address this objective.</p><p>Now, let’s delve into the sequential stages:</p><ol><li><strong>Execute an initial model without configuring any parameters.</strong></li></ol><p>This is how it it done using the code below</p><pre>#create pipleline for model<br>log_P= Pipeline([(&quot;coltrans&quot;, col_pipe), (&quot;model&quot;, LogisticRegression(random_state= 100))])</pre><pre>#fit the model<br>log_P.fit(X_train, num_y_train)</pre><p>The code gives this output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*KaeW0J11Nh6ScSKl9TeWiA.png" /><figcaption>Picture of the Logistic Regression Classifier with no parameters</figcaption></figure><p><strong>2. Handle the class imbalance using class_weight and SMOTE and then compare the results</strong></p><p>For class weights we use this code</p><pre># intialize class weight<br>class_weights = compute_class_weight(&#39;balanced&#39;, classes=[0, 1], y=num_y_train)</pre><pre># Assign our weight to our class<br>weight= dict(zip([0, 1], class_weights))<br>print(weight)</pre><pre>{0: 0.6802698145025295, 1: 1.8868101028999065</pre><p>After getting the value of class weight we use it in our pipeline for our model</p><pre>create classweight for model<br>d_tree_CW= Pipeline([(&quot;coltrans&quot;, col_pipe), (&quot;model&quot;, DecisionTreeClassifier(random_state= 100,class_weight=weight))])</pre><pre>#fit the model<br>d_tree_CW.fit(X_train, num_y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*NLPygmKk5U85UVW0Tt-LBQ.png" /><figcaption>Decision Tree Classifier with Class_weight</figcaption></figure><p>For SMOTE</p><p>We don’t directly apply it to the pipeline. Instead, we utilize the column transformer to fit and transform our test data. Subsequently, we employ SMOTE for resampling. The following code snippet demonstrates this process:</p><pre># Fit and transform the ColumnTransformer on the training data <br>X_train_transformed = col_pipe.fit_transform(X_train) <br><br>#  Transform the test data using the pre-fitted ColumnTransformer<br>X_test_transformed = col_pipe.transform(X_test)</pre><pre># Apply SMOTE to the transformed training data and target variable<br>smote = SMOTE(random_state=100)<br>X_train_resampled, y_train_resampled = smote.fit_resample(X_train_transformed, num_y_train)</pre><p>We then use this resampled train and test data on our model</p><pre># Create the final pipeline with SMOTE and RandomForestClassifier<br>RF_SM =Pipeline([<br>    (&quot;model&quot;, RandomForestClassifier(random_state=100))<br>])</pre><pre># Fit the pipeline on your resampled data<br>RF_SM.fit(X_train_resampled, y_train_resampled)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*7GJWJORbss_R0KJaLFxu-g.png" /><figcaption>Random Forest Classifier with SMOTE</figcaption></figure><p>After conducting modeling using Class_weights (_CW), SMOTE (_SM), and the baseline model, I arrived at the subsequent findings:</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.</li></ul><p>as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*l6HAlPJ9QZTdDcngai_ssg.png" /></figure><p>The F2-score is a metric used to evaluate the performance of a classification model. It is a variant of the F1-score that places more emphasis on the model’s ability to correctly classify positive examples (i.e., the “positive class”) while still considering precision and recall.</p><p>Precision measures the ratio of correctly predicted positive observations to the total predicted positives. A higher precision indicates a lower rate of false positives.</p><p>Considering the observed metrics, we will select the model with the higher <strong>precision and F2 score</strong>. Upon comparison, it becomes evident that Logistic Regression with class weights <strong>(Logistic Regression_CW)</strong> demonstrates the <strong>highest precision and F2 score. </strong>Consequently, this particular model will be employed for further utilization.</p><p>A<strong> confusion matrix </strong>will help us understand the accuracy and error types of the model’s predictions by comparing the predicted labels with the actual labels.</p><p>The confusion is visualised below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*L8aPFpBqC4v5_kjhGsHS3w.png" /></figure><p>It’s important to keep in mind that the dataset is imbalanced, and we addressed this by applying class weights to balance it. As a result, our model has the capacity to make accurate predictions for churners. This is evident from the confusion matrix, which indicates a notable level of churner prediction.</p><h3>Explanation of the Confusion Matrix</h3><p>The visual representation of the confusion matrix through the heatmap provides a clear insight into the various prediction outcomes. The cells positioned along the diagonal signify true positive and true negative predictions, whereas the cells outside the diagonal correspond to false positive and false negative predictions.</p><h4>Within the Heatmap:</h4><ul><li>The intensity of color indicates the frequency of instances.</li><li>The cells on the diagonal (from top-left to bottom-right) indicate accurate predictions.</li><li>The cells outside the diagonal denote inaccurate predictions.</li></ul><h4>Interpretation of the Heatmap:</h4><ul><li>The cell at the top-left represents true negatives (correctly predicted negatives).</li><li>The cell at the top-right represents false positives (incorrectly predicted positives).</li><li>The cell at the bottom-left represents false negatives (incorrectly predicted negatives).</li><li>The cell at the bottom-right represents true positives (correctly predicted positives).</li></ul><h4><strong>4.1 K-Cross Fold Validation</strong></h4><p>Cross-validation serves as a comprehensive method to evaluate a model’s performance, offering enhanced robustness compared to a single train-test split. Its utility lies in mitigating the influence of data variability and furnishing a more accurate assessment of the model’s effectiveness.</p><p>The employment of k-Fold cross-validation facilitates the evaluation of the model across diverse data subsets, enabling the detection of potential overfitting or underfitting challenges.In K-fold cross-validation, the evaluation of the model is performed multiple times, equal to the number of folds (K). During each iteration, one fold is designated as the validation set, and the model is trained on the remaining K-1 folds. This allows for a comprehensive assessment of the model’s performance using different subsets of data for training and validation in each iteration. The final performance metric is usually averaged across all K iterations to provide a more accurate estimate of the model’s effectiveness.</p><p>The selection of 10 folds (num_folds = 10) strikes a desirable equilibrium between model appraisal and computational efficiency. Ten-fold cross-validation is a widely adopted approach in practical applications.</p><p>In our chosen model, we will implement K-fold cross-validation, and the subsequent code snippet illustrates its application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*A5rBF3GH4_t2KXujSTh8wA.png" /></figure><p>From the code you can see the accuracy of the model vary across the various folds indicating how each fold affects the model.</p><h3>5. Hyperparameter Tuning</h3><p>Hyperparameter tuning involves identifying the optimal values for a machine learning model’s hyperparameters in order to enhance its performance. Hyperparameters are configuration settings that profoundly influence the model’s behavior and its ability to generalize to new data, yet they are not learned directly from the data. The process of tuning these hyperparameters can result in improved model performance and better generalization when faced with unseen data.</p><p>To conduct hyperparameter tuning, I employed GridSearchCV. I fine-tuned the subsequent parameters:</p><ul><li>The C-parameter</li><li>The Penalty</li><li>The Solver</li></ul><p>The code is displayed below:</p><pre># Define the parameter grid for grid search<br>param_grid = {<br>    &#39;model__C&#39;: [0.001, 0.01, 0.1, 1, 10, 100],<br>    &#39;model__penalty&#39;: [&#39;l1&#39;, &#39;l2&#39;],<br>    &#39;model__solver&#39;: [&#39;liblinear&#39;],<br><br>}</pre><p>Subsequently, we applied GridSearchCV to the selected model and the specified parameters, utilizing it to fit the training data. The corresponding code is displayed below:</p><pre># Create the grid search object<br>grid_search = GridSearchCV(log_P_CW, param_grid=param_grid, cv=5, scoring=&#39;accuracy&#39;)</pre><pre>#Perform the grid search:<br>grid_search.fit(X_train, num_y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*cjfvhOdHcRvrq1nWT7Mj5g.png" /></figure><p>After fitting we use gridsearch to get the best hyperparameters,best score and best model.This is shown by the code below</p><pre>#Get the best parameter results and best_score<br>best_hyperparameters = grid_search.best_params_<br>best_score = grid_search.best_score_<br><br>print(f&quot;best hyperparameters are:{best_hyperparameters}&quot;)<br>print(f&quot;best score is {best_score}&quot;)</pre><pre>best hyperparameters are:{&#39;model__C&#39;: 10, &#39;model__penalty&#39;: &#39;l2&#39;, &#39;model__solver&#39;: &#39;liblinear&#39;}<br>best score is 0.7516110583264919</pre><pre>#### We get the best model<br>best_model = grid_search.best_estimator_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*7NwDKdgx-7YHfg-6OWXpxg.png" /></figure><h3>6. Model Evaluation</h3><p>Once we obtained our optimized model using GridSearchCV, we proceeded to utilize this model for making predictions on our previously unseen data. This unseen data corresponds to our test set, specifically the Telco_churn Second 2000 dataset.</p><p>Once the optimal model is employed to make predictions on the test set, the resulting predictions are added as a new column named “churn” in the test set DataFrame. The following code snippet illustrates the process:</p><pre>###use best model to predict<br>final_result=best_model.predict(test_set)</pre><pre># Create a new DataFrame to store the results<br>result_df = pd.DataFrame(final_result, columns=[&quot;Churn&quot;])<br></pre><pre># Concatenate the original test set and the result DataFrame along the columns<br>final_test_with_churn= pd.concat([test_set, result_df], axis=1)</pre><pre>we view to confirm changes <br>final_test_with_churn.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*-h3EL0nK6lD_S0rPhXnaNA.png" /></figure><p>From the code you can see a column named churn has been added</p><h3>7.Hypothesis Testing</h3><p>This is my hypothesis</p><p><strong>Null Hypothesis (H0):</strong> The Monthly Charges, Total charges and tenure do not have significant impact on the Churn rate.</p><p><strong>Alternative Hypothesis (H1):</strong> The Monthly Charges, Total charges and tenure significantly impact the Churn rate.</p><p>For my hypothesis testing,i used Logistic regression</p><p><strong>logistic regression </strong>is a type of multiple regression used for predicting binary outcomes, and it is a suitable approach for analyzing the impact of multiple predictor variables (independent variables) on a binary categorical target variable (dependent variable).</p><p>The code below shows how it was used</p><pre>#we put the features that we want to see whether they have impact on churn or not in a variable and do same for churn<br>X = Telco_churn_copy[[&#39;MonthlyCharges&#39;, &#39;TotalCharges&#39;, &#39;tenure&#39;]]<br>y = Telco_churn_copy[&#39;Churn&#39;]</pre><pre># Convert the &#39;churn&#39; variable to binary numeric values (0 and 1)<br>y = pd.get_dummies(y, drop_first=True)[&#39;Yes&#39;]</pre><pre># Add an intercept<br>X = sm.add_constant(X)<br><br># Fit the logistic regression model<br><br>logit_model = sm.Logit(y, X)<br>result = logit_model.fit()<br><br>print(result.summary())</pre><p>And the results were</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*0nzPB6JLhLCIujFtg4hBGg.png" /></figure><p>The <strong>Pseudo R-squared</strong> value reflects the extent to which the model accounts for the variance in the data. A higher value signifies a stronger fit of the model.</p><p>In this case, the computed Pseudo R-squared value is 0.2179, approximately indicating that around 21.79% of the variability in the probability of churn can be attributed to the included predictor variables.</p><p><strong>Coefficients</strong>: The sign of a coefficient illustrates the direction of the relationship between a predictor variable and the likelihood of churn. A positive coefficient implies that an increase in the predictor variable is linked to a higher probability of churn, while a negative coefficient suggests the opposite.</p><p><strong>P-values of Predictors</strong></p><p>The p-value acts as a metric to determine whether a specific variable significantly affects the likelihood of churn. If the p-value of a variable is lower than the predefined significance level (usually 0.05), it implies a significant impact on the probability of churn. Conversely, if the p-value is greater, the variable does not wield a significant impact on the probability of churn.</p><p><strong>The likelihood ratio test (LLR) </strong>p-value evaluates the collective significance of all predictor variables incorporated in the model.</p><p>With a calculated LLR p-value of 3.069e-275, significantly below the predetermined significance level of 0.05, substantial evidence arises against the null hypothesis. This signifies that the combined impact of the predictor variables on churn holds remarkable statistical significance.</p><p>From this we reject our null hypothesis</p><h3>8. Conclusion</h3><p>Exploring customer churn and refining strategies to retain customers provides valuable insights into understanding consumer behavior and enhancing business performance. This analysis yielded significant takeaways:</p><p><strong>Churn Distribution</strong>: The majority of customers remained loyal throughout the observed period, revealing a significant portion of non-churned customers.</p><p><strong>Key Features</strong>: Key influencers like contract type, monthly charges, and tenure were identified through feature analysis. Businesses should prioritize these factors when formulating retention strategies.</p><p><strong>Data Imbalance</strong>: Handling imbalanced data posed challenges. Techniques such as SMOTE and class weight were employed to balance the dataset, aiding model training and performance.</p><p><strong>Model Success</strong>: Machine learning models, especially Random Forest and Logistic Regression, exhibited promising predictive accuracy. Rigorous hyperparameter tuning and model evaluation played a pivotal role in optimizing model efficacy.</p><p><strong>Preserving Valuable Customers</strong>: Pinpointing high-value customers prone to churn enabled personalized retention measures. This proactive approach can bolster customer loyalty and curb churn rates.</p><h3>Challenges Faced:</h3><p><strong>Data Imbalance</strong>: Tackling imbalanced data demanded strategic utilization of SMOTE and class weight techniques to ensure fair representation and model enhancement.</p><p><strong>Hyperparameter Tuning</strong>: Fine-tuning model hyperparameters was intricate due to diverse possibilities. Grid search and cross-validation emerged as indispensable tools for identifying optimal parameter configurations.</p><p><strong>Interpreting Insights</strong>: Gaining a deep understanding of complex models like Random Forest and Linear Regression proved challenging due to their complexity. Feature importance analysis was instrumental in shedding light on the relationships between features and churn.</p><h3>The Path Forward:</h3><p><strong>Continuous Monitoring</strong>: Regularly tracking customer churn trends and analyzing fresh data offers valuable insights into evolving customer behaviors. This facilitates timely adjustments to retention strategies.</p><p><strong>Predictive Analytics</strong>: Exploiting advanced predictive analytics techniques like deep learning and ensemble methods has the potential to enhance the accuracy of churn prediction models.</p><p><strong>Feedback Loop</strong>: Establishing a feedback loop that captures customer interactions and outcomes empowers ongoing refinement of models and strategies.</p><p>To sum up, the analysis of customer churn delivers actionable insights to guide businesses in customer retention and overall performance enhancement. Through advanced analytics, ongoing monitoring, and customized strategies, organizations can effectively combat churn and foster enduring customer loyalty.</p><p>Displayed below is a snapshot of the Power BI dashboard I utilized to derive valuable insights. The link to access this interactive Power BI dashboard, along with my GitHub repository, is provided at the outset of my article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRz8h1ZQRIG0ESKOCK7nRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Im2QtWnNE7vqhB_USS2Mgw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae8774d22c09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Exploring The Startup Ecosystem In India]]></title>
            <link>https://medium.com/@kodwoam/understanding-and-exploring-the-startup-ecosystem-in-india-1129cf69d60b?source=rss-7dbd0a8ea794------2</link>
            <guid isPermaLink="false">https://medium.com/p/1129cf69d60b</guid>
            <dc:creator><![CDATA[Kodwo Amissah-Mensah]]></dc:creator>
            <pubDate>Sat, 22 Jul 2023 21:27:55 GMT</pubDate>
            <atom:updated>2023-07-23T20:46:26.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8XlglFu682cDiI-j" /><figcaption>Photo by <a href="https://unsplash.com/@raghunayyar?utm_source=medium&amp;utm_medium=referral">Raghu Nayyar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is my first major project as part of a team in Azubi Africa’s Data Analytics Program.My team and i were assigned to analyse the Indian startup ecosystem.This task was rather tedious due to the nature of the datasets.There are four datasets in total, each covering a different year from 2018 to 2021.Each dataset had a lot of discrepancies from misplaced values to spelling error and a whole lot.Each dataset was really dirty but with good communication between me and my team the data was able to be cleaned thoroughly and removed of all errors.</p><p>The aim of this project is to gain a comprehensive understanding of the funding landscape for start-ups in India from 2018 to 2021 by analyzing the funding data, the project seeks to uncover trends, patterns, and factors influencing start-up funding in India.</p><p>Before exploring this project,the outline of the article is as follows:</p><ul><li>Business Understanding of The Indian Startup Market</li><li>Data Understanding</li><li>Null and Alternate Hypothesis</li><li>Questions Explored</li><li>Library Installation and Importation</li><li>Exploratory Data Analysis</li><li>Hypothesis Testing</li></ul><p>Let us begin with the business understanding of the Indian ecosystem</p><h3><strong>1. Business Understanding of The Indian Startup Market</strong></h3><p>The Indian startup ecosystem has experienced tremendous growth and transformation in recent years, making it one of the most dynamic and vibrant startup ecosystems globally.India is home to a large and diverse population, providing a massive market for startups to target. Overall, the Indian startup ecosystem presents a fertile ground for entrepreneurs and investors alike, offering diverse opportunities for innovation and growth across various sectors. With increasing investments, and a large consumer base, the future looks promising for the Indian startup landscape.The objective includes evaluating and leveraging the thriving Indian startup ecosystem and the impact of funding on start-up success, identifying sectors attracting the most investment, and providing actionable insights for stakeholders. The analysis will focus on the distribution of funding amounts and stages of funding reached.The goal of this analysis is to determine the most effective approach for investment. The project also aims to empower stakeholders with knowledge and insights to navigate the Indian start-up ecosystem effectively.</p><h3>2.Data Understanding</h3><p>In this project, the dataset resides in 3 places. For ease of access and security we have made the datasets available there in the GitHub Repository</p><h4>- First Data Set</h4><p>The data for 2020 and 2021 where extracted from a database.</p><h4>- Second Data Set</h4><p>The data for 2019 was found in One Drive.</p><h4>- Third Data Set</h4><p>The third part of the data (data for 2018) is hosted on a GitHub Repository in a file called startup_funding 2018. csv</p><h3>3.<strong> Null and Alternate Hypothesis</strong></h3><h4>Null Hypothesis:</h4><p>There are no significant differences in the funding amounts among the top 10 sectors.</p><h4>Alternate Hypothesis:</h4><p>There are no significant differences in the funding amounts among the top 10 sectors.</p><h3>4.Questions Explored</h3><p>a) What are the overall funding trends in the Indian start-up ecosystem during the analyzed period?</p><p>b) What are the top 10 companies/brands in the startup ecosystem based on the highest funding amounts received?</p><p>c) Which sectors attracted the most funding and experienced the highest growth?</p><p>d) Who are the top 10 investors in the Indian start-up ecosystem?</p><p>e) Which Top 10 cities have attracted the highest total funding amounts for start-ups?</p><p>f)Has there been any change in the distribution of headquarters locations over the analyzed period?</p><h3>5.Library Installation and Importation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*aPZSi-b1L7yqscB8AEy1jg.png" /></figure><h4>Data Loading</h4><p>The 2020 and 2021 dataset was stored in a database .The process to access this is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Kzjm6QidqjXkvmAfSBnv7Q.png" /></figure><p>The 2018 data was in a github repository and the 2019 was found in a onedrive. I downloaded the dataset and went ahead to load it in vscode together with the 2020 and 2021 dataset.A new column named year will be added to each of the dataset to help us know the year each row represents.The code can be seen below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*tmltz9xv5Sw6qd63JrXAvA.png" /></figure><h3>6. Exploratory Data Analysis</h3><p>Here we will analyze and investigate data sets and summarize their characteristics by using data visualization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*4rYbl1Qv8e3gss3qQAgyyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*GZAiINKj_JuKB1C-siIExA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*dQu_9k_vpaXBL3Nc5dE1Pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*MoQHFWZgon4c6LPr2bDoJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*GBIRNsgDp8c2JDNw-JVa3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*G_1f4oelS-qYjSKmczT8SA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*h6KTc11of7vBHol7FkeYwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*S0gmAk1h5bFonQismWxjkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*zF3iBEZDz9mw7nSy_6Wmaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*wNzKaZSjIvrf9Nd2bzmnew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*5IcVfj965r-3r_ZkRfyePw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*tZr29akY7QqRVhRQ1szMxQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*VI2Z5xhwqBm-yTPRg2yEvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*iQIT3kDFKTZ-rU5vdkhfKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*10YjO0L2w1Jlpky3qUvu5A.png" /></figure><p>For the dataset i observed some issues which will be resolved when analyzing and cleaning the data.These issues include:</p><ul><li>The 2018 dataset is missing 3 columns</li><li>The 2020 dataset has an additional column named column 10 which will be analysed to see it’s content</li><li>The datatype of the amount column in 2021,2018 and 2019 is in object</li><li>2018 dataset has no missing values in any of the columns</li></ul><p>Also each column in all the datasets will be thoroughly inspected to check for inconsistencies and variations, Duplicates will be removed from each dataset and datatypes will be checked.</p><p>Since we now have a fair knowledge of what our datasets entails,before cleaning each dataset,duplicated values will be removed and each column in each dataset will be analysed meticulously to ensure uniformity through out each dataset.</p><h3>6.1 Handling Duplicated Values</h3><p>The process taken to handle the missing values is shown below and this process was also used for all the other datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*4GsfX5PWXlcK8G_91-2zwA.png" /></figure><h4>6.1.1 Checking Company Brand column for errors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*gG9AnMHTHGYy6X55AoRmRw.png" /></figure><p>In the company brand column the only issue noticed was there were companies that used their websites instead of the company name so i removed the website to maintain the name of the company.This error was also noticed in all the other datasets and the same solution was also applied.After this we view the company brand to ensure the changes were made.The code below will show this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*ohwohf9NgDDYJiAG7Bh-6w.png" /></figure><h4>6.1.2 Checking Founded column for errors</h4><p>In all the datasets,the founded column had no errors or discrepancies</p><h4>6.1.3 Checking Headquarter column for errors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*xnRZZL5StDUb6nPyAe5WLw.png" /></figure><p>In the headquarter column of the 2020 dataset these errors were noticed:</p><ul><li>In the headquarters column we noticed the headquarters where attached to their countries and we took the first index</li><li>From research we noticed the official name of bangalore is bengaluru so we changed it</li><li>From research we noticed the official name of Gurgaon is Gurugram so we changed it</li><li>There was a spelling error in one of the headquarter names</li></ul><p>The codes on how all these were handled is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*aBOOp1ZYBq_iu7_l2FMqzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*37P6qRF9kEtXW5i7NuF-0g.png" /></figure><p>The results of the codes used were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*UPDDxy2cVyqwin5M-rhJpQ.png" /></figure><h4>6.1.4 Checking Sector column for errors</h4><p>With the sector column in the 2020 dataset, i noticed these errors</p><ul><li>Some values in the sector column were swapped</li><li>Noticed sectors have sub sectors attached so we took the first index</li><li>Corrected some spellings mistake in the sector to make the sectors uniform</li></ul><p>Below are the codes used to handle the errors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*p4YdvNoqdV4rzDbES8RWmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*bwtcnPv8fvJsuKgVuDS6zA.png" /></figure><p>The result of the codes above is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*rDO4nBCVz5Yvccp53GhpWg.png" /></figure><h4>6.1.5 Checking for errors in what it does column</h4><p>In the 2020 dataset,what it does has no errors</p><h4>6.1.6 Checking for errors in Founders column</h4><p>In the founded column i noticed that</p><ul><li>Some of the names of the founders had commas(,) and question marks(?) attached to them</li><li>Some of the names were also all in capital letters</li></ul><p>These errors were corrected in the codes below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*a_lz8tA8Ca23HDpFniK6Hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*zyTgBeTvSW5_Z516Ib8JRg.png" /></figure><p>The results of the code above are shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*NEC1B87x7z5i-VtUZ7e5ug.png" /></figure><h4>6.1.7 Checking error in investor column</h4><p>A row had a greater than(&gt;) symbol infront of the investor name</p><p>The code below shows how it was handled</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*GoWMpKpxS26T9n_hp_E1Pg.png" /></figure><p>The results of the code above has is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*VqK4yEzoAweRD9UP0alv-w.png" /></figure><h4>6.1.8 Checking errors in Amount column</h4><p>For the amount column 1 assumed the values were in dollars.In this column no errors were found</p><h4>6.1.8 Checking errors in Stage column</h4><p>I observed these error in the Stage columns</p><p>* A row in the stage column had an investor named attached to it so we took the first index which is the stage name</p><ul><li>Corrected spellings mistake to make stage column uniform</li></ul><p>The code below handles these errors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*Mtmfqwq9m9Vx_Itzebq2ag.png" /></figure><p>The result is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*_UTlsweQKO0rDa3DSfH-PQ.png" /></figure><p>These were some of the steps that were used to handle the errors in the dataset.To know how all the datasets were cleaned and the columns renamed the link to my github repository will be added at the ended of this article.</p><h4>Univariate Analysis</h4><p>We aim to understand the distribution, central tendency, spread, and other key characteristics of the data</p><p>After each dataset was cleaned, i renamed the columns to allow uniformity.</p><p>After renaming, i went ahead to concatenate everything together.</p><p>I started by taking a statistical description of the whole dataset.This resulted to the output below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*gawHWx828raWlc8gagcgEQ.png" /></figure><p>After viewing the statistical description of the concatenated dataset,i view the datatypes of each column and dropped the columns that were to relevant to my analysis.The columns dropped were:</p><ul><li>Founded</li><li>Founder’s</li><li>What it does</li><li>Stage</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*Cv7ynHvmENmh0oAFwZCw4w.png" /></figure><p>After this process the numerical column will be visualised to determine how the missing values will be imputed.</p><p>I used a boxplot to visualise the numerical column</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*_YZuypdP5-gJ4Tng0LViXA.png" /></figure><p>The result of the code is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*awzTKN5PWbKc9La6hVPWrQ.png" /></figure><p>For the amount column zero(0) will be repalce with np.nan to make it easier to impute.This code was used to replace the number zero</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*OXczqIuL-kB4sLQsatVOaQ.png" /></figure><p>I will now the check the number of missing values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*tkLB4Rk2YOLoIg-xpbmyfA.png" /></figure><p><strong>From the univariate analysis the following observation were made;</strong></p><ul><li>Sector,Headquarter,amount and investor columns had missing values.</li><li>Due to the very high huge outlier recorded. The median value to fill in the missing values of the amount column</li></ul><h4><strong>Missing/NaN Values</strong></h4><p>There are missing values in the following columns:</p><ul><li>HeadQuarter</li><li>Sector</li><li>Amount</li><li>Investor</li></ul><p><strong>Handling missing values in Amount column</strong></p><p>The amount column has a huge outlier therefore the missing values will be imputed with the median.The code below show how the values were imputed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*6dlgS66-pt6Izoz4rlcDlQ.png" /></figure><p><strong>Handling Missing Values in Categorical Column namely</strong></p><ul><li>Sector</li><li>HeadQuarter</li><li>Investor</li></ul><p>The reason we are choosing not to impute the missing values in the columns with the mode is to not contaminate the dataset so we will replacing the missing values with Unknown</p><p>The code to replace the missing values is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*q6ku-MSMCRtcJqpEHS7gqg.png" /></figure><h4>Bivariate Analysis</h4><p>I went ahead to use bivariate analysis since the questions explored involved analyzing two columns</p><h3>Questions Explored</h3><p><strong>a) What are the overall funding trends in the Indian start-up ecosystem during the analyzed period?</strong></p><p>The code below was used to answer this question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*oFJ2h44hQwfLcik6fOTLXw.png" /></figure><p>The output of the above code is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*OzYJVATCNznRE0fOsfVlYQ.png" /></figure><p>The trend direction dropped slightly in 2018 indicating a negative trend of decreasing funding amounts during that year. However, the shift changed from 2019 through to 2021. The trend predominately shot up indicating increasing funding amounts over the period.It means that there was significant funding growth during this period.</p><p>This upward trend suggests a period of substantial funding growth and indicates a positive outlook for the Indian start-up ecosystem during that time.</p><p><strong>b)What are the top 10 companies/brands in the startup ecosystem based on the highest funding amounts received?</strong></p><p>The code below was used to answer this question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*GWeN7VklnGFBnXy7wNV-ng.png" /></figure><p>The output of the code is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*om_kxwFJkBK0HtZZ_0uTyg.png" /></figure><p>Alteria Capital secured the highest funding amount of 150 billion dollars, making it the leading company in terms of funding. Reliance Retail Ventures Ltd follows closely behind with a funding amount of 70 billion dollars.</p><p>Snowflake secured the third-highest funding with 3 billion dollars. Reliance, with 2.2 billion dollars in funding, takes the fourth position. Swiggy and VerSe Innovation both secured 1 billion dollars in funding, placing them in the fifth and sixth positions, respectively. Dream Sports received funding of 840 million dollars, ranking seventh.</p><p>Reliance Retail Ventures secured another spot in the top 10 with 800 million dollars in funding. Swiggy also appears again in the list, matching the funding amount of 800 million dollars. SBI Life closes the top 10 with funding of 742 million dollars.</p><p><strong>Conclusion</strong></p><p>These funding amounts represent significant investments in these companies/brands, indicating their potential for growth and success in the startup ecosystem.</p><p><strong>c) Which sectors attracted the most funding and experienced the highest growth?</strong></p><p>This question is answered with the code below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*U3xodWlDEZs7Bdd374dVMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*SbJ7Cd2hgCF9LtRvkDO-mQ.png" /></figure><p>The result of the code for highest funding is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*Rjwq2dVUm4-yJysciYPK1A.png" /></figure><p><strong>Sectors with the highest funding</strong></p><p>With a total funding amount of 154.89 billion dollars, FinTech sector attracted the highest funding during the analyzed period. The Retail sector secured the second-highest funding with a total amount of 70.55 billion dollars. EdTech sector received substantial funding amounting to 6.05 billion dollars, placing it in the third position. Tech sector obtained funding of 3.83 billion dollars, showing significant investment in this sector. E-commerce sector attracted considerable funding with a total amount of 2.99 billion dollars.</p><p>We plot the sector with the highest growth rate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*Cwj2WWfq0FOlhw_3QSprxQ.png" /></figure><p>The output is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*LMsdGhlIxjcmEPubK2gy_Q.png" /></figure><p><strong>Sectors with the highest growth</strong></p><p>FinTech sector exhibited remarkable growth with a growth rate of approximately 867,229.43%. This indicates a substantial increase in funding compared to the initial amount. The Sports sector experienced significant growth with a growth rate of approximately 24,526.92%.Social Media sector achieved substantial growth with a growth rate of 18,000%.The Gaming sector showed notable growth with a growth rate of 13,810%. The Dating sector experienced significant growth with a growth rate of 12,425%.</p><p><strong>Conclusion</strong></p><p>FinTech sector not only attracted the highest funding but also experienced substantial growth during the analyzed period. The Retail sector also secured a significant amount of funding, while other sectors like EdTech, Tech, and E-commerce demonstrated noteworthy investment. Additionally, sectors such as Sports, Social Media, Gaming, and Dating showed significant growth rates, suggesting emerging opportunities and investor interest in these sectors.</p><p><strong>d) Who are the top 10 investors in the Indian start-up ecosystem?</strong></p><p>The code below answers this question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*gXPPQxoEH1ojhq98zmVngQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*g7qVK8dtN9eqYKvBK--Htg.png" /></figure><p>The output of the code is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNmgSNxtTrlVCkKKcntXjg.png" /></figure><p>Silver Lake,Mubadala Investment Company has the highest total funding amount, indicating a significant contribution to the start-up ecosystem.This investor’s funding amount surpasses all others by a large margin. Notable investors such as Salesforce Ventures,Dragoneer Investment Group which is the second highest also hold substantial funding amounts.</p><p>The list of top investors includes a mix of well-known companies and investment firms such as Facebook, Google, KKR, and Silver Lake, highlighting their active participation in funding Indian start-ups. This diversity suggests a broad range of expertise and resources being brought into the ecosystem.</p><p>The funding amounts of the top 10 investors vary significantly, ranging from billions of dollars to hundreds of millions of dollars. This indicates that different investors have varying levels of involvement and financial commitments in supporting start-ups in India.</p><p>The presence of prominent investors in the top 10 list signifies a high level of confidence and belief in the potential of Indian start-ups. These investors’ financial backing suggests that they see promising opportunities for growth and innovation within the Indian entrepreneurial landscape.</p><p><strong>Conclusion</strong></p><p>There is a strong financial support provided by a diverse group of investors to the Indian start-up ecosystem. Their investments not only provide capital but also bring expertise, resources, and networks that can contribute to the success and development of start-ups in India.</p><p><strong>e) Which Top 10 cities have attracted the highest total funding amounts for start-ups?</strong></p><p>The code to answer this question is below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*MU6ijfQt-PBHaK4cAyOtWw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*ZrOiUHYIM297b-PSazvvzw.png" /></figure><p>The output is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*9USmncd-JFjABgoj5UpM0Q.png" /></figure><p>The top city with the highest total funding amount for start-ups is Mumbai, with a staggering amount of 230,965,800,000 dollars. This indicates a significant level of investment in the start-up ecosystem in Mumbai. Bengaluru follows closely behind with a total funding amount of 24,652,630,000 dollars. It is evident that both Mumbai and Bengaluru have emerged as major hubs for start-up funding in India.</p><p>Other cities in the top 10 list include Gurugram, New Delhi, California, Pune, Chennai, Haryana, and Delhi. These cities have also attracted substantial funding amounts, demonstrating the diverse geographical distribution of start-up funding in India.</p><p><strong>Conclusion</strong></p><p>These findings highlight the concentration of funding in certain cities, reflecting the presence of a vibrant start-up ecosystem and the attractiveness of these cities for investors.</p><p><strong>f)Has there been any change in the distribution of headquarters locations over the analyzed period?</strong></p><p>The code below was used to answer this question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*1nhmIojU17auY3ipSmTdSQ.png" /></figure><p>And the resulting output is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*aQG82ZdWB3Csb3ou4nMISA.png" /></figure><p>After conducting the analysis, it becomes evident that Bengaluru hosts a significantly higher number of startups in it’s city as compared to others during the years . The graphical representation further highlights that the number of startups in Bengaluru surpassed the count in other cities in 2021. Subsequently, the years 2018, 2020, and 2019 followed this pattern, respectively.</p><h3>7.Hypothesis Testing</h3><p><strong>Null Hypothesis (H0):</strong> There are no significant differences in the funding amounts among the top 10 sectors.</p><p><strong>Alternative Hypothesis (H1):</strong> There are significant differences in the funding amounts among the top 10 sectors.</p><p>We will have to get the top 10 sectors with the most funding</p><p>The code below shows how</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*p1XdUcPZIzE8Gkc9yAQmgw.png" /></figure><p>The output results in</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3Cc3vYQ5Vb6VXV7Xqc5jg.png" /></figure><p>These sectors represent the areas in which start-ups have received the highest funding amounts. The order of the sectors is determined by the total funding received in each sector, with FinTech being the sector that has received the highest funding amount, followed by Retail, EdTech, Tech, E-commerce, Automotive, Multinational conglomerate company, Financial Services, Food Delivery, and Hospitality.</p><p>This information provides insights into the sectors that have attracted significant investment in the Indian start-up ecosystem. It highlights the sectors that have shown promising growth potential and have gained the attention of investors. These sectors may offer attractive opportunities for entrepreneurs and investors looking to enter or invest in the Indian start-up market.</p><p>Some assumptions must be met before we choose which test to use</p><p><strong>Assumptions to be met</strong></p><ul><li><strong>Normality</strong></li><li><strong>Equal Variance</strong></li></ul><p><strong>Normality</strong> refers to the assumption that the data follows a normal distribution. In a normal distribution, the data is symmetrically distributed around the mean, with the majority of the values clustering around the mean and fewer values towards the tails of the distribution.</p><p><strong>Equal variance</strong>, also known as homogeneity of variance, refers to the assumption that the variability of the data is approximately the same across different groups or categories. In other words, it assumes that the spread of data is similar across the levels of a categorical variable or the groups being compared.</p><p>Violations of these assumptions can impact the validity and reliability of the results obtained from these analyses. Therefore, it is essential to assess normality and equal variance to ensure the appropriateness of the chosen statistical methods.</p><p><strong>Normality Check</strong></p><p>We will run descriptive statistics on the top 10 sectors</p><p>The code below will show the descriptive statistics</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*YrYSpYoskOUaWyuRLFMp-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*6Wn0_Dfho8YYKT5GJm4vCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*NsQCcb5JDkfBza_JqqFUlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*d9MyApeo6x5oS3yfGuowmA.png" /></figure><p><strong>Observations</strong></p><p>There is a significant difference between the mean and median for FinTech(which indicate that the data is skewed or not symmetric), along with the large standard deviation and the presence of outliers, indicates potential deviations from normality. Further analysis, such as formal statistical tests for normality, would be required to confirm the distribution characteristics.</p><p>The same applies to Retail sector, EdTech, Tech, E-commerce, Automative sector, Financial Services, Food delivery and Hospitality Sector.</p><p>The mean funding amount for the ‘Multinational conglomerate company’ sector is 2,200,000,000.00, and the median is also 2,200,000,000.00. Since the mean and median are equal, it suggests that the data is symmetric and not skewed. The standard deviation is reported as NaN. This occurs when there is no variability in the data or when all the values are the same. In this case, the standard deviation is undefined, likely because there is only one data point available for the ‘Multinational conglomerate company’ sector. The minimum and maximum funding amounts are both 2,200,000,000.00, indicating that there is no variability in the data. This further supports the absence of standard deviation.</p><p>However, with only one data point available, it is not possible to determine the distribution characteristics or make any definitive conclusions about the normality of the data.</p><p><strong>Visual inspection:</strong>We create a histogram to visually inspect the distribution of funding amounts for the sector.</p><p>Look for bell-shaped distributions that resemble a normal distribution.</p><p>We create a histogram to visually inspect the distribution of funding amounts for the sector.</p><p>Look for bell-shaped distributions that resemble a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*6fE8fJdz6Iwv-eg1PTY6ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*XSSjyduUmDeO9XPPVomawg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*SBhbRoxw0Wa0SCuIG-9sPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*HmsFpnDmTcI-vzVNZxHYAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*HzLFTYdjXIG4Koj2rYNZdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*k05pqHrgUGW7e0ZYfVqO9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*pGRBQGtOz5Zsk0j7hJhCnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*2ON1FZ8CAvUxG1Nl6pra6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*aWHEO7PntoFTB8aFobg9-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*xsMG2RvzaOW-qOtYrkf51Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*cqGlcuwCzm2KUZVXjOUSdA.png" /></figure><p>From the charts above, we can see that the charts do not have the bell shape, indicating that the distributions are not normal. To gain more insights into whether the data for each sector approximately follows a normal distribution we have to run a Quantitative Test(Shapiro-Wilk test, Anderson-Darling test, and Kolmogorov-Smirnov test)</p><p><strong>Quantitative Test using Shapiro-Wilk test</strong></p><p>The <strong>Shapiro-Wilk test</strong> is a statistical test used to assess whether a given data sample is likely to come from a normally distributed population. It is a commonly used test for checking the normality assumption of a dataset.</p><p>This test generate a test statistic and a p-value. A p-value greater than the chosen significance level (e.g., 0.05) indicates that the data can be considered normally distributed.</p><p>The code is shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*e5XXdYBfsciwliiNUNw60g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*w0FqU_W0OgkUeGUF5IItPA.png" /></figure><p>The <strong>test statistic</strong> is a numerical value that measures the deviation from normality. In this case, the test statistic is 0.4462.</p><p>The <strong>p-value</strong> is a measure of evidence against the null hypothesis, which states that the data is normally distributed. A lower p-value indicates stronger evidence against the null hypothesis, suggesting that the data significantly deviates from a normal distribution. In this case, the p-value is 0.0000, which is less than any conventional significance level (e.g., 0.05).</p><p>Therefore, based on the results of the Shapiro-Wilk test, we can conclude that the funding amount data for FinTech, Retail, EdTech, Tech, E-commerce, Automotive, Financial Service and Hospitality sector do not follow a normal distribution. They have extremely low p-value suggesting a significant departure from normality, indicating that the distributions are not normally distributed.</p><p>The p-value for Food delivery is 0.0589 which is greater than the significant value of 0.05, indicating that data significantly does not deviate from a normal distribution. We therefore conclude that the distribution for Food delivery is normally distributed.</p><p>In the case where a sector has fewer than 3 data points, such as the “Multinational conglomerate company” sector, it is not possible to perform a meaningful statistical test for normality. It is important to acknowledge the limitation due to insufficient data points. This indicates that further analysis or interpretation of normality for that specific sector is not feasible with the available data.</p><p>However, we still performed visual inspection and explore descriptive statistics (e.g., mean, median, skewness) to gain insights into the distribution of funding amounts for the “Multinational conglomerate company” sector.</p><p><strong>Equal Variance Test using Levene’s test to test for equal variance across different sectors</strong></p><p><strong>Levene’s test</strong> for equal variance is a statistical test used to determine if the variances of two or more groups are equal. It is used when the assumption of equal variances (homogeneity of variances) needs to be checked, typically in the context of analysis of variance (ANOVA) or other parametric tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*WV2VQKuwM85dC_YlLp9tJA.png" /></figure><p>The <strong>test statistic</strong> measures the magnitude of the difference in variances among the sectors which is 0.6689.</p><p>The <strong>p-value</strong> is a measure of evidence against the null hypothesis, which states that the variances across the sectors are equal. A higher p-value suggests weak evidence against the null hypothesis, indicating that the differences in variances among the sectors are not statistically significant.</p><p>The p-value is 0.7376, which is greater than the typical significance level of 0.05. Therefore, we fail to reject the null hypothesis and conclude that there is no significant difference in the variances of funding amounts across the top 10 sectors. This supports the assumption of equal variance among the sectors.</p><p>If the normality assumption is not met, but the assumption of equal variance is met, you can use the Kruskal-Wallis test instead of ANOVA.</p><p>The Kruskal-Wallis test is a non-parametric alternative to ANOVA and is appropriate when the data do not meet the assumption of normality.</p><p><strong>Kruskal-Wallis test</strong></p><p>The Kruskal-Wallis test assesses whether there are significant differences in the medians of the groups being compared, without assuming a specific distribution. It is robust to violations of the normality assumption and can be used when the data are skewed or have outliers.</p><p>The Kruskal-Wallis test compares the medians of the groups rather than the means. It is a non-parametric test that does not assume a specific distribution of the data, making it suitable for situations where the data may not follow a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*2MajB1hPQbJ_9IoUaaCeYg.png" /></figure><p>The result of the test statistic is 30.0738 which measures the magnitude of the differences in the medians of the funding amounts among the sectors. The p-value is 0.0004, which is less than the typical significance level of 0.05. Therefore, we reject the null hypothesis and conclude that there are significant differences in the medians of the funding amounts among the top 10 sectors.</p><p><strong>Conclusion</strong></p><p>The results of the Kruskal-Wallis test indicate that there is statistical evidence to suggest significant differences in the funding amounts across the top 10 sectors.</p><p>To access the full code,you can check out my <a href="https://github.com/KodwoAmissah/Indian-startup-market-LP1-project-/blob/main/Code/Notebooks/project.ipynb">Github repository.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1129cf69d60b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>