<?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 Phonex Chemutai on Medium]]></title>
        <description><![CDATA[Stories by Phonex Chemutai on Medium]]></description>
        <link>https://medium.com/@phinmaiyo?source=rss-64101df3f334------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lL5310bR3IOrQT3N</url>
            <title>Stories by Phonex Chemutai on Medium</title>
            <link>https://medium.com/@phinmaiyo?source=rss-64101df3f334------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:01:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@phinmaiyo/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[Machine Learning Model Deployment with FastAPI and Docker]]></title>
            <link>https://medium.com/@phinmaiyo/machine-learning-model-deployment-with-fastapi-and-docker-5e5fef8a2dd9?source=rss-64101df3f334------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e5fef8a2dd9</guid>
            <dc:creator><![CDATA[Phonex Chemutai]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 12:04:59 GMT</pubDate>
            <atom:updated>2024-01-10T15:21:52.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-DrgDjxh45DLlKrXJKUtEg.png" /></figure><p>Machine learning model deployment is a crucial step in making your ML models accessible to users and applications. FastAPI, a modern Python web framework, and Docker, a containerization platform, have gained popularity for their efficiency and simplicity in deploying machine learning models.</p><p>Mostly, the real use of your ML model lies at the heart of an intelligent product — that may be a small component of a recommender system or an intelligent chat-bot. These seem very difficult to overcome as the majority of ML practitioners use R/Python for their experiments whilst consumers of those ML models would be software engineers who use a completely different technology stack.</p><p>This problem can be easily solved with building of APIs. Web APIs have made it easy for cross-language applications to work well. If a frontend developer needs to use your ML Model to create an ML powered web application, they would just need to get the URL Endpoint from where the API is being served.</p><p>In this tutorial, we’ll walk through the process of deploying a machine learning model using FastAPI and Docker, making it accessible via a RESTful API.</p><h3>Prerequisites</h3><p>Before we begin, ensure you have the following:</p><ol><li>Python and pip installed on your system.</li><li>Basic understanding of machine learning and Python.</li><li>Docker installed on your system. You can download it from the official website: [Docker official website](https://www.docker.com/get-started)</li></ol><h3>Create a Machine Learning Model</h3><p>For this tutorial, we’ll use a simple scikit-learn model to classify sepsis, which is a serious condition in which the body responds improperly to an infection. You can replace it with your own trained model.</p><ol><li>Create a pipeline with a preprocessor and a model(e.g., xgb_pipeline), fit the pipeline on the training data and save the pipeline:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*11jbYIeEtss2_NUdvS7W4w.png" /></figure><h3>Create a FastAPI App</h3><p>Now, let’s create a FastAPI app that serves the machine learning model as a RESTful API.</p><ol><li>Create a virtual environment (venv) and Install the requirements.txt with fastapi and uvicorn libraries</li><li>Create a FastAPI app script (e.g., main.py) and define the API:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*DMu1nVbBgaZts6OJp8xPmA.png" /></figure><p>3. Define a sepsis features class using Pydantic&#39;s <em>BaseModel</em> for handling data validation and two endpoints (<em>/</em> and <em>/info</em>) for your Sepsis Analysis API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*9Om0O4jqqmcCXp1WhWNByQ.png" /></figure><p>4. Set up a prediction endpoint (/predict_sepsis) for your Sepsis Analysis API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*0DG0NobSDEPw7u--uL4NlA.png" /></figure><h3>Build and Run the Docker Container</h3><p>With the Dockerfile in place, you can now build and run the Docker container.</p><ol><li>Create a Docker file:</li></ol><p>This Dockerfile contains instructions to build a Docker image that sets up an environment to run your FastAPI application.</p><p>Make sure the requirements.txt file exists in your project directory and contains the necessary Python dependencies for your FastAPI application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*Mxvs7MpcUTcdELeYdhWB-w.png" /></figure><p>2. Build and Run the Docker Container</p><p>With the Dockerfile in place, you can now build and run the Docker container.</p><ol><li>Build the Docker image:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*K3Qas-SX8yuqlU6aQjMCYA.png" /></figure><p>2. Run the Docker container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*LW9jqRAIdUbi0Z6b73N85g.png" /></figure><h3>Test the API</h3><p>Your FastAPI app is now running in a Docker container. You can test it by making POST requests to the /predict/ endpoint:</p><pre>curl -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{&quot;PRG&quot;: 10, &quot;PL&quot;: 20, &quot;PR&quot;: 30, &quot;SK&quot;: 40, &quot;TS&quot;: 50, &quot;M11&quot;: 1.5, &quot;BD2&quot;: 3.2, &quot;Age&quot;: 45, &quot;Insurance&quot;: 1}&#39; http://localhost:8000/predict_sepsis</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*NYjERfxpYSoEbXxkrdcgVA.png" /></figure><h3>Conclusion</h3><p>You’ve effectively implemented a machine learning model through FastAPI and Docker, establishing a RESTful API accessible from any location. This method enables seamless scaling of your machine learning model deployment, facilitating integration into diverse applications and services. Take your project further by improving your FastAPI application, incorporating authentication mechanisms, and optimizing your Docker container to ensure suitability for production environments.</p><p>[Read more in my notebook](<a href="https://github.com/phinmaiyo/Embedding-Machine-Learning-Model-into-Web-Application">https://github.com/phinmaiyo/Embedding-Machine-Learning-Model-into-Web-Application</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e5fef8a2dd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Fine-Tune an NLP Classification Model with HuggingFace]]></title>
            <link>https://medium.com/@phinmaiyo/how-to-fine-tune-an-nlp-classification-model-with-huggingface-de632ff6f8a7?source=rss-64101df3f334------2</link>
            <guid isPermaLink="false">https://medium.com/p/de632ff6f8a7</guid>
            <dc:creator><![CDATA[Phonex Chemutai]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 20:03:24 GMT</pubDate>
            <atom:updated>2023-11-12T20:05:24.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*Czm5p-8MUP2dQyEPM79pMg.png" /></figure><p>This tutorial serves as a comprehensive guide for training a personalized Natural Language Processing (NLP) classification model using the transformers library by Hugging Face. The process initiates with the utilization of a pre-trained model, followed by fine-tuning through transfer learning techniques. The tutorial provides detailed steps for working with the Hugging Face transformers library, allowing users to adeptly create and enhance their NLP classification models.</p><h3>Classification Model</h3><p>For exhibition purposes, we will build a classification model trying to predict if a Twitter sentiment is either positive, negative, or neutral. Hugging Face is an open-source and platform provider of machine learning technologies. You can install their package to access some interesting pre-built models to use them directly or to fine-tune (retrain it on your dataset leveraging the prior knowledge coming with the first training), then host your trained models on the platform, so that you may use them later on other devices and apps.</p><p>The Hugging face models are Deep Learning based, so will need a lot of computational GPU power to train them. Please use <a href="https://colab.research.google.com/">Colab</a> to do it, or your other GPU cloud provider, or a local machine having NVIDIA GPU.</p><h3>Install the Required Libraries</h3><p>For this tutorial, you can download the following libraries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*z4UOXRL8YhRCxaM4RO_51g.png" /></figure><h3>Load the Data</h3><p>We have the train and test datasets stored as CSV files in Google Drive. Take note that HuggingFace requires the data to be a Dataset Dictionary.</p><p>I manually split the training set to have a training subset ( a dataset the model will learn on), and an evaluation subset ( a dataset the model with use to compute metric scores to help avoid some training problems like <a href="https://colab.research.google.com/corgiredirector?site=https%3A%2F%2Fwww.ibm.com%2Fcloud%2Flearn%2Foverfitting">the overfitting</a> one ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*2wlVmPV33Y5myx5LI2BE-g.png" /></figure><p>Next, we save the splitted subsets and load them as datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*jIRKv0WuxE3rHnfx2QNcLA.png" /></figure><p>We then prepare our data for training a machine learning model by converting text data into tokenized format and ensuring the labels are in a numerical format suitable for modeling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*qthCfjAX4iU1WSdwjbauBQ.png" /></figure><p>The ‘transform_labels’ function takes a dictionary with a ‘label’ key and maps the label to numerical values. The labels -1, 0, and 1 are mapped to 0, 1, and 2, respectively.</p><p>The ‘tokenize_data’ function then tokenizes the ‘safe_text’ column of each example using a tokenizer. It pads the sequences to a maximum length of 128. Additionally, it removes unnecessary columns (‘tweet_id’, ‘label’, ‘safe_text’, ‘agreement’).</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*qCOnoyVlLFPjH6nY0ViqWQ.png" /></figure><p>DatasetDict object containing training and evaluation datasets, each with features like ‘input_ids’, ‘attention_mask’, and ‘labels’.</p><p>* input_ids: These are tokenized input sequences converted to IDs, ready for model input.</p><p>* attention_mask: This is a binary mask that indicates which tokens the model should pay attention to (usually 1 for tokens, 0 for padding).</p><p>* labels: These are the target labels for the text classification task.</p><h3>Fine Tune the Model</h3><p>In this problem, we will fine-tune the sentiment analysis model called “<em>cardiffnlp/twitter-roberta-base-sentiment</em>”. This model is based on RoBERTa, a variant of the BERT architecture, and has been fine-tuned for sentiment analysis on Twitter data by the Cardiff NLP research group. This model is specifically fine-tuned for sentiment analysis on Twitter data, so it should perform well on tweets or similar short-form text. The sentiment labels for our dataset are 0 (Negative),1 (Neutral), or 2 (Positive).</p><p>we start by loading the model using the Hugging Face Transformers library in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*afj8PtHXz6qDecwRrz0v7Q.png" /></figure><p>we then instantiate the train and validation datasets as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*evxYJO4-5TQNT_wMDL0mbg.png" /></figure><p>The ‘<em>shuffle</em>’ method is used to shuffle the examples within the training and validation sets. The ‘<em>seed</em>’ parameter is set to 10, ensuring reproducibility if you need to recreate the same shuffled datasets.</p><p><strong>Training arguments</strong></p><p>We then configure the training arguments for our model using the Hugging Face Transformers library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*KtNxk_VefoMpJcYSPfY6pQ.png" /></figure><p>These arguments provide a good starting point for training the model.</p><p><strong>Pad Sequences</strong></p><p>Since we are working with a sequence-based model that requires input sequences to be of the same length within a batch, we implement a ‘<em>DataCollatorWithPadding’, </em>which is a class from the Hugging Face Transformers library that helps collate and pad sequences in a dataset.</p><pre>data_collator = DataCollatorWithPadding(tokenizer=tokenizer,padding =&#39;max_length&#39;, max_length=128, return_tensors=&#39;pt&#39;)</pre><p>It handles input sequences of varying lengths and efficiently batch them together. In natural language processing (NLP) tasks, input text sequences often have varying lengths. However, neural networks typically require fixed-length input sequences. By using ‘<em>DataCollatorWithPadding’</em>, we ensure that our input sequences are appropriately padded, making them compatible with transformer-based models and improving the overall training efficiency.</p><p><strong>Define a custom trainer</strong></p><p>We then define a custom trainer by subclassing the ‘<em>Trainer’</em> class and overriding the ‘<em>compute_loss</em>’ method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*bpD_LBZOAFY6bMndvGPOsA.png" /></figure><p>While the default trainers provided by Hugging Face are powerful and cover many use cases, defining a custom trainer becomes essential as we need to extend or modify the training process to suit the specific needs of the problem.</p><p>The function retrieves the labels from the input batch and performs a forward pass through the model using the provided inputs. The <em>loss_function </em>defines a custom loss function using cross-entropy loss with class weights and the loss is computed by applying the custom loss function to the logits and labels.</p><p>we use the <em>nn.CrossEntropyLoss </em>with class weights as we are dealing with an imbalanced dataset where some classes have significantly fewer examples than others, and the model may become biased toward the majority class.</p><p><strong>Instantiate the trainer</strong></p><p>Since the arguments and the compute loss function are set up, we define the evaluation metric and instantiate the trainer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*K02GfSDmPgOMxSiRdgX-Og.png" /></figure><p>This configuration sets up the custom_trainer with the necessary components for training our model.</p><h3>Train the model</h3><p>The last step is to train the model using the “train” method.</p><pre>custom_trainer.train()</pre><p>This will initiate the training loop using the Roberta model, training and evaluation datasets, and training arguments. The CustomTrainer will handle the training process, including loss computation, parameter updates, and evaluation.</p><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*3n4DtiYRSpWszaMtL2__7g.png" /></figure><p>To evaluate the trained model on the provided evaluation dataset we use the “evaluate” method.</p><pre>custom_trainer.evaluate()</pre><p>This method computes various evaluation metrics based on the predictions of the model on the evaluation dataset. In this case, we are using the accuracy metric to evaluate the performance of the model.</p><h4>output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*7Ejo6FJQK4iCQMey5pSjyw.png" /></figure><p>Represents the average loss computed on the evaluation dataset. It measures how well the model is performing in terms of minimizing the difference between predicted and actual labels. Lower values indicate better performance. An accuracy of 0.771 means that approximately 77.1% of the instances were predicted correctly.</p><h3>Model Improvement</h3><p>To improve the accuracy of the model, several strategies can be implemented such as Fine-Tuning Hyperparameters. This involves experimenting with different hyperparameter settings such as learning rate, batch size, and the number of training epochs. Alternatively, consider trying different model architectures or variations. For example, you could experiment with larger or smaller versions of your current model, or try a different pre-trained model from the Hugging Face model hub.</p><h3>Push the Model</h3><p>The last step is to push your fine-tuned model and tokenizer to the Hugging Face Model Hub.</p><pre>custom_trainer.push_to_hub<br>tokenizer.push_to_hub( &quot;roberta_fine_tuned_sentiment&quot;)</pre><h3>Conclusion</h3><p>In conclusion, training a custom sentiment analysis model using transformers and fine-tuning techniques with Hugging Face’s library provides a powerful framework for creating models tailored to specific tasks. The process involves leveraging pre-trained transformer models, adapting them to domain-specific data, and optimizing performance through hyperparameter tuning.</p><p>Here is the link to the hugging face space where the pre-trained model is hosted: <a href="https://huggingface.co/spaces/phinm/pretrained_sentiment_Roberta">https://huggingface.co/spaces/phinm/pretrained_sentiment_Roberta</a></p><p>Appreciation</p><p>I highly recommend Azubi Africa for its comprehensive and effective programs. Read More articles at <a href="https://medium.com/@azubiafrica">https://medium.com/@azubiafrica</a> and take a few minutes to visit this link to learn more about Azubi Africa’s life-changing programs.</p><p><a href="https://bit.ly/41CGCwK">https://bit.ly/41CGCwK</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de632ff6f8a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy a Machine Learning Model using Streamlit]]></title>
            <link>https://medium.com/@phinmaiyo/how-to-deploy-a-machine-learning-model-using-streamlit-d0b0b9d28e37?source=rss-64101df3f334------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0b0b9d28e37</guid>
            <dc:creator><![CDATA[Phonex Chemutai]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 15:12:48 GMT</pubDate>
            <atom:updated>2023-10-15T20:21:19.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ADMwfS9PqjQ_8w8LP5R-xA.png" /></figure><p>If you’re a data scientist or machine learning enthusiast looking to take your models from the development phase to real-world deployment as user-friendly web applications, you’ve landed in the right spot. This article is your guide to understanding model deployment and, specifically, how to deploy machine learning or deep learning models using Streamlit.</p><h3>Article Overview:</h3><ol><li>Grasp the Essence of Model Deployment.</li><li>Dive into Model Deployment with Streamlit for a Dog Breed Classifier.</li></ol><p>Once your model is trained and ready, you have several avenues for deploying it on the web. Common choices include Flask, Django, and Streamlit. While Flask and Django offer powerful capabilities, they can be quite heavyweight and may require extensive learning. In this article, our focus is on Streamlit, and here’s why it’s a compelling choice.</p><h3>Why Opt for Streamlit?</h3><p>Streamlit empowers you to develop applications for your machine-learning projects with minimal coding effort.</p><p>It features hot-reloading, ensuring your app updates in real time as you make edits and save your files.</p><p>No need to write a backend, No need to define different routes, or handle HTTP requests.</p><p>More information can be found on their website — — –https://www.streamlit.io/.</p><p>So, if you’re keen on making your machine learning models accessible through user-friendly web apps, Streamlit is your gateway. Let’s get started!</p><h3>Prerequisites</h3><p>For you to build an effective machine learning web app, the following are the requirements:</p><ol><li>Familiarity with Python</li><li>Basic Machine Learning Knowledge</li><li>Python Environment: Set up a Python environment using tools like virtual environments or conda to manage dependencies and avoid conflicts.</li><li>Installed Libraries: Make sure you have the required libraries, such as Gradio, Streamlit, pandas, and scikit-learn, installed in your Python environment.</li><li>Trained Machine Learning Model</li></ol><h3>Let’s Get Building</h3><p>You can check out the [GitHub repo for the project here](<a href="https://github.com/your-username/your-repo">https://github.com/phinmaiyo/</a>Streamlit_Project). Now I’ll take you through the project step by step.</p><p>The first step is to create a virtual environment and install packages in requirements.txt. Next, we export the trained model and the toolkit, which has the encoder and scaler components used to transform the dataset.</p><h3>Import the required packages</h3><p>Let’s import the required packages:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*L_hNmWgrF8xhuMxSTXvvzw.png" /></figure><h3><strong>Design the User Interface</strong></h3><ol><li>We load the model and the toolkit.</li><li>Load dataset for users to preview.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*-kLF2ciGVwOvTNuREFrWng.png" /></figure><p>3. Add a title to the app and modify the font style.</p><p>4. Define app sections</p><p>5. Add and design a sidebar to define the purpose of the app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*2zuzl2vlDuTQs6fMGvc1dQ.png" /></figure><p>6. Create user input widgets and create a DataFrame for the inputs.</p><p>7. Create a submit button such that when clicked, it displays the user inputs in a DataFrame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*4pVa3nmZpmTuxhrJfIejxw.png" /></figure><p>8. Transform the user inputs and make a prediction for sales using the model we loaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*mcN7ssRzdjd1aaSp4NXKww.png" /></figure><p>The web app looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpkulOVWUyo8bA7XQ4PKjQ.png" /></figure><p>That’s all! We have successfully deployed a machine-learning model as a Streamlit app.</p><h3>Important resources</h3><p><a href="https://docs.streamlit.io/library/api-reference/widgets">Input widgets - Streamlit Docs</a></p><h3>Summary</h3><p>Streamlit is like the magical wand of the data science world. It’s the superhero cape you put on your Python scripts to transform them into dynamic and interactive web apps.</p><p>With Streamlit, you can turn your boring scripts into web apps faster than you can say “abracadabra.” It’s so simple, even your pet hamster could use it (well, maybe not, but you get the point). You just write your Python code, and Streamlit handles the rest, creating a user-friendly interface for your data-driven sorcery.</p><p>So, whether you’re a data scientist, a machine learning maestro, or just someone who loves to play with data, Streamlit is your trusty sidekick, ready to turn your code into interactive adventures. It’s like coding with a sprinkle of fairy dust — making data exploration a magical experience! 🧙✨📊🔮</p><h3>Appreciation</h3><p>Sincere appreciation to</p><p><a href="https://medium.com/u/7754e3e008bb?source=post_page-----d3745e63e6--------------------------------">Azubi Africa</a></p><p>through their program <a href="https://bit.ly/3ARq742">Azubi Data Science</a> for the valuable skills I have acquired. Spare a few minutes and check out Azubi Africa and learn about their <a href="https://bit.ly/41CGCwK">programs</a>.</p><h3>My socials</h3><p>[LinkedIn](<a href="https://www.linkedin.com/in/phonex-chemutai/">https://www.linkedin.com/in/phonex-chemutai/</a>)</p><p>[GitHub](<a href="https://github.com/phinmaiyo/Gradio_Project">https://github.com/phinmaiyo</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0b0b9d28e37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a GUI Using Gradio for Machine Learning Models]]></title>
            <link>https://medium.com/@phinmaiyo/how-to-build-a-gui-using-gradio-for-machine-learning-models-7d8bcb341d6e?source=rss-64101df3f334------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d8bcb341d6e</guid>
            <dc:creator><![CDATA[Phonex Chemutai]]></dc:creator>
            <pubDate>Sun, 15 Oct 2023 12:13:59 GMT</pubDate>
            <atom:updated>2023-10-15T20:19:58.965Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*NKahx9qPv8_m_-98P9J5TQ.png" /></figure><p>Have you ever crafted a nifty Machine Learning model and thought, “Wow, this is cool, but how do I flaunt its coolness to the world?”</p><p>Model deployment, often lurking in the shadow of ML, is the unsung hero of showcasing your algorithmic marvels.</p><p>Now, in this enlightening piece, I’ll unveil a secret weapon, a new-fangled tool that transforms your ML creation into a splendid web app. Share your wizardry with fellow devs, and watch their faces light up as they interact with your model. It’s like showing off your prized pet unicorn, but in the digital realm. So, fasten your seatbelts and prepare for a journey through the land of model deployment! 🚀✨</p><p>I will be building a simple supervised model using scikit-learn. But what makes this adventure truly epic is our secret weapon, Gradio, the innovative tool I mentioned earlier. With Gradio, we’ll conjure up a captivating graphical interface for our model.</p><p>What is Gradio?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*xUwhgA2365slca9oTP0nsA.png" /></figure><p>Well, before embarking on this adventure, lets understand what gradio is.</p><p>According to <a href="https://www.gradio.app/">https://www.gradio.app/</a></p><p>Gradio is the fastest way to demo your machine learning model with a friendly web interface so that anyone can use it, anywhere!</p><p>Gradio is like the Gandalf of machine learning tools — it’s a wizard that transforms your models into interactive web applications.</p><p>With Gradio, you can create intuitive user interfaces for your machine learning models without needing extensive web development skills. It’s like giving your models a user-friendly front door, allowing users to interact with them, input their data, and receive predictions or results, all within a web application.</p><p>So, in a nutshell, Gradio is the enchanting bridge between your models and the real world.</p><p>Now that we understand what Gradio is, let’s get into the project.</p><h3>Pre-requisite</h3><p>For you to successfully work through this tutorial, you’ll need to have Python installed in your machine.</p><h3>Let’s Get Building</h3><p>You can check out the [GitHub repo for the project here](<a href="https://github.com/your-username/your-repo">https://github.com/phinmaiyo/</a>Gradio_Project). Also, check out the notebook inside the repo where we load, split, transform, instantiate and train the model. Now I’ll take you through the project step by step.</p><h3>Import the Packages</h3><p>We are going to import the required packages like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*MhkQI88Yvb4ZcbBU_pLHyw.png" /></figure><h3>Create the function for Gradio</h3><p>Let’s create a function that forms the heart of our Gradio application. Gradio operates by connecting its graphical user interface to a Python function. This function serves as the link between the user and the machine learning model. It’s the conductor of the orchestra, facilitating the flow of data from the user to the model and back.</p><p>The function we’re about to craft takes in the features of the dataset our model was trained on, processes user inputs, passes them as an array to the model for prediction, and then returns the prediction result. This is where the magic happens. Gradio builds its graphical user interface components based on this function.</p><p>Think of it like a relay race: Gradio starts the race by collecting user inputs, hands off the baton (your data) to the function, and watches as the function guides it to the model. The model does its thing and hands the result back to the function, which, in turn, hands it back to Gradio for presentation to the user.</p><p>Now, let’s craft this function to make our Gradio web app come to life! 🚀✨</p><p>First, we define a function to load a pipeline, import the model, load the trained model with joblib, and instantiate the pipeline, scaler, and encoder objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*9poY1efMF_sYd5VNb89g4w.png" /></figure><p>Next, we craft the function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*icuuJOzr1Ot4hRkgB-sTdg.png" /></figure><p>In the code above we passed the pipeline, model, and transformers from our data as arguments into a function which we named <em>predict_customer_attrition</em>. Then we converted the inputs into a DataFrame which we then passed onto our model for prediction. Finally, we returned the predicted result of our model.</p><h3>Create our Gradio Interface</h3><p>Now we are going to create our Web App interface using Gradio:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*iDE1reFS1sdiOXzI6G97Ug.png" /></figure><p>In the code above we define our input components using instances of various classes or functions from the Gradio library. Users of the Gradio application will see the instances of input components in the interface, and they can select their choices from the provided options. The default value set can be changed by users by interacting with the components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*_5pTGeXoAWVNgEqi2hbW5g.png" /></figure><p>The inputs represent the feature columns that are present in our dataset — the same feature column names we passed into our <em>predict_customer_attrition</em> function.</p><p>Then we instantiated the Gradio interface object and passed in our earlier <em>predict_customer_attrition</em> function. Then we generated our Inputs GUI component and told radio the inputs to expect.</p><p>Then we created a variable named outputs which holds the GUI component for our model result. The result of our model’s prediction will be outputted in a text box.</p><p>Finally, we passed in the description of our web app into the description parameter.</p><h3>Launch the Gradio Web App</h3><p>Now we’re going to Launch our Gradio web app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*3S_WcWTxvuS3YkjixWurBg.png" /></figure><p><strong>NOTE:</strong> If you are launching the Gradio app as a script from that e command line, you will be given a local host link which you will then copy and paste into your browser to see your web app.</p><p>If you are launching the app from a Jupyter notebook, you will see a live preview of the app as you run the cell (and you will also be provided with a link).</p><p>“The ‘share=True’ parameter in Gradio is like a magical link that gives your web app a .gradio extension. It’s like Cinderella’s carriage, but with a curfew. This link works, but only for 72 hours, and there’s a catch — it depends on your computer. Yes, your computer has to stay awake for the party to continue. Once it takes a nap, the link turns into a ‘500’ error — not very magical!</p><p>But here’s the plot twist: Gradio offers a way to be the fairy godparent of your app. You can make it permanent, like turning a pumpkin into a carriage forever. The most interesting part is that its free; you’ll need to run `gradio deploy` from Terminal to deploy to Spaces (<a href="https://huggingface.co/spaces">https://huggingface.co/spaces</a>). This way, your app can dance the night away, even if you’re broke like the author (glass slippers not included).” 😄👠🎃</p><h3>Important resources</h3><ul><li><a href="https://gradio.app/">Gradio Website</a></li><li><a href="https://gradio.app/docs">Gradio Documentation</a></li><li><a href="https://github.com/gradio-app/gradio">Gradio on GitHub</a></li></ul><h3>Summary</h3><p>In a nutshell, Gradio is an incredibly handy library that tackles a common challenge in the world of Machine Learning: deploying models.</p><p>Believe it or not, a whopping 90% of ML models never see the light of day, and Gradio aims to change that. It’s a fantastic platform that’s not just for seasoned pros but also for newcomers to strut their model’s stuff and put them to the test in real-world scenarios.</p><p>If you haven’t already, definitely give the Gradio Library a whirl. It’s a game-changer! 😉🚀</p><h3>Appreciation</h3><p>Sincere appreciation to</p><p><a href="https://medium.com/u/7754e3e008bb?source=post_page-----d3745e63e6--------------------------------">Azubi Africa</a></p><p>through their program <a href="https://bit.ly/3ARq742">Azubi Data Science</a> for the valuable skills I have acquired. Spare a few minutes and check out Azubi Africa and learn about their <a href="https://bit.ly/41CGCwK">programs</a>.</p><h3>My socials</h3><p>[LinkedIn](<a href="https://www.linkedin.com/in/phonex-chemutai/">https://www.linkedin.com/in/phonex-chemutai/</a>)</p><p>[GitHub](<a href="https://github.com/phinmaiyo/Gradio_Project">https://github.com/phinmaiyo/Gradio_Project</a>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d8bcb341d6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis of External Factors that Impact Sales of a Retail Store- A Regression Analysis]]></title>
            <link>https://medium.com/@phinmaiyo/analysis-of-external-factors-that-impact-sales-of-a-retail-store-a-regression-analysis-f7445bbf3e86?source=rss-64101df3f334------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7445bbf3e86</guid>
            <dc:creator><![CDATA[Phonex Chemutai]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 23:27:34 GMT</pubDate>
            <atom:updated>2023-09-17T23:27:34.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*APFVXeFttawXBKEU3Q0Sng.png" /></figure><p><strong>Introduction</strong></p><p>In the highly competitive landscape of the retail industry, understanding the multifaceted dynamics that influence sales performance is essential for strategic decision-making. External factors, ranging from economic indicators and seasonal trends to marketing efforts and competitive influences, play a pivotal role in shaping a retail store’s sales trajectory. Through a comprehensive regression analysis, this study aims to delve into the intricate relationships between these external variables and sales outcomes. By quantifying the impact of these factors, retailers can glean actionable insights to optimize operations, tailor marketing strategies, and ultimately enhance their revenue-generation potential.</p><ol><li><strong>Business Understanding</strong></li></ol><p>The problem at hand pertains to comprehensively investigating the external factors that have a bearing on the sales performance of retail stores. While existing research acknowledges the significance of various factors such as economic indicators, seasonal trends, and marketing strategies, there remains a gap in terms of a comprehensive and up-to-date analysis that quantifies the individual and collective impacts of these factors. This study aims to bridge this gap by conducting a rigorous regression analysis, thus providing a more nuanced understanding of the interplay between external variables and sales outcomes. The ultimate goal is to offer retailers actionable insights that can drive informed decision-making, optimize resource allocation, and enhance overall sales effectiveness in a competitive retail environment.</p><p><strong>Objective</strong></p><p>The objective of this study is to investigate how external factors such as holiday events, oil prices, public sector wages, and natural occurrences, impact the sales of Corporation Favorita, a large Ecuadorian-based grocery retailer.</p><p><strong>Hypothesis</strong></p><p>Hypothesis testing is a statistical method used to draw conclusions or make inferences about a larger population or dataset based on the analysis of a sample.</p><p><strong>Null Hypothesis: </strong>Promotions have no significant effect on product sales.</p><p><strong>Alternate Hypothesis: </strong>Promotions positively impact product sales, leading to increased sales during promotional periods.</p><p><strong>Questions</strong></p><p>The questions below are to be answered to understand the data.</p><p>1. Is the train dataset complete (has all the required dates)?</p><p>2. Which dates have the lowest and highest sales for each year?</p><p>3. Did the earthquake impact sales?</p><p>4. Are certain groups of stores selling more products? (Cluster, city, state, type)</p><p>5. Are sales affected by promotions, oil prices and holidays?</p><p>6. What analysis can we get from the date and its extractable features?</p><p>7. What is the difference between RMSLE, RMSE, MSE (or why is the MAE greater than all of them?)</p><p>Other Questions</p><p>The study seeks to answer the following key questions</p><p>1. What is the effect of seasonal variations (e.g., Monthly, or quarterly patterns) on total sales?</p><p>2. What store is the highest performer in terms of sales?</p><p>3. What are the best-selling products per location?</p><p>4. Does store size affect total sales?</p><p>5. Which days have the most sales?</p><p>By answering these questions Retailers, including Corporation Favorita can glean actionable insights to optimize operations, tailor marketing strategies, and ultimately enhance their revenue-generation potential.</p><p><strong>2. DATA UNDERSTANDING</strong></p><p>The datasets for this project are in a CSV format and include train and test datasets, as well as stores, holidays, transactions, and oil prices datasets. sales are shaped by external factors, ranging from economic indicators and seasonal trends to marketing efforts and competitive influences.<strong> </strong>Ecuador is an oil-dependent country and its economic health is highly vulnerable to shocks in oil prices. Hence, I analyze the trend of sales with respect to oil prices and test their correlation.</p><p>Holidays can have a significant impact on sales for businesses in various industries. The impact of holidays on sales can be both positive and negative, depending on several factors. Holidays can affect sales through:</p><ol><li>Increased Sales:</li></ol><ul><li>Seasonal Demand: Many holidays are associated with increased consumer spending, such as Christmas, Valentine’s Day, Thanksgiving, and back-to-school shopping. Businesses that offer products or services related to these holidays often experience a boost in sales during these periods.</li><li>Promotions and Discounts: Retailers often run special promotions and discounts during holidays to attract customers. This can lead to increased sales as consumers take advantage of these deals.</li></ul><p>2. Consumer Behavior:</p><ul><li>Gift-Giving: Holidays like Christmas, birthdays, and anniversaries often involve gift-giving, leading to higher sales in the retail sector, particularly for gift shops, online marketplaces, and brick-and-mortar stores.</li><li>Travel and Leisure: Holidays like summer vacations or long weekends can boost sales for businesses in the travel and hospitality industry, including hotels, airlines, and restaurants.</li><li>The holiday dataset is comprised of columns containing the type of holiday and whether it is local, regional or national.</li></ul><p><strong>3. DATA PREPARATION</strong></p><p>The importation of libraries is an essential step before beginning an analysis.</p><p><strong>3.1: Python Libraries</strong></p><p>These are the libraries that will be used for the analysis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*gwxxn3fzW6Ta07f_qi6CcQ.png" /></figure><p><strong>3.2: Data Loading</strong></p><p>This is how the holiday, oil, and stores datasets were retrieved from the SQL Server database. Train, test, and transaction datasets were downloaded and imported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*CesvNa-foeEt1dQamG01Bw.png" /></figure><p>upon examining the train and test datasets, most columns were deemed as relevant except for “id” which was dropped in all the datasets. Only the oil dataset had a few missing values. Below is the summary of train and test datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*TEuYe9b65TrVjI5BFzA4cQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*g8D17GZh0LfAtCx2HaO2iw.png" /></figure><p>it can be observed that the training dataset has a shape of (3000888, 6), while the testing dataset has a shape of (28512,5).</p><p><strong>Exploratory Data Analysis</strong></p><p>Here I examined the datasets in depth to gain insights, understand patterns, and identify anomalies within the time-ordered datasets.</p><p><strong>Checking ranges of dates</strong></p><p>to conduct exploratory analysis, it was deemed important to merge the datasets. Merging time series datasets by date involves combining two or more datasets based on a common date or time column. Hence, I checked the range of dates for each dataset to split them into train and test datasets. upon examining the datasets, the range of dates for transactions was only within the range of the training dataset, while holiday had only one date within the range of the test dataset, which was not significant to transfer all the attributes in the holiday columns to the test dataset. Thus these datasets were used for analysis to understand and provide actionable insights to optimize operations, tailor marketing strategies, and ultimately enhance sales revenue-generation potential. The date ranges are as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*ENB73-4nWXfUBTmp9aQSQA.png" /></figure><p>From the date ranges the range of the test dataset is 15 days after the train dataset.</p><p><strong>Merging Datasets</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*QSSU_ueUfLu8lS82n0oj2A.png" /></figure><p>After splitting the oil dataset as shown below, it was merged on both the train and test datasets.</p><p>Below is an image of both the train and test datasets after merging all the datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*386EydIjpU2nLoWvfOlzAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPv9gdG8TISI36PZ4F29dw.png" /></figure><p>it can be observed that the merging process created missing values in the datasets as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*gc9eNB0UABHIorT8JoogiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*TVWw47zp7YA1_U-AKWKXqA.png" /></figure><p>These missing values were handled in the data preprocessing stage.</p><p><strong>Sales Distribution</strong></p><p>KDE is a non-parametric way to estimate the probability density function of a continuous variable, in this case, the “sales” variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*F8Fh986p7fD6aveuDyVy0w.png" /></figure><p>The shape of the curve is unimodal (one peak) indicating a central tendency in sales, and the distribution is symmetric, skewed right (positively skewed) suggesting that the mean (average) is typically greater than the median (middle value when the data is ordered from smallest to largest). we can also observe that sales are most concentrated between 0 and 3000. The narrower curve suggests less variability in sales while the long tail suggests the presence of few extremely large values (outliers). Certain statistical tests and models assume normality, so skewed data might require transformation before analysis. In summary, a positively skewed distribution suggests that the data is not symmetrical and has a long right tail.</p><p><strong>Bivariate Analysis</strong></p><ol><li><strong>Is the train dataset complete (has all the required dates)?</strong></li></ol><p>Ensuring the completeness of dates is a fundamental step in preparing time series data for analysis. It helps maintain the reliability and accuracy of your analysis and ensures that you can trust the results and insights derived from your time series data.</p><p>Time series data is unique in that it has a temporal component. The order and spacing of timestamps matter. Incomplete data can disrupt the temporal consistency of your dataset.</p><p>Incomplete data can result in uneven or irregular time intervals between data points. Consistent frequency is important for many time series models, such as ARIMA, which assumes that data points occur at regular intervals.</p><p>Also, Seasonal patterns and trends may not be accurately captured if data is missing for specific time periods. This can lead to misinterpretation of the data and ineffective forecasting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*BXiPfg2qe6hvJdeueUpEOA.png" /></figure><p>Upon checking the missing dates, it was found that the train dataset was missing four dates, which is the 25th day of December from 2013 to 2016 and were concatenated into the train dataset as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*4Wbr5MTzRbGqYsjcCz35Lw.png" /></figure><p><strong>2. Which dates have the lowest and highest sales for each year?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*Hd2vLihkOFGPuogY0EoT3A.png" /></figure><p>Upon grouping the data by year and finding the date with the lowest and highest sales, The following conclusions were observed:</p><p>For the year 2013, the date with the lowest sales was January 1st, with sales amounting to 0.0 units. Conversely, the date with the highest sales was November 12th, with a substantial sales figure of 46,271.0 units. These findings provide insights into sales variation observed throughout the year, with a remarkable peak towards the end of the year.</p><p>In 2014, the observations were similar to those of 2013 with the lowest sales again falling on January 1st and the highest sales on December 8th reaching 45,361.0 units. This suggests seasonality in sales with peak sales observed towards the end of the year.</p><p>In 2015, the trend continued with the lowest sales observed on January 1st, amounting to 0.0 units, and the highest sales registered on December 14th totaling 40,351.0 units. This data strengthens the observation of increased sales during the latter part of the year, potentially associated with holiday shopping and year-end promotional activities.</p><p>The year 2016 exhibited a different trend. while the lowest sales remained consistent on January 1st, amounting to 0.0 units, the date with the highest sales shifted to May 2nd, recording an impressive 124,717.0 units. This significant increase in sales was about a week after 16 April 2016, 23:58 UTC when a powerful earthquake (7.8 M) struck the coast of Ecuador and people sought to get more supplies to ensure they were ready for any potential disruptions.</p><p>Finally, in 2017, the date with the lowest sales remained consistent on January 2nd, with 0.0 units. However, the year’s highest sales occurred on April 2nd, totaling 38,422.0 units. This particular year showed a different peak sales date compared to previous years. However, the variation could be a result of the data’s end date, which is on 2017 August 15th.</p><p><strong>3. Did the earthquake impact sales?</strong></p><p>The Ecuador earthquake that occurred in 2016 was a devastating natural disaster that struck the coastal region of Ecuador on April 16, 2016. The earthquake resulted in a significant loss of life and injuries. Hundreds of people were killed, and thousands were injured. Many buildings and infrastructure were damaged or destroyed, including homes, schools, and hospitals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*TIlcZKtZEggHnxnbrbf58Q.png" /><figcaption>Fig 1: Earthquake impact</figcaption></figure><p>From the visualization, the earthquake had a significant impact on sales. it is observed that there were spikes in sales after the earthquake, denoted by the red line, to a few months later after the earthquake. The high sales could be a response to the damage caused by the earthquake as people sought to get more supplies to ensure they were ready for any potential disruptions and also concerns about the availability of goods as earthquakes can disrupt supply chains and transportation networks.</p><p><strong>4. Are sales affected by promotions?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*dQa6QNQS17E3sqfTgRsIWA.png" /><figcaption>Fig 2: Sum of Sales by Year for Promoted and Non-Promoted Items</figcaption></figure><p>The visualization above shows that the grocery store makes more sales for items not on promotion compared to items on promotion. however, there is a consistent decline in sales figures for non-promoted items from 2013 to 2017 which could have been due to changes in market conditions, competition, customer preferences, or economic factors. For the promoted items sales figures increased from 2014 to 2015, before a consistent decline from 2015 to 2017. Hence, we can conclude that there is a decreasing trend in sales data.</p><p><strong>5. What are the best-selling products?</strong></p><p>The best selling products were extracted by grouping the data by sales and products and calculating the sum of sales. the results are as visualized below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*J_6Xoj31K3VZMJnif9Oueg.png" /><figcaption>Fig 3: Sum of Sales by Products</figcaption></figure><p>It is observed that the top 5 selling products are Grocery1, Bevarages, Produce, Cleaning and Dairy products. The store has sold Grocery1 items worth about $340,000,000.</p><p>6. <strong>Are certain groups of stores selling more products?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*kyMyyjqGw0n7CIxwYnRXNw.png" /></figure><p>The visualization shows that some stores are selling more products compared to others. The sales of most stores are below 30,000,000 while others, such as store 3, 44, and 45 are the highest performers and make sales of about $50,000,000, $62,000,000, and $55,000,000 respectively. The variation in sales could be influenced by the store’s location or other internal factors.</p><p><strong>7. Which days have the most sales?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*kmjtoBy_WlQwH30m5fO7CQ.png" /></figure><p>The store makes most sales during the weekend, that is Saturday and Sunday, with the highest sales observed on Sunday and the lowest sales observed on Thursday.</p><p><strong>8. which stores have the highest transactions?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*bQ1r4JoUQDHiMzAmK6zc-w.png" /></figure><p>The sum of transactions of most stores is below 3000000 with store 44 recording an impressive number of 7,250,000 transactions followed closely by store 47 with 6,600,000 transactions and stores 45 and 46. Store 3 also has a lower but substantial transaction figure of about 5,400,000. The analysis highlights variations in transactions across different stores that can inform strategic decision-making for retail store management. It assists in directing resources and efforts toward high-performing stores, thereby contributing to increased sales and overall profitability.</p><p>Checking for Trend, Seasonality, Irregularity and Cyclic Components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*Npb2gakn9thAPMveHlqJ7w.png" /></figure><p>There is no clear trend in the data, however, in 2014 and 2015 it was observed that there was an upward trend in sales. There is also a repeating pattern in sales at the end of each year where sales are relatively high. Hence, it is concluded that there is seasonality in the data. it is also observed that there are non-repeating patterns or random variations, particularly in 2016 and 2017, where sales were relatively high in the middle of the year. Hence, it is also concluded that there is irregularity in the data.</p><p><strong>Resampling</strong></p><p>Resampling involves changing the frequency or granularity of your time series data by aggregating it over different time intervals. This will allow deep analysis of the data. The data was resampled as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*iZyqoaqywaAs9HjviNKYDg.png" /></figure><p>upon looking at the monthly sales after resampling, it is observed that there is an upward trend in sales and seasonality, as sales peak at the end of each year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*5yJwR3oghFKZlt5rIsD_Cw.png" /></figure><p>There are also random variations or unexplained fluctuations in the data that cannot be attributed to any systematic pattern as seen in 2014 and 2016, hence, irregularity or random noise in the data.</p><p>Weekly sales also deduced interesting patterns as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*1QszUASHhoR4SptoBGkmgw.png" /></figure><p>A downward and upward variation in weekly sales is observed. Wages in the public sector are paid every two weeks on the 15th and on the last day of the month. Hence, the rising and declining pattern in sales could be affected by this.</p><p><strong>Sales and Transactions by Stores</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*SyhzXcM-rCjsmvfrXQ5qgQ.png" /></figure><p>Upon observation, there is a similar pattern in sales and transactions in most stores. however, looking at other stores, such as store 34, despite having higher transactions than most stores, its sales are slightly lower. a similar pattern is observed with store 38, where despite having transactions higher than its subsequent stores, its sales are lower than those stores. Store 48 also has higher transactions than store 49, but the sales of store 49 are higher than those of store 48. The analysis therefore shows variations in sales and transactions that the management could use to look at the factors contributing to lower sales in these stores despite having higher transactions.</p><p><strong>ARE CERTAIN GROUPS OF STORES SELLING MORE PRODUCTS? (CLUSTER, CITY, STATE, TYPE)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pPE2gCewavssZ3C5zEYhA.png" /></figure><p>The analysis of total sales based on different groupings reveals interesting insights into the performance of stores in various categories.</p><p>City Analysis: Among the cities, Quito is the top-performing city in terms of sales. Guayaquil follows with a substantial but lower total sales figure. This suggests that Quito and Guayaquil cities generate the highest revenues for the retail store.</p><p>Cluster Analysis: For the clusters(store size), Cluster 14 is the top-performing cluster in terms of revenue. Clusters 6, 8, 11, and 10 also perform well but slightly lower than 14. This analysis provides insights on variations in sales performance across different clusters, with no clear relationship between sales and cluster.</p><p>State Analysis: In regard to states, Pichincha is leading with the highest total sales, followed by Guayas with substantial but lower sales. This suggests that stores located in Pichincha and Guayas contribute significantly to the overall sales, reflecting the regional variations in sales performance.</p><p>Store Type Analysis: Among the store types, type A lead in total sales, indicating that they generate the highest revenue followed closely by type D. This suggests that type A and D generates the highest revenues for the retail store.</p><p>To sum it up, this analysis provides valuable insights that can inform strategic decision-making for retail store management. It assists in directing resources and efforts towards high-performing segments, thereby contributing to increased sales and overall profitability.</p><p><strong>Impact of oil prices on sales</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ba3_ma4dg6NEweSqtGdvyg.png" /></figure><p>The relationship between sales and oil prices is complex and can be influenced by various factors. Ecuador is an oil-dependent country and its economic health is highly vulnerable to shocks in oil prices. From the visualization, the relationship is not clear. hence, I tested the correlation between the two variables to determine the relationship.</p><p>Imputing Nan values in oil_prices</p><p>Since ‘oil_prices’ is a time series column, and considering the trend, it is appropriate to consider Time-Based Imputation to impute missing values based on the values at adjacent time points. This will involve using the previous or next available value, or even interpolating between nearby values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*dfVNbC57zJiOFmXO_Ai_4g.png" /></figure><p>Testing correlation of oil prices and sales</p><p>Null Hypothesis (H0): There is no correlation between sales and oil prices (ρ = 0).</p><p>Alternative Hypothesis (Ha): There is a correlation between sales and oil prices (ρ ≠ 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*6-lX4gWg3B-6ckqqiA6M_w.png" /></figure><p>Interpretation:</p><p>The p-value is less than the significance level (0.05), we conclude that there is a statistically significant correlation between sales and oil prices. The correlation coefficient (ρ) indicates the strength and direction of the correlation. a negative ρ indicates a negative correlation. -0.08 indicates a weak negative correlation. In this scenario, rising oil prices could lead to decreased consumer spending, as higher fuel costs can reduce disposable income.</p><p><strong>Impact of Holidays on Sales</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*ACpbblcHZLG6zGVB9DKTlQ.png" /></figure><p>From the visualization, holidays have an impact on sales, where holidays recorded high sales of $109,222,700. Event and Additional days, which are days added to a regular calendar holiday, for example, as typically happens around Christmas (making Christmas Eve a holiday) also recorded substantial but relatively low sales of $42,477,470 and $33,020,280 respectively.</p><p><strong>Hypothesis Testing</strong></p><p><strong>Null Hypothesis (H0): </strong>There is no correlation between sales and promotion (ρ = 0).</p><p><strong>Alternative Hypothesis (Ha): </strong>There is a correlation between sales and promotions (ρ ≠ 0).</p><p>The hypothesis was tested as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*gh1lduwR2Fw6MrlbtsWLpg.png" /></figure><p>Interpretation:</p><p>The p-value is less than the significance level (0.05), it is concludes that there is a statistically significant correlation between sales and promotions. The correlation coefficient (ρ) indicates the strength and direction of the correlation. a positive ρ indicates a positive correlation. 0.43 indicates a relatively strong correlation. In this scenario, Promotions positively impact product sales, leading to increased sales during promotional periods.</p><p><strong>Data Preprocessing</strong></p><p>Data preprocessing is a crucial step in the data analysis and machine learning pipeline. It involves cleaning, transforming, and organizing raw data into a format that is suitable for analysis or modeling.</p><p>At this stage, I first dropped columns that will not be used for training and set the date column to index since time series data is inherently ordered by time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*j7XKd6DJkKgSUoykrJ0vwA.png" /></figure><p><strong>Imputing Missing Values</strong></p><p>upon inspection of the attributes in columns having null values as shown below, it was observed that the columns in train had inconsistent attributes to those in the test dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*HeAQCMWQ3dA-UiVUnxfKtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*Sc37fgNiyXJ2nC7SuZJqLQ.png" /></figure><p>It was established that the inconsistencies would result in errors when predicting the test dataset. Hence, the columns with missing data were dropped except for oil prices that were imputed through interpolation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*em0vULIqffRO5DbQ6--OOg.png" /></figure><p>The final output after data preprocessing is as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*6iWxMAZwXXi2JYtQM3djcA.png" /></figure><p>The last step involved renaming the family column to the product as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*kWrl1C8MKYDBXjZa59NdYA.png" /></figure><p><strong>Feature Engineering</strong></p><p>Here we generate additional features that might improve the model’s performance. The date column was decomposed into year, month, and day and shown below since time series data is inherently ordered by time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*H0lZm94RUXfgP2us-qBEwg.png" /></figure><p><strong>Decomposition</strong></p><p>Time series decomposition is a statistical technique used to break down a time series into its underlying components. These components help us understand the various patterns and behaviors within a time series, making it easier to analyze, model, and forecast.</p><p>The primary components of a time series are typically:</p><p>1. Trend: The trend component represents the long-term movement or direction of the time series. It indicates whether the series is generally increasing, decreasing, or staying relatively stable over time. Removing the trend component helps isolate short-term fluctuations.</p><p>2. Seasonality: Seasonality refers to the repeating, predictable patterns or cycles in the time series that occur at fixed intervals. For example, retail sales might have a yearly seasonality pattern due to holiday shopping. Seasonality can occur at various frequencies, such as daily, weekly, monthly, or yearly.</p><p>3. Residual (or Error): The residual component, also known as the error term, represents the unexplained or random fluctuations in the time series after removing the trend and seasonality. It includes factors that are not accounted for by the trend and seasonality components.</p><p>Since the magnitude of seasonality remains roughly constant over time, and the variations around the trend are roughly constant we use Additive Decomposition where the original time series is represented as the sum of its components:</p><p>Original Time Series = Trend + Seasonality + Residual</p><p>Additive Decomposition and its visualization are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbwn6jLsPaoEvjT0m221qw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*NamjvK4UuACEs7XlGjICpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHhwA1GjNbJffTlZEQ1__w.png" /></figure><p>From the components plotted above, the trend of sales is clearly observed. The residuals show periods of high variability in sales.</p><p>1. Seasonal Component: although not clearly observed, it can be observed in the plot “Seasonal” that there are patterns that seem to be repeating over time. A further statistical test will be employed to confirm the seasonality of the sales.</p><p>2. Trend Component: The trend is clearly observed in the plot “Trend” with that line shows a gradual increase in sales over time.</p><p>3. Residual Component: Residuals are what remains in your data after the trend and seasonality have been removed. It represents the random noise or fluctuations as shown in the plot. They capture irregularities or deviations from the expected trend and seasonality.</p><p>The use of an additive model assumes that these components (trend, seasonality, and residuals) can be combined in a straightforward manner to recreate the original time series values (in this case, sales data). This assumption implies that the interactions between these components are linear, meaning their effects can be summed together to reproduce the observed data.</p><p><strong>Data Sampling</strong></p><p>The data points in the dataset are over 3 million and as I am limited by computational resources, I sampled and worked with only 40% as my current system cannot handle the entire dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*AtZDuOzUtAmPbka196MfnQ.png" /></figure><p>After sampling the 40% the shape of the train is as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*Lw8zP5OiHCQWjPGnhRdOoQ.png" /></figure><p><strong>Stationarity Testing</strong></p><p>The Kwiatkowski-Phillips-Schmidt-Shin (KPSS) test is a statistical test used in time series analysis to check the stationarity of a time series data set. Unlike the Augmented Dickey-Fuller (ADF) test, which tests for a unit root (non-stationarity), the KPSS test is designed to test for stationarity around a deterministic trend. In other words, it helps determine if a time series is stationary in levels (around a constant mean) or if it has a deterministic trend.</p><p>The KPSS test involves two hypotheses:</p><p>Null Hypothesis (H0): The null hypothesis of the KPSS test assumes that the time series is stationary around a deterministic trend. In other words, it assumes that the time series is stationary or trend-stationary.</p><p>Alternative Hypothesis (H1): The alternative hypothesis of the KPSS test assumes that the time series has a unit root or is non-stationary around a stochastic (random) trend. In other words, it assumes that the time series is non-stationary.</p><p>The test calculates a test statistic and compares it to critical values to determine whether to accept or reject the null hypothesis.</p><p>Below is the stationary test, KPSS and ADF results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Z3LOIuia1In2imoDon395Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*PJKGpJ6MnM0VzyjGVDPsKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*sze3nra6IIw7VDh98PG9Zw.png" /></figure><p>looking at the results of both the Kwiatkowski-Phillips-Schmidt-Shin (KPSS) and Augmented Dickey-Fuller (ADF) tests, we draw insights about the stationarity of the sales data. the test statistic of the ADF test is -73.476, which is remarkably low with a corresponding p-value of 0.000, below significance levels. Hence, we reject the null hypothesis that the sales time series contains a unit root, implying the sales series is weakly stationary, providing evidence of non-stationarity.</p><p>On the other hand, the KPSS test produced a test statistic of 1.885 and a p-value of 0.000, which is lower than the significance levels. Hence, we reject the null hypothesis, suggesting that the time series is not stationary around a deterministic trend and is constant, implying non-stationarity. In conclusion, both of these results suggest that the sales time series data exhibits evidence of non-stationarity.</p><p><strong>Differencing the Sales Series.</strong></p><p>Differencing is a technique used to transform a non-stationary time series into a stationary one.</p><p>Below is a visualization of the train data after performing a first-order differencing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUJhzbmGv369REKAWahZwQ.png" /></figure><p>The results of the differenced sales are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*8XVXtZhh5WEU6bLMPgRwNQ.png" /></figure><p>Another stationarity was conducted to check whether the series was stationary after differencing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*8H09qfilk1SeXkksfRfSZg.png" /></figure><p><strong>Autocorrelation Test</strong></p><p>The Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF) are important tools in time series analysis for understanding and modeling the relationships between observations at different time lags. These functions help analysts identify the order of autoregressive (AR) and moving average (MA) components in a time series model, which is essential for building accurate forecasting models.</p><p>Autocorrelation Function (ACF):</p><p>The ACF measures the correlation between a time series and its own lagged values.</p><p>It calculates the correlation coefficient between the time series at time “t” and the same series at various previous time points (lags).</p><p>The ACF is used to identify the order of the MA (moving average) component in a time series model.</p><p>In the ACF plot, significant spikes at specific lags indicate potential AR or MA orders.</p><p>Partial Autocorrelation Function (PACF):</p><p>The PACF measures the correlation between a time series and its own lagged values while controlling for the intermediate lags.</p><p>It helps identify the direct relationship between a data point at time “t” and its value at time “t-k,” where “k” is the lag.</p><p>The PACF is used to identify the order of the AR (autoregressive) component in a time series model. In the PACF plot, significant spikes at specific lags suggest potential AR orders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EX202CjbDRPyZOchkuiQtQ.png" /></figure><p>Both the ACF and PACF start with a lag of 0, which is the correlation of the time series with itself and therefore results in a correlation of 1.</p><p>The difference between ACF and PACF is the inclusion or exclusion of indirect correlations in the calculation.</p><p>Furthermore, you will see a blue area in the ACF and PACF plots, which depicts the 95% confidence interval and is in indicator for the significance threshold. That means, anything within the blue area is statistically close to zero and anything outside the blue area is statistically non-zero.</p><p>In the figures above we can see highly significant lags every 7 time periods. This indicates a 7-time period seasonal cycle in the data. The ACF is gradually declining with every 7th period and the PACF shows a 1 significant seasonal lag(1st). This suggests that the series is a seasonal-AR(1) process because the PACF has 1 significant lag.</p><p>Additionally, this series is also an ARMA process because the other lags of both ACF and PACF are geometrically declining</p><p><strong>Correlation Matrix</strong></p><p>A correlation matrix is a table that shows the correlation coefficients between many variables. Each cell in the table displays the correlation between two variables. Correlation coefficients quantify the strength and direction of a linear relationship between two variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*SwZTpFTqtm7AWC8MX7lmKA.png" /></figure><p>The results of the correlation matrix is as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*9D3sfKfmpWxDVg5v5MQ2bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*f2ehPlOVPu1cWMRetQ6z7Q.png" /></figure><p>From the image above, sales have a high correlation with product and on-promotion attributes.</p><p><strong>Feature Encoding</strong></p><p>It involves transforming categorical and textual data into a numerical format that can be fed into statistical models and machine learning algorithms.</p><p>The train and test datasets were encoded using the process below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*iPFi5qpmH4Qw7t-lxqzBgg.png" /></figure><p>After Encoding the train dataset the resulting rows were [1221740 rows x 85 columns] while the test datasets had [5 rows x 83 columns].</p><p><strong>Normalizing the ‘sales’ column</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FhRn9FlaBSTQSfjHa9zAew.png" /></figure><p>By subtracting the minimum value and adding 1, we ensure that the minimum value in the ‘sales’ column is 1. This is useful as we are working with certain models or algorithms that require positive input values.The addition of 1 is like adding a constant offset to all values. It doesn’t change the relative differences between values.</p><p><strong>4. Modelling</strong></p><p>This is the stage to develop and evaluate predictive models. It involves the following steps:</p><p>a. Model Selection:</p><p>The predictive models used include:</p><ol><li>Random Forest Regressor</li><li>Decision Trees Regressor</li><li>AutoRegressive(AR) Statistical Model</li><li>ARIMA (AutoRegressive Integrated Moving Average) Statistical Model</li><li>Seasonal AutoRegressive Integrated Moving Average(SARIMA) Statistical Model</li></ol><p>Evaluation metrics:</p><p>Mean Squared Error (MSE):</p><p>MSE measures the average of the squared differences between predicted and actual values. It quantifies the overall model error. Lower MSE values indicate better model performance, with 0 being a perfect fit (the predicted values match the actual values).</p><p>Mean Squared Logarithmic Error (MSLE):</p><p>MSLE is similar to MSE but calculates the squared differences on the logarithmic scale. It’s often used when the target variable has a wide range of values. Like MSE, lower MSLE values indicate better model performance.</p><p>Root Mean Squared Error (RMSE):</p><p>RMSE is the square root of MSE and provides a measure of the average magnitude of errors in the same units as the target variable. Lower RMSE values indicate better model performance.</p><p>Root Mean Squared Logarithmic Error (RMSLE):</p><p>RMSLE is the square root of MSLE and is used when the target variable is in the form of counts or has a wide range of values. Like RMSE, lower RMSLE values indicate better model performance.</p><p>Model Building:</p><p>This stage involves training the selected models using the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*A8YSh45oXQRAnRmOp_-9JQ.png" /></figure><p><strong>Random Forest Model</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*1GPOrxJ02-vfXotKOy7JkQ.png" /></figure><p>Below is a plot of predictions using the random forest regressor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAxtIxzOH0gDDBcbgnBQBQ.png" /></figure><p>The model’s predictions are very close to the actual values, and the fit is nearly perfect. The red line (predicted values) follows the blue line (actual values) throughout the entire time series. The low RMSLE 0f 0.02 suggests that the Random Forest model has effectively captured the underlying patterns, seasonality, and trends in the sales data. It means that the model’s predictions are not only close to the actual values but also in the same relative proportion as the original data.</p><p>Random Forest Residual Plot</p><p>A residual plot, often called a residuals plot, is a graphical tool used in regression analysis and other statistical modeling techniques. It helps in assessing the goodness of fit of a model and checking for potential problems or patterns in the model’s errors (residuals). Residuals are the differences between the observed values (actual data points) and the predicted values (values generated by the model).</p><p>Below is the Random Forest residual plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UXsyZ8BfgmV1mk2-WLhoA.png" /></figure><p>It is observed that the residuals are centered around the zero line on the vertical axis. the residuals have a mean close to zero, indicating that, on average, the model neither overpredicts nor underpredicts. There is a random scatter of points around the horizontal axis. This suggests that the model is capturing the underlying data patterns well.</p><p><strong>Feature importances</strong></p><p>Feature importances refers to the process of determining and ranking the importance or contribution of individual features (variables or predictors) in a machine learning model. Understanding feature importances can help you identify which features have the most influence on the model’s predictions and can be valuable for model interpretation, feature selection, and decision-making.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*yd50mttR_Aqw4c0ROQuG4g.png" /></figure><p>The graph shows the contribution of each input variable (feature) in predicting the target variable or sales. The above features are the top 15 features that are most influential in making predictions, with grocery 1, oil prices, store number, day of the year, and beverages being the top contributors in predicting sales using the random forest model.</p><p><strong>Decision Tree Regressor</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*7Qi7vljDrhCd4yOIK5ulSQ.png" /></figure><p>The visualization below shows Decision Trees predictions against original data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEeCO30R2qTrVTJYP_GSrg.png" /></figure><p>The Decision Trees model produces predictions with an RMSLE (Root Mean Squared Logarithmic Error) of 0.03, it indicates that the model’s predictions are quite close to the actual values, although not as precise as the Random Forest model with an RMSLE of 0.02. while the fit is close, there are some instances where the predictions deviate slightly from the actual values. generally, the Decision Trees model has captured most of the important trends, seasonality, and variations in the data. However, there may be some occasional deviations from the true values.</p><p>Residual plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wnXtT1j8Zjrs7fxwg_zZ9Q.png" /></figure><p>It is observed that the residuals are centered around the zero line on the vertical axis. Ideally, the residuals should have a mean close to zero, indicating that, on average, the model neither overpredicts nor underpredicts. Also, the random scatter of points around the horizontal axis suggests that the model is capturing the underlying data patterns well.</p><p>Feature importances</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*apr2qgwWLyzsD3uaUVpyFQ.png" /></figure><p>The graph shows the contribution of each input variable (feature) in predicting the target variable or sales. The above features are the top 15 features that are most influential in making predictions, with grocery 1, oil prices, store number, day of the year, and onpromotion ranking as the top contributors in predicting sales using the Decision tree model.</p><p><strong>Statistical Models</strong></p><p>For the statistical models, it is important to first group the data by date and average sales as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*IWyHb28DYoM21Xyw6C1UJQ.png" /></figure><p><strong>AR Model</strong></p><p>The AR model was trained as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*8FhROYpKsX1we9dSvk8dGA.png" /></figure><p>predictions were made on evaluation data as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*QKckBbGsQSb-Rdpisq8goQ.png" /></figure><p><strong>Evaluation</strong></p><p>The evaluation metrics of the model are as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*52nGPhnmcq6AuigGLn_9Uw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*0ZXzvMEPNP08pR0gIOohfA.png" /></figure><p>The RMSLE value of 0.13 means that, on average, the model’s predictions have a relatively low logarithmic error compared to the actual values. It suggests that the model is making predictions that are reasonably close to the true values, with a relatively small amount of error as shown in the visualization</p><p>Residual plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*KhENu_k9P960ywgmZm8HUQ.png" /></figure><p>A residual plot helps identify whether the AR model captures the temporal dependencies in the data effectively. we can see that residuals are distributed relatively evenly around zero, with no apparent patterns or trends. Points above the zero line represent cases where the model underestimates the actual values. In other words, the observed values are higher than what the model predicted. Points below the zero line represent cases where the model overestimates the actual values. The observed values are lower than the model’s predictions. This suggests that the model may need improvement.</p><p><strong>SARIMA Model</strong></p><p>SARIMA, or Seasonal AutoRegressive Integrated Moving Average, is an extension of the ARIMA (AutoRegressive Integrated Moving Average) model designed to handle time series data with seasonal patterns.</p><p>SARIMA model was trained as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*NzRaqBGzEvtvHk1BsLL1Nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*RJ2Kd-W5vw1fWwnXzkB-TA.png" /></figure><p>SARIMA’s metric results are as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*D_KSj7lz9_7kzozN7_CBQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*XAWpA1284xuMFYjIB7byug.png" /></figure><p>The RMSLE value of 0.16 means that, on average, the SARIMA model’s predictions have a relatively low logarithmic error compared to the actual values. It suggests that the SARIMA model is making predictions that are reasonably close to the true values, with a moderate amount of error. From the visualization, we can see that the predicted sales are slightly deviating from the actual values. This implies that there is a need to improve the model.</p><p>Residual plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*G3BvSxkKRnehOEkIbwxbMw.png" /></figure><p>we can see that residuals are distributed relatively evenly around zero, with no apparent patterns or trends. Points above the zero line represent cases where the model underestimates the actual values while points below the zero line represent cases where the model overestimates the actual values. Generally, the randomness of residuals and its even distribution around zero suggests that the SARIMA model is a good fit for the data, and the RMSLE of 0.17 is reflective of a well-performing model.</p><p><strong>ARIMA Model</strong></p><p>For ARIMA it is important to determine the order parameters based on ACF and PACF plots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*xGayLKCH4i2oTHig-6rNCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*33CpeM9w_nnWrCChaanqpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*nKStzTNhKLaCsXi6s_GqRQ.png" /></figure><p>Identifying d (Differencing Order):</p><p>If the ACF plot shows a slow decay and remains significant at higher lags, your data may need differencing (d) to become stationary.</p><p>Check the number of differences required to achieve stationarity. This is typically the number of times you need to difference the data until it becomes stationary. Use the ADF (Augmented Dickey-Fuller) test for stationarity.</p><p>Identifying p (AR Order):</p><p>For the PACF plot, look for significant spikes at lags before they drop off to insignificance. These spikes indicate the order of the autoregressive (AR) component (p).</p><p>If the PACF plot cuts off after p lags, this suggests that the AR term should be set to p. In other words, p is the lag value where the PACF sharply drops to zero.</p><p>Identifying q (MA Order):</p><p>For the ACF plot, look for significant spikes at lags before they drop off to insignificance. These spikes indicate the order of the moving average (MA) component (q).</p><p>If the ACF plot cuts off after q lags, this suggests that the MA term should be set to q. In other words, q is the lag value where the ACF sharply drops to zero.</p><p>I used a one-order difference to make the data stationary, hence d=1</p><p>both ACF and PACF sharply drop to zero at lag 9</p><p>Below is how the ARIMA model was trained and its metric results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*9JPheYbstZFMcrRjfiytNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*LcQbhWUZ9iJPewZq2Wy6nA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*hfUDVLdsvRwq26MeH1hGRw.png" /></figure><p>The ARIMA model is providing predictions that are reasonably close to the actual values. An RMSLE of 0.13 indicates that the model’s predictions are on average within a relatively small percentage error of the actual values. An RMSLE of 0.13 means that the model’s predictions deviate from the actual values by around 13% on average when considering the logarithm of the values. Hence, there is a need to refine the model to improve the RMSLE.</p><p>Residual plot</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*ORwPZMGXFGMRGj7cSd9xqA.png" /></figure><p>The residuals are centered around zero. This means that, on average, the model is not systematically overestimating or underestimating the target variable. The randomness of residuals indicates that the model has captured most of the underlying patterns in the data. This suggests that the ARIMA model is a good fit for the data, and the RMSLE of 0.13 is reflective of a well-performing model.</p><p><strong>Model Comparison</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*Jk9orLCmFAtwD3FNjbLY5w.png" /></figure><p>From the results of the models trained, Random Forest is the best-performing model with an RMSLE of 0.02. Root Mean Squared Logarithmic Error (RMSLE) is a metric commonly used to evaluate the performance of regression models, especially in cases where the target variable has a wide range of values and is subject to exponential growth or decay. RMSLE measures the accuracy of predictions on a logarithmic scale, making it suitable for tasks where relative errors are more important than absolute errors. Thus looking at the results, the performance of stat models is slightly lower compared to machine learning models. Hence, we fine-tune the parameters of stat models to improve their performance.</p><p><strong>Hyperparameter tuning</strong></p><p>Tuning ARIMA Model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*8dm2yzklQLLzTEuhgpUpgg.png" /></figure><p>After tuning the order of ARIMA Model, the best RMSLE was still at 0.13 with an order of (2,1,2).</p><p>Similarly, no changes were noted after tuning the SARIMA with the best RMSLE maintained at 0.16.</p><p>in conclusion, the RMSLE is a measure of accuracy that considers the logarithm of the actual and predicted values. In this case, the predictions are likely on a logarithmic scale. Therefore, an RMSLE of 0.02 means that the model’s predictions deviate from the actual values by around 2% on average when considering the logarithm of the values. Hence, this makes the Random Forest model the best model for predicting sales of the retail store.</p><p><strong>Conclusion</strong></p><p>Based on the analysis of the provided data, several key findings and trends have emerged:</p><ol><li>Sales Trends and Seasonality:</li></ol><p>There is a clear upward trend in sales over the years 2013 to 2017. Sales peak at the end of each year, likely driven by holiday shopping and year-end promotional activities. Additionally, seasonality is evident, with consistently lowest sales on January 1st each year.</p><p>2. Impact of External Events:</p><p>In 2016, there was a significant deviation from the typical sales trend, with the highest sales occurring in May, following a powerful earthquake in April. This suggests that external events can have a substantial impact on sales patterns.</p><p>3. Top-Selling Product Categories:</p><p>The top five selling product categories are Grocery1, Beverages, Produce, Cleaning, and Dairy products. Understanding the performance of these categories is crucial for inventory management and marketing strategies.</p><p>4. City Analysis:</p><p>Among the cities, Quito is the top-performing city in terms of sales, followed by Guayaquil. This indicates that these cities generate the highest revenues for the retail store, possibly due to higher population density and economic activity.</p><p>5. Cluster Analysis:</p><p>Cluster 14 is the top-performing cluster in terms of revenue, followed by clusters 6, 8, 11, and 10. This analysis provides insights into variations in sales performance across different store clusters.</p><p>6. State Analysis:</p><p>Pichincha leads in total sales among states, followed by Guayas. This reflects regional variations in sales performance, with stores in these states contributing significantly to overall sales.</p><p>7. Store Type Analysis:</p><p>Type A stores lead in total sales, closely followed by type D stores. Understanding the performance of different store types is essential for making strategic decisions.</p><p><strong>Recommendations</strong></p><ol><li>Seasonal Inventory Management:</li></ol><p>Given the observed seasonality in sales, the retail store should consider implementing seasonal inventory management strategies. This may involve stocking up on popular products before the holiday season and optimizing inventory levels throughout the year.</p><p>2. Event-Based Planning:</p><p>The impact of external events, such as the earthquake in 2016, highlights the importance of event-based planning. The store should have contingency plans in place to respond to unexpected events that may drive changes in customer behavior and demand.</p><p>3. Product Category Focus:</p><p>The top-selling product categories (Grocery1, Beverages, Produce, Cleaning, and Dairy) should receive special attention in terms of product availability, marketing, and promotions. Identifying trends within these categories can further enhance sales.</p><p>4. City and Store Type Strategy:</p><p>Since Quito and Guayaquil are the top-performing cities, the retail store should consider expanding its presence and marketing efforts in these cities. Additionally, understanding the performance of different store types can inform decisions regarding store expansion and investment.</p><p>5. Data-Driven Decision-Making:</p><p>The choice of the Random Forest model, with an RMSLE of 0.02, indicates that this model provides accurate predictions of sales. The retail store should continue to leverage data analytics and machine learning to make informed decisions, optimize inventory, and improve overall performance.</p><p>6. Economic Vulnerability:</p><p>Recognizing Ecuador’s economic vulnerability to oil price shocks, the retail store should remain agile in responding to economic fluctuations. Diversification of product offerings and risk management strategies may be considered.</p><p>In conclusion, the analysis of sales data provides valuable insights for the retail store’s strategic planning. By understanding sales trends, product categories, regional performance, and the impact of external events, the store can make data-driven decisions to optimize its operations and drive growth. Additionally, continued investment in data analytics and modeling can further enhance sales forecasting and overall performance.</p><p>Read more in my notebook:</p><p><a href="https://github.com/phinmaiyo/Regression-Model/tree/main">GitHub - phinmaiyo/Regression-Model</a></p><p>An Interactive Dashboard for this analysis is available at:</p><p><a href="https://app.powerbi.com/view?r=eyJrIjoiMTE3MmM2MTctN2FhZi00MmI0LWE1NzktMzRkY2M4YWJiY2ZjIiwidCI6IjQ0ODdiNTJmLWYxMTgtNDgzMC1iNDlkLTNjMjk4Y2I3MTA3NSJ9">Power BI Report</a></p><p>Appreciation</p><p>I highly recommend Azubi Africa for its comprehensive and effective programs. Read More articles at <a href="https://medium.com/@azubiafrica">https://medium.com/@azubiafrica</a> and take a few minutes to visit this link to learn more about Azubi Africa’s life-changing programs.</p><p><a href="https://bit.ly/41CGCwK">https://bit.ly/41CGCwK</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7445bbf3e86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Telecommunication Company Churn Analysis-Classification Model]]></title>
            <link>https://medium.com/@phinmaiyo/telecommunication-company-churn-analysis-classification-model-a190f9ce6518?source=rss-64101df3f334------2</link>
            <guid isPermaLink="false">https://medium.com/p/a190f9ce6518</guid>
            <dc:creator><![CDATA[Phonex Chemutai]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 19:23:25 GMT</pubDate>
            <atom:updated>2023-08-20T21:11:34.749Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*DCn_Zd2_oRtJA5dfjigBfA.png" /></figure><p><strong>INTRODUCTION</strong></p><p>Customer attrition is one of the biggest expenditures of any organization. Customer churn otherwise known as customer attrition or customer turnover is the percentage of customers that stopped using your company’s product or service within a specified timeframe.</p><p>For instance, if you began the year with 500 customers but later ended with 480 customers, the percentage of customers that left would be 4%. If we could figure out why a customer leaves and when they leave with reasonable accuracy, it would immensely help the organization to strategize their retention initiatives manifold.</p><p>The analysis follows The CRoss Industry Standard Process for Data Mining (<em>CRISP-DM</em>), which provides a structured approach, from understanding the business problem to deploying the model in a production environment.</p><ol><li><strong>BUSINESS UNDERSTANDING</strong></li></ol><p>In this project, we aim to find the likelihood of a customer leaving the organization, the key indicators of churn as well as the retention strategies that can be implemented to avert this problem.</p><p>This project is exploratory and predictive analytics, as it is my aim to deduce hidden insights and patterns from the dataset, as well as build a model for future customer churn predictions.</p><p><strong>Formulated questions for our analysis</strong></p><p>1. How does gender impact customer churn? Are there significant differences in churn rates between male and female customers?</p><p>2. Does the presence of a partner or dependents influence customer churn? Is there a relationship between marital status and churn behavior?</p><p>3. How does the length of tenure affect churn rates? Are customers with longer tenures less likely to churn compared to new customers?</p><p>4. What role do additional services (e.g., online security, tech support, streaming TV, etc.) play in reducing customer churn? Are customers with more services less likely to churn?</p><p>5. Is there a correlation between the contract term (month-to-month, one year, two years) and churn rates? Are customers on long-term contracts less likely to churn compared to those on month-to-month contracts?</p><p><strong>Hypothesis</strong></p><p>Hypothesis testing is a statistical method used to draw conclusions or make inferences about a larger population or dataset based on the analysis of a sample.</p><p>Null hypothesis(H_o): Contract type has no significant effect on customer churn.</p><p>Alternative hypothesis(H_a): Contract type has a significant effect on customer churn.</p><p>To test this hypothesis, I will examine the trend of customer churn based on the type of their contracts.</p><p>At the end of the analysis, it was clear that contract type has a significant effect on customer churn as customers with shorter(month-to-month) contracts churned more than customers with longer(one-year and two-year) contracts.</p><p><strong>2. DATA UNDERSTANDING</strong></p><p>The data for this project is in a CSV format and contains customer details such as gender, marital/dependents status, contract type, payment method, tenure, monthly and total charges, as well as whether or not the customer has access to additional services, such as online backup/security, device protection, tech support and their ability to stream tv and movies.</p><p><strong>3. DATA PREPARATION</strong></p><p>The importation of libraries is an essential step before beginning an analysis.</p><p><strong>3.1: Python Libraries</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*6J5X4z3KMskh41Rz8pImtw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*z8U5OIDstEftq5sAl3f9oQ.png" /></figure><p><strong>3.2: Data Loading</strong></p><p>This is how the first dataset was retrieved from the SQL Server database. The second and third datasets were downloaded and imported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*kijMpR7Di8XoZ_OYiWh6ag.png" /></figure><p>upon examining the train and test datasets, most columns were deemed as relevant except for “customer_id” which was dropped in all the datasets. The first train set had considerable missing values while the second train set and test set had no null values. upon further examination, it was noted that the datatypes of these datasets were not consistent as some were objects while others were in boolean type as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*7wr7POb7OnI_NFh2Rp0x8A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*yD_TdxIcKj2tbpu_cp5n4Q.png" /></figure><p><strong>3.3: Data Cleaning</strong></p><p>The cleaning process of the training set took the following steps:</p><p><strong>3.3.1: Handle Inconsistencies</strong></p><p>The first step was to replace the encoded column values in the second training set with No and Yes to match the first training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*GBgGXKZGqXyKxY5UDpNtwA.png" /></figure><p>I then converted the boolean values of ‘True’ and ‘False’ in the first training dataset to objects of ‘No’ and ‘Yes’. This ensured that both datasets had the same data types to enable merging. The process is as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*UMjefVPnLKQL2tx43w0oJA.png" /></figure><p>The output of the code is as shown below, where we see consistent datatypes except for total charges in the second dataset which was converted to a float 64.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*cW420VrO71aljstdMR7Bog.png" /></figure><p>Once, the inconsistencies were handled, the training datasets were merged as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*JEJy8EJWwimih5iaskOmdQ.png" /></figure><p>Next was to look at the missing which will be imputed using a simple imputer at the modelling stage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*jeg51t0R3qzY8Rb9i5M0kQ.png" /></figure><p><strong>3.3.2: Handle Outliers</strong></p><p>Outliers are data points that significantly deviate from the majority of the data points in a dataset. They can be caused by various factors such as errors in data collection, measurement errors, or rare events. Outliers can have a significant impact on machine learning models, as they can distort the statistical properties of the data and lead to inaccurate or biased results.</p><p>I created a box plot to have a look at the outliers in the monthly charges and total charges attributes as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*2rxmQ5eWJMjdMopVxBIzaw.png" /></figure><p>The output of the code is as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*JBIKr4D61d5Ix-LtGnybWA.png" /></figure><p>On checking, the number of outliers in both attributes was zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*owLxMQWDrsYLJbsEnBVsnA.png" /></figure><p><strong>3.3.3: Handle duplicates</strong></p><p>Duplicate data points occur when there are multiple entries in the dataset that represent the same underlying observation. These duplicates can skew the training process and evaluation metrics, leading to misleading results. It’s important to identify and remove duplicate data points from your dataset before training the model.</p><p>I found that there were 10 duplicates in the training dataset as shown below, which were dropped based on the specified subset of total charges and monthly charges columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*yw-wnqNoWyKpwHI4lmPKzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*e_8EYjQaLaM-CdpMrDOtKw.png" /></figure><p>On comparing the cleaned training dataset with the test dataset, I found inconsistencies in the test dataset, which were handled with the same process as the training dataset by converting the ‘seniorcitizen’ column to an object and converting the total charges to a float.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*ALq0YukAW9sB786O0bT94g.png" /></figure><p>On further examination of the test dataset, it was found that the total charges column had a few outliers, which were replaced with the median using the Interquartile Range (IQR) approach. IQR is a common method used in data analysis to identify and deal with extreme values that lie far from the central distribution of the data. The duplicates in the dataset were also dropped based on the specified subset of columns as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*zktePeovV2vcgP7hi3besQ.png" /></figure><p><strong>3.4: Univariate Analysis</strong></p><p>In this section, we inspect the datasets in-depth and conduct a univariate, bivariate, and multivariate analysis and test the hypothesis to have a clear understanding of the patterns and trends in the training dataset.</p><p><strong>3.4.1: Analysis of tenure attribute</strong></p><p>the tenure attribute was categorized to reveal trends and insights on customer churn across different tenure groups as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*CWc7OA4hGv6C9DTVLuogYg.png" /></figure><p>The output was then plotted to show the frequency distribution of the tenure attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*mx2x23RyGr2GYpy80OCdMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*yWpCcouDvBPpQUpyCTJpYw.png" /><figcaption>Fig 1: Tenure distribution</figcaption></figure><p>From the visualization, it&#39;s clear that most of the customers have stayed in the company for less than 12 months. I also deduced that the company has a significant number of loyal customers who have stayed for more than 61 months.</p><p><strong>3.4.2 Analysis of churn attribute</strong></p><p>since the churn attribute is categorical, I visualized the churn rate with a doughnut chart. From the value counts below, 3655 of the customers did not churn while 1280 churned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*kJG2tEa9JsHi8_9I6h_JVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*oXLyfHnjM2-cXIDBHjY35w.png" /><figcaption>Fig 2: churn distribution</figcaption></figure><p>we can also see that we have imbalanced data as 74% of the total customers did not churn while 26% left the company. this implies that we have to balance our data before training the model.</p><p><strong>3.4.3 Analysis of total charges</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*cks1fwJxM6_RGOyeXa_9Jw.png" /><figcaption>Fig 3: Total charges distribution</figcaption></figure><p>The distribution plot shows in detail the skewness of the total charges, and it indicates a positively skewed distribution.</p><p><strong>3.4.4 Analysis of Gender Attribute</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*U-_B7k8lKY-eMzQyYJO1mA.png" /><figcaption>Fig 4: Gender distribution</figcaption></figure><p>used a bar graph to visualize the gender attribute. It can be observed that gender distribution is almost even, with Males exceeding females by a very small margin.</p><p><strong>3.4.5 Analysis of payment method</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*G6UGhY5iXDm1gOqIRCfPQQ.png" /><figcaption>Fig 5: payment method distribution</figcaption></figure><p>It can be observed that the majority of customers preferred Electronic Checks as a method of payment. This can be linked to the convenience and security offered by electronic checks of making payments directly from a bank account without the need to write and mail physical checks. Customers can initiate transactions online or through electronic payment platforms.</p><p><strong>3.4.6 Analysis of internet service</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*MWhlxiTJMmiGr0j7yBMWqg.png" /><figcaption>Fig 6: Internet service distribution</figcaption></figure><p>it is observed that the majority of customers prefer Fibre optic for internet service provision.</p><p><strong>3.5: Bivariate Analysis</strong></p><p>Bivariate analysis is a statistical analysis technique that involves examining the relationship between two variables. It aims to determine whether there is a significant association, correlation, or pattern between the two variables</p><p>In this section, we also answer the analytical questions.</p><p><strong>3.5.1: How does gender impact customer churn? Are there significant differences in churn rates between male and female customers?</strong></p><p>I created a contingency table using the crosstab function and then calculated the churn rate for each gender category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*b98xLOLeL35wWfmcWlSDBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*9TXRldOxSUOn09yZfA4M7Q.png" /><figcaption>Fig 7: Churn vs Gender</figcaption></figure><p>It is observed that there is no significant difference in churn rates between male and female customers where 25.9% of males churned while 26.1% of females churned.</p><p><strong>3.5.2: Does the presence of a partner or dependents influence customer churn? Is there a relationship between marital status and churn behavior?</strong></p><p>I calculated the churn rate for each partner and dependents category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wnt5oPZ0azEwhKpUDYIgmQ.png" /><figcaption>Fig 8: Churn vs partner and dependents</figcaption></figure><p>It is observed that the presence of a partner or dependents influences customer churn as those without partners churned more compared to those with partners. similarly, those without dependants churned more compared to those with dependants. I conclude that customers in a family setup tend to stay longer compared to those without.</p><p><strong>3.5.3: How does the length of tenure affect churn rates? Are customers with longer tenures less likely to churn compared to new customers?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*yIm2KY40yf6WXVvVq_rk_g.png" /><figcaption>Fig 9: Churn vs Tenure</figcaption></figure><p>It is observed that the churn rate decreases with an increase in tenure. New customers are more likely to churn than old customers.</p><p><strong>3.5.4:</strong> <strong>What role do additional services (e.g., online security, tech support, streaming TV, etc.) play in reducing customer churn? Are customers with more services less likely to churn?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTOzlHy-FkoXEUR4sh3Tdg.png" /><figcaption>Fig 10: Churn vs Additional Services</figcaption></figure><p>It is observed that most customers do not have access to additional services. however, additional services play a significant role in reducing customer churn. we can see that customers with additional services are less likely to churn considering the rate of churn. the rate of churn for customers without additional is about 1/3 compared to the rate of churn for customers with additional services which is about 1/5. Hence, we conclude that the company should ensure that its customers have access to additional services to reduce churn.</p><p><strong>3.5.5:</strong> <strong>Is there a correlation between the contract term (month-to-month, one year, two years) and churn rates? Are customers on long-term contracts less likely to churn compared to those on month-to-month contracts?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*5u7SjnrN1O1nI4mAmAwZCA.png" /><figcaption>Fig 11: Churn vs Contract</figcaption></figure><p>It is observed that customers on long-term contracts are less likely to churn compared to those on month-to-month contracts. Thus the company should make their long-term contracts attractive to customers to encourage them to sign up for one-year or two-year contracts.</p><p><strong>3.6:</strong> <strong>Multivariate Analysis</strong></p><p>Multivariate analysis is a statistical technique used to analyze and interpret relationships between multiple variables in a dataset. It involves examining the interactions and dependencies between several variables simultaneously to gain deeper insights and understand complex patterns within the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*0h4SnIA6F3KnNxu26UK9Lw.png" /><figcaption>Fig 12: A multivariate analysis</figcaption></figure><p>It is observed that the number of months the customer has stayed with the company(tenure) has a higher correlation of 0.82 with the total amount charged to the customer(TotalCharges) compared to the amount charged to the customer monthly(MonthlyCharges). Hence, the tenure period of a customer is determined by long-term charges compared to monthly charges.</p><p><strong>3.6 Hypothesis Testing</strong></p><p>H_o: Contract type does not influence customer churn</p><p>H_a: Contract type affects customer churn</p><p>I created a contingency table using the crosstab function and then calculated the churn rate for each contract category as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*iRTGn49mHag5GbtEv2pl1A.png" /></figure><p>The churn rate is calculated by dividing the number of customers who churned (‘Yes’) by the total number of customers in that gender category, and then multiplying by 100 to get a percentage. It is observed that for customers with month-to-month contracts, 1128 churned while 1513 did not churn. Of those with one-year contracts, 122 churned while 930 did not churn. lastly, for those with two-year contracts, 30 churned while 1212 did not churn. The trend shows that customers with shorter contracts are more likely to churn compared to customers with longer contracts such as one-year or two-year contracts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRQGHwLDDVfnZN7OHYBxkQ.png" /></figure><p>Performed a chi-squared test for independence to test the association of the two variables. It is observed that the p-value is less than alpha, thus, we reject Ho and conclude that there is a statistical significance association between Churn and Contract.</p><p><strong>4: Modeling</strong></p><p>At this stage, I start training the data using different models to predict whether a customer will churn or not.</p><p>The models to be tested include:</p><p>1. Random Forest Classifier</p><p>2. Decision Tree Classifier</p><p>3. Ada Boost Classifier</p><p>4. Logistic Regression</p><p>5. Gradient Boosting Classifier</p><p>The number of numerical and categorical columns in the training set is as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*DD2v73ObjtWf48DEOjMXBA.png" /></figure><p>The training data has three numeric features and seventeen categorical features.</p><p><strong>4.1: Split Train Dataset</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*5P8FRd6m8QHesOVsJjppyg.png" /></figure><p>The training data is split into train and evaluation as a ratio of 7:3. There is a separate test dataset (X_test) that will be used for testing the final trained model and making future predictions.</p><p><strong>4.2: Impute Missing Values</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*v9f9Aj7TvgcH_SyRgpqTqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*oueD_B3xsA8AC93wWPUfgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*v-CdvhX10pbWdekBUDIe7Q.png" /></figure><p>From the code above, it is observed that the train and eval sets have missing values that will be imputed using the ‘simpleimputer’. The ‘Simpleimputer’ class in scikit-learn is used to impute missing values in a dataset with a specified strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*rJJoFVIQhw6t6z-Hx3U0yQ.png" /></figure><p>In the code above I set <em>strategy=&#39;median&#39;,</em> the <em>simpleimputer</em> calculates the median of each numerical (column) and then replaces missing values in that column with the calculated median. The median is the middle value of a sorted list of values. This strategy is particularly useful for numerical features.</p><p>After fitting the imputer to the data, the next step is to transform X train, X eval, and X test using <em>imputer.transform(X)</em> to replace missing values with the median of each column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*iWuE-gdot8dwETPwJusN1w.png" /></figure><p>The same process is applied to the categorical columns by setting the <em>strategy=most_frequent</em>, which replaces missing values in each column with the most frequent value (mode) of that column as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*pmyLerExNDGwhfgJFojwlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*1qJtWfl6_ycv5zfkGBBxjg.png" /></figure><p><strong>4.3: Feature Engineering</strong></p><p>Feature engineering is a critical step in the machine learning pipeline where you create new features or modify existing ones to improve the performance of your model. It involves selecting, transforming, and creating features from your raw data to make it more suitable for machine learning algorithms. Well-engineered features can help the model better capture patterns and relationships within the data, leading to improved predictive power.</p><p><strong>4.3.1: Feature Scaling</strong></p><p>It is important to standardize or normalize numerical features to ensure that they have similar scales. This helps algorithms that rely on distance or magnitude, such as k-nearest neighbors and gradient descent-based methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*vpo8mQjTNEvIUjEcHt_1Wg.png" /></figure><p>The <em>StandardScaler</em> is used to standardize features by removing the mean and scaling them to unit variance. It is observed that the <em>tenure</em>, <em>monthlycharges</em> and <em>totalcharges</em> columns have been scaled.</p><p><strong>4.3.2: Feature Encoding</strong></p><p>Feature encoding is a crucial step in preparing your data for machine learning models. It involves transforming categorical and textual data into a numerical format that can be fed into machine learning algorithms. since the categorical variables are nominal, I applied One-Hot Encoding that converts each category into a binary column (0 or 1), indicating the presence or absence of that category. This technique increases the dimensionality of the data but works well with algorithms that require numerical input.</p><p>The process of encoding is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7U6Pk-t4rNSYssRdXwrHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LK4ppIu4EkbGdaugLzZCiw.png" /></figure><p>First I fit and transform the train data, and only transform the evaluation and test datasets to avoid data leakage. I then converted the arrays to Dataframe and merge the numeric features that were scaled with encoded categorical features for all the datasets.</p><p>The final output of the datasets is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtwEGMUcpPPv6uVBWYRsHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irulFG34XY05gjArEkLK7A.png" /></figure><p><strong>4.4 Balancing Data</strong></p><p>Balancing the data is important when you have imbalanced classes in a classification problem, meaning one class has significantly more samples than the other. Imbalanced data can lead to biased model training and inaccurate predictions, as the model may become biased towards the majority class. We have imbalanced data as 74% of the total customers did not churn while 26% did churn. this implies that we have to balance our data before training the model</p><p>SMOTE (Synthetic Minority Over-sampling Technique) is a popular technique used to balance imbalanced datasets by creating synthetic samples for the minority class. It aims to alleviate the class imbalance problem by oversampling the minority class, thus improving the performance of machine learning algorithms. Here’s how I applied SMOTE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*obcc-73hjX1hm9BttT3XBQ.png" /></figure><p>On applying smote, it is observed that the target is now balanced.</p><p><strong>4.5 Model Training</strong></p><p>Here, I created instances of different models (Logistic Regression, Random Forest, Decision Tree, Ada Boost, and Gradient Boosting Classifier) and added them to the model&#39;s dictionary. Then, I loop through each model, train it on the training data, evaluate it on the evaluation data, and print their evaluation metrics, which include accuracy, precision, recall, F1 score, and F2 scores. The process is as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*tEeNcgqyeH2FaGRBoKE4sw.png" /></figure><p>The output of the code is as shown below, which includes the confusion matrix of each model and their respective accuracies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*p7wACPZZCHuyWGh3cAt-Gg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*gZFtFENHXLAPER0y7loMXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*Lex_QzisQL6Dp_wmXZc4hQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*OoX06KG0RqvEGKIe3-edhA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*aB8FekWEr8bAqbIlnMhIbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*4aQEOXWAUJEXZetuc7CfYg.png" /></figure><p>It is observed that the Gradient Boosting classifier is the best model with an accuracy score of 79% followed by Random Forest with a score of 78% and Ada Boost with 77.5%. The random forest classifier has correctly predicted 927 positive instances and 235 negative instances, while Gradient boosting has correctly predicted 889 positive instances and 278 negative instances.</p><p>Accuracy measures the proportion of correctly classified instances out of the total instances. It’s a basic metric that gives an overall view of the model’s correctness.</p><p>In this analysis, we want to find a model that can accurately classify churn instances and from the results, we can see that Gradient Boosting, Random Forest, and Ada Boost Classifiers have the highest accuracies.</p><p><strong>4.6 Model Improvement</strong></p><p>Model improvement in machine learning involves various strategies to enhance the performance of a model and achieve better predictive accuracy.</p><p><strong>Hyperparameter Tuning</strong></p><p>To improve the three top models, I apply hyperparameter tuning to Fine-tune the top k models (3&lt;k&lt;5) using a GridsearchCV (that is in sklearn.model_selection) to find the best hyperparameters and achieve the maximum performance of each of the top k models, then compare them again to select the best one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*_UYnwxg1hSQXTo_mSetJjw.png" /></figure><p>The first step is to initialize an empty list to store the models after tuning the parameters and create an instance of LabelEncoder to fit it to the target variable y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*9K_HlkSsz0PulBRUa-HfWA.png" /></figure><p>Next is to define the parameters to fine-tune and their possible values to search through. I then create a <em>GridSearchCV</em> object for hyperparameter tuning of gradient boosting classifier using a parameter grid and evaluation metrics to find the best combination of hyperparameters for a machine learning model.</p><p>The accuracy score evaluation metric is used to determine the performance of different hyperparameter combinations, while the refit indicates the need to refit the best model found with the entire training dataset using the best hyperparameters. 5-fold cross-validation is applied during the hyperparameter tuning process. Verbose sets the level of verbosity for the output.</p><p>After tuning the parameters of the three top models, the best combination of hyperparameters and accuracy is displayed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CRwHGHGYw1N98XhiESjybw.png" /></figure><p>From the results of the hyperparameter tuning, we can see that Random Forest Classifier is the best model to make predictions on customer churn with an accuracy of almost 88% followed closely by Gradient boosting with 86% accuracy. I apply the best parameters on the evaluation test to further compare the performance of the models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*DEsKqBi7buxBXlYXe7eiog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*fVLWKfGddkG6XtXYjT59aA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*DdIqkadfGHF7_wITuWde1w.png" /></figure><p>The scores of the two models on the evaluation dataset show that the Gradient Boosting classifier has the highest accuracy of 78.5% while the Random Forest classifier has an accuracy of 78.1%. looking at the confusion matrix the Random Forest model correctly predicted 919 instances as positive out of the 1074 instances and correctly predicted 237 instances as negative out of the 407 instances. on the other hand, Gradient boosting correctly predicted 909 instances as positive out of the 1074 instances and correctly predicted 256 instances as negative out of the 407 instances. Hence, the Random Forest model has predicted more instances in the positive class, while the Gradient boosting has predicted more instances in the negative class. however, the margin of difference in the prediction of the positive class is insignificant compared to the margin in the negative class. Hence, we choose the Random Forest classifier as the best model for predicting customer churn as it provides a balance between predicting positive and negative instances, and also its high accuracy score of 88% on training data.</p><p><strong>5: Evaluation</strong></p><p><strong>Saving the model</strong></p><p>Pickle is the standard way of serializing objects in Python. we will use the pickle operation to serialize our machine-learning algorithm and save the serialized format to a file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Gju40_oPw9vv0Jnkre4CZw.png" /></figure><p>The loaded_churn_model can now be used for making future predictions as shown below.</p><p><strong>5.2: Testing of Predictions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*YQMM-LtRXwUTPHbSEEzUXg.png" /></figure><p>It is observed that the model has made predictions on new data (test data), returning an array of whether or not ( Yes or No) the customer will churn based on the best-trained Random Forest Classifier model.</p><p><strong>6: Deployment</strong></p><p><strong>Export Key Components</strong></p><p>Here we export the important ML objects that will be used to develop an app: encoder, scaler, column transformer, models e.t.c.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4KiDHASJuycleP5a9Q0T4g.png" /></figure><p>To export key components, I define the imputer, encoder, and scaler used to transform the data and the best model selected for predicting customer churn. I then created a directory that I will use to save the components and requirements. The pickle. dump() function is then used to save the serialized ‘components’ object to a binary file named “ml.pkl” inside the “export” directory. The object can later be loaded back into memory using pickle.load() to use the components data.</p><p><strong>7.0: Conclusion</strong><br>In this customer churn analysis, we have explored and analyzed a telecommunications dataset to understand the factors influencing customer churn. The primary goal was to identify patterns and insights that can help us predict and manage customer churn effectively. Through a rigorous process of data preprocessing, exploratory data analysis, and machine learning modeling, we were able to uncover valuable insights.</p><p><strong>7.1: Key Insights:</strong><br><strong>1. Best Model for Prediction</strong>: After thorough experimentation with various machine learning models, the Random Forest Classifier emerged as the best model for predicting customer churn. This model demonstrated a robust ability to accurately predict whether a customer is likely to churn or not.</p><p><strong>2. Impact of Tenure:</strong> One significant insight is that customer churn rate decreases with an increase in tenure. This suggests that customers who have been with the company for a longer period are more likely to remain loyal, possibly due to the establishment of a trusting relationship over time.</p><p><strong>3. Effect of Additional Services</strong>: Found that the availability of additional services plays a crucial role in reducing customer churn. Customers who are utilizing these services are less likely to churn. This insight underscores the importance of providing valuable and relevant additional services to enhance customer retention.</p><p><strong>4. Contract Type</strong>: Another important finding is that customers on long-term contracts are less likely to churn compared to those on month-to-month contracts. This highlights the significance of offering contract options that encourage longer-term commitments, leading to better customer loyalty.</p><p><strong>7.2: Recommendations:</strong><br>Based on the insights gained from our analysis, here are some actionable recommendations to reduce customer churn and improve overall customer retention:</p><p><strong>1. Leverage Additional Services</strong>: Focus on enhancing and promoting additional services that provide value to customers. This could include personalized offerings, discounts, or bundling services to increase customer engagement and loyalty.</p><p><strong>2. Incentivize Long-Term Contracts</strong>: Encourage customers to choose longer-term contracts by offering benefits such as reduced rates, exclusive offers, or rewards for committing to extended periods. This strategy can help stabilize customer retention rates.</p><p><strong>3. Improve Customer Onboarding</strong>: Provide comprehensive onboarding experiences for new customers, ensuring that they understand the full range of services available to them. This can help set realistic expectations and increase satisfaction in the early stages of their relationship with the company.</p><p>4<strong>. Targeted Retention Strategies</strong>: Identify high-risk segments of customers, such as those with short tenure or using fewer services, and implement targeted retention campaigns. Tailor communication and offers to address their specific needs and concerns.</p><p><strong>5. Continuous Monitoring and Analysis</strong>: Implement a system to regularly monitor customer behavior, feedback, and satisfaction. Use this data to adapt and refine customer retention strategies over time.</p><p>In conclusion, the insights gained from this analysis and the predictive power of the Random Forest Classifier provide a solid foundation for customer churn prediction and management. By implementing the recommended strategies, the company can proactively reduce churn, enhance customer satisfaction, and foster long-lasting relationships with its customers.</p><p>Read more in my notebook:</p><p><a href="https://github.com/phinmaiyo/Telco-Churn-Analysis">GitHub - phinmaiyo/Telco-Churn-Analysis: 1. Help the client, a telecommunication company, to understand their data. 2. Find the lifetime value of each customer. 3. Know what factors affect the rate at which customers stop using their network. 4. predict if a customer will churn or not.</a></p><p>An Interactive Dashboard for this analysis is available at:</p><p><a href="https://app.powerbi.com/view?r=eyJrIjoiNWRlMDhhYzMtMGJkZi00OTQzLWI0MTItZGJmODJjYWVlYjE3IiwidCI6IjQ0ODdiNTJmLWYxMTgtNDgzMC1iNDlkLTNjMjk4Y2I3MTA3NSJ9">Power BI Report</a></p><p>Appreciation</p><p>I highly recommend Azubi Africa for its comprehensive and effective programs. Read More articles at <a href="https://medium.com/@azubiafrica">https://medium.com/@azubiafrica</a> and take a few minutes to visit this link to learn more about Azubi Africa&#39;s life-changing programs.</p><p><a href="https://bit.ly/41CGCwK">https://bit.ly/41CGCwK</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a190f9ce6518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysis Of the Indian Start-Up Ecosystem Based on Funding From 2018–2021-A Data Visualization…]]></title>
            <link>https://medium.com/@phinmaiyo/analysis-of-the-indian-start-up-ecosystem-based-on-funding-from-2018-2021-a-data-visualization-b8c9df3eb9ff?source=rss-64101df3f334------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8c9df3eb9ff</guid>
            <dc:creator><![CDATA[Phonex Chemutai]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 21:47:52 GMT</pubDate>
            <atom:updated>2023-07-23T21:47:52.439Z</atom:updated>
            <content:encoded><![CDATA[<h3>Analysis Of the Indian Start-Up Ecosystem Based on Funding From 2018–2021-A Data Visualization Approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*pJ5Rwf1gqRZ5ytLpbbARIQ.png" /></figure><p><strong>INTRODUCTION</strong></p><p>The Indian startup ecosystem is the 3rd largest in the world and has been a subject of interest to various global stakeholders. Hence, as a data analyst, I researched the topic and used my skills to analyze and visualize it to aid the stakeholders in making more informed decisions. The analysis follows The CRoss Industry Standard Process for Data Mining (<em>CRISP-DM</em>), which provides a structured approach to guide data scientists and analysts through all the stages of a data mining project, from understanding the business problem to deploying the model in a production environment.</p><p><strong>1.</strong> <strong>BUSINESS UNDERSTANDING</strong></p><p>India’s economy is experiencing rapid growth, making it one of the fastest expanding in the world. Over the past decade, the Indian startup ecosystem has seen a significant rise in unicorn startups, which have gained global influence. Despite being small businesses, startups play a crucial role in boosting economic growth by creating more job opportunities and contributing to a healthier economy. Additionally, startups drive innovation and competition, further enhancing economic vitality.</p><p>In this article, I will walk you through the steps I took to understand the Indian startup ecosystem using Python. I utilized data from Indian startups that received funding between 2018 and 2021. However, the data cleaning process proved challenging due to inconsistencies within the dataset for each year. Nonetheless, by employing Python and data analysis techniques, I was able to gain valuable insights into the Indian startup landscape during this period.</p><p>The objective of this project is to provide insights to key stakeholders interested in venturing into the Indian startup ecosystem. To achieve this, I will be analyzing key metrics in funding received by startups in India from 2018 to 2021. These insights will be used by start-up management to make data-driven decisions about entering the Indian market.</p><p>This project is of the exploratory data analytic and visualization type, as it is my aim to deduce hidden insights and patterns from the dataset. To draw valid conclusions from the dataset, I formulated hypotheses to test its underlying patterns and relationships. By creating these hypotheses, I aimed to systematically investigate and analyze the data, allowing for informed and evidence-based conclusions. This approach helped ensure that my findings were grounded in rigorous analysis and statistical testing, enhancing the credibility and reliability of the conclusions drawn from the dataset.</p><p><strong>4.2 Questions</strong></p><p>1. To what extent do cities influence funding (amount, etc.)?</p><p>2. Which industries are preferred by investors for funding?</p><p>3. At which stage do start-ups get more funding from investors?</p><p>4. What is the typical funding amount that startups receive in India?</p><p>5. Which type of investors invest the most money?</p><p>6. Can the age of the startup affect the amount received from investors?</p><p><strong>Hypothesis:</strong></p><p>Hypothesis testing is a statistical method used to draw conclusions or make inferences about a larger population or dataset based on the analysis of a sample. By conducting specific statistical tests on the sample data, researchers can gain insights into the characteristics of the entire population. This approach enables them to make data-driven decisions and draw meaningful conclusions with a certain level of confidence, ensuring that their findings are representative and applicable beyond the sampled data. To further analyze the data, I developed the null and alternate hypothesis to focus on the location of the startup.</p><p>Hypothesis:</p><ul><li>Null Hypothesis (H0): The location of a startup has no significant effect on the amount received from investors.</li><li>Alternative Hypothesis (H1): The location of a startup significantly influences the amount received from investors.</li></ul><p>To test this hypothesis, I will examine the distribution of tech start-ups across cities and deduce which cities have the most highly funded start-ups.</p><p>At the end of the analysis, it becomes clear that the location of a startup significantly affects the amount of funding issued by investors.</p><p><strong>2.</strong> <strong>DATA UNDERSTANDING</strong></p><p>The dataset contains funding details of Indian startups spanning from 2018 to August 2021. It comprises several columns, such as the date when the funding was received, the city where the startup is located, the names of the founders and investors, what the company does, and the investment amount given in USD, occasionally supplemented by values in Rupees.</p><p><strong>3. DATA PREPARATION</strong></p><p><strong>3. 1: Python Libraries</strong></p><p>Before cleaning and doing an analysis of the data, it is essential to import all necessary libraries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*ZGGkKcxGd88gUyOoe9WHqg.png" /></figure><p><strong>3.2: Import Data</strong></p><p>This is an example of how the 2021 dataset was retrieved from the SQL Server database. The same process was used for the 2020 dataset, while the 2018 and 2019 datasets were downloaded and imported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*ixyTBOHai-tcleIOiT8XpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*mqkUvZYQWHpwFKaRORDwIQ.png" /></figure><p>Upon examining the datasets from different years, certain common columns were identified as relevant for the analysis. To ensure consistency across all datasets, some columns were renamed. The ‘Industry’ column was renamed to ‘Sector’, the ‘Location’ was renamed to ‘Headquarter’, the ‘Amount’ was renamed ‘Amount ($), and the ‘Round/Series’ column was renamed to ‘Stage’.</p><p>Additionally, a new column called ‘Funding Year’ was added to each dataset. Each row in the respective datasets was assigned the corresponding year, ‘2018’, ‘2019’, ‘2020’, or ‘2021’, depending on the dataset’s data.</p><p>Except for the 2018 dataset, all other datasets included additional relevant columns. These columns contained information such as the year the startup was founded and the name of the investor who provided the funding. The inclusion of these columns was necessary to understand the number of years each startup had been in operation and to gain insights into their funding sources over time.</p><p><strong>3.3 Data Cleaning</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PjElzdHQ98Dn1jwxZf7v-A.jpeg" /></figure><p>Data cleaning follows the following steps.</p><p><strong>3.3.1 Handle Inconsistencies</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*Pz-KoJooyoPgcHVjET_S7g.png" /></figure><p>I then checked for consistency in each column and applied various changes as shown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*_YHFepCGrGIsv2-K7L9GeA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*yP04JAOAfL_tMWlnRJBuYg.png" /></figure><p>I grouped the sector column into main sectors since a question was required to show the typical funding of various sectors in India.</p><p>The final output of the sector column is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*Vkhlav08jzG0ljBlAM1zOw.png" /></figure><p>The Amount column also had inconsistencies in the form of special characters and non-digit characters, which I replaced with empty strings and converted to nan before converting the column to numeric;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*00fMfTYX6gen1Ud3Vy1rUg.png" /></figure><p>The result of this code can be observed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*FLv4xwruct73P1adQTBtOA.png" /></figure><p>The stage column also had inconsistencies in the form of special and digit characters, which I replaced with empty strings and replaced with Unknown as most of the stages in the column were ‘Unknown’. To further achieve consistency, I grouped the categories into various stages as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*O1DDbRXoZH5hoP7LE5UYgQ.png" /></figure><p>The result of this code can be observed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*Ygt0hpBw1R7x8_SlLWqhgA.png" /></figure><p><strong>3.3.2 Imputing Missing Values</strong></p><p>Some of the columns had missing values as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*Yqx3sqWDVMOhcyd4v0sCAQ.png" /></figure><p>To impute the missing values I separated the columns into numeric and object, where I used mode to impute object columns and median to impute numeric columns as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*1veUXeie3AbWPa3BmEfKNA.png" /></figure><p>The result of the code can be observed below, and we can see that the 2021 dataset does not have any null values;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*7nlAgK8O4ZEAFEMQeezwOQ.png" /></figure><p><strong>3.3.3 duplicates</strong></p><p>The dataset had a few columns which I dropped as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*PY1b0o2xGNED7pKsSFKyOw.png" /></figure><p>I used the subset of columns to avoid dropping non-duplicates since some records could have similar sector names, but different investors and amounts raised.</p><p><strong>3.3.4 Final Dataset</strong></p><p>After the data cleaning process, all datasets were concatenated and merged into 1 data frame with 2873 rows and 8 columns in total. The top 5 records of the dataset are as follows;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*wl0jMya-rmjOQ1ccBR0yqQ.png" /></figure><p>Column names and descriptions:</p><p>Company Name: Name of the company/start-up</p><p>Founded: Year start-up was founded</p><p>Sector: Sector of service</p><p>Investor: Investors</p><p>Amount ($): Raised fund.</p><p>HeadQuarter: Town where the startup is located</p><p>Stage: Round of funding reached</p><p>Funding year: The year when the survey was taken.</p><p><strong>3.4 Exploratory Data Analysis: EDA</strong></p><p>In this section, we inspect the datasets in-depth and conduct a univariate, bivariate, and multivariate analysis and test the hypothesis to further understand the patterns and trends in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*C7ZkwFF7Xm8TFreCbtvm1w.png" /></figure><p>The empty entries in the Founded, Founders, and Investor columns were imputed and filled. These missing values were a result of the absence of these three columns in the 2018 dataset. Since dealing with null values can be challenging, the missing values in the founded column were imputed with mode, while those in founders and investor columns were imputed with ‘unknown’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*f-ceIU6rCJCXMt8PIAwNgA.png" /></figure><p>The result of the code can be observed below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*CDv5E4WQ2wvfdqmKMnu3yg.png" /></figure><p>There were still some inconsistencies in the sector column after merging the datasets and were handled as follows;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*QwBA7C2X7gMAWUL6ReFqbg.png" /></figure><p>There were also duplicates in the combined dataset which were dropped. The new shape of the combined dataset can be observed below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*IX7TvJ-9heq1q_yXn6sglQ.png" /></figure><p><strong>3.5 Feature Processing</strong></p><p>We have a business question that aims to answer whether the age of the startup affects funding. Hence, we need to add a new column that calculates this age by subtracting the funding year from the year the startup was founded. The new column was achieved using the code below and the resulting columns are as observed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*UWYsODjG0SXPX0T8zYLS_w.png" /></figure><p><strong>4. MODELING</strong></p><p><strong>4.1 Visualization</strong></p><p><strong>4.2 Univariate Analysis</strong></p><p><strong>4.2.1 Analysis of the Amount attribute</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*vb01bXbVXC46BTQvbE7odQ.png" /></figure><p>Started with calculating statistical measures like Mean, Median, Mode, etc. These statistical measures will provide insights into the central tendency and distribution of the data in the ‘Amount’ column.</p><p>The histogram of the Amount column is visualized below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*L4gKDrkQu-bEFJAHBPe-vQ.png" /><figcaption>Figure 1: Frequency of amount attribute</figcaption></figure><p>The distribution plot shows in detail the skewness of the Amount attribute of the dataset, and it indicates a positively skewed distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*9dnNlUWB7I4XU7F_eOargw.png" /><figcaption>Figure 2. Distribution of amount attribute</figcaption></figure><p>The box plot showed existing outliers in the Amount column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*yC0P1JpqZFwxmSmcB_VeoQ.png" /><figcaption>Figure 3. Boxplot with outliers</figcaption></figure><p>Boxplot after removing the outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*THIRlkSi5OWVfMYNInYs1A.png" /><figcaption>Figure 4. Boxplot after removing outliers.</figcaption></figure><p>This was handled using the IQR approach as observed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*jC1p5S3Y0MT1wuWZslNRhw.png" /></figure><p>Handling outliers with the Interquartile Range (IQR) approach is a common method used in data analysis to identify and deal with extreme values that lie far from the central distribution of the data. It’s important to note that the IQR approach is just one of many methods to handle outliers. Depending on the context and the nature of your data, other methods, such as z-score, modified z-score, or domain-specific knowledge, may also be applied. Handling outliers effectively ensures that your analysis is more robust and accurate, and it helps avoid skewed results due to extreme values.</p><p><strong>4.2.2 Analysis of the Sector Attribute</strong></p><p>Since the stage is a categorical column, I visualized only the first five stages. It can be observed that 48.9% of startups, which is almost half are funded at the seed stage. It is the initial phase of the company’s development, where the founders or entrepreneurs work on turning their idea into a viable business. During the seed stage, the focus is on laying the foundation for the business and securing the necessary resources to begin operations. At the seed stage funding typically comes after the initial startup capital, and often comes from the founders’ own savings or contributions from friends and family.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*5HBspAtKU_ExnN9GWq4b4Q.png" /><figcaption>Figure 5. Stage distribution</figcaption></figure><p><strong>4.2.3 Analysis of the Sector Attribute</strong></p><p>The sector is also categorical and I visualized the first 5 sectors. It can be observed that the top five sectors are Technology, Finance and Education, Healthcare, and E-commerce sectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*cPklLY3jTOCxw2XJ4tA1Cw.png" /><figcaption>Figure 6. Sector distribution</figcaption></figure><p><strong>4.2.4 Analysis of the location attribute</strong></p><p>I also visualized the top 5 locations according to the number of startups they have. It can be observed that Bangalore holds almost half of the startups followed by Mumbai and New Delhi cities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*MrRwt7LYp0VIhJy5sxf7pg.png" /><figcaption>Figure 7. Headquarters distribution</figcaption></figure><p><strong>4.2.5 Analysis of the investor attribute</strong></p><p>In the categorical attribute representing investors, I visualized the top 10 investors who provide funding to the highest number of startups in India. Among them, Inflection Point Ventures stands out as the most prominent investor, holding about 50% of the total investment portfolio. This indicates that Inflection Point Ventures is a major player in the Indian startup ecosystem, supporting a significant share of funded startups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*V_Fd4t7cY_Ydo1LUZR6oCQ.png" /><figcaption>Figure 8. Investor Distribution</figcaption></figure><p><strong>4.2.6 Analysis of the founded attribute</strong></p><p>Used a line chart to visualize the years in which startups were established. It can be observed that most startups were started in 2016 which could be a result of imputing the missing values in the 2018 dataset with mode. we can deduce that between 2011 and 2016 the number of startups rose steadily within a plateau of about 600 startups in 2016. Numbers then declined in 2017 before rising steadily and again declining in 2020 with only 59 startups recorded in 2021.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*HA9d844Wb8wTA7Rg0GWiQw.png" /><figcaption>Figure 9. The number of startups founded each year.</figcaption></figure><p><strong>4.3 BIVARIATE ANALYSIS</strong></p><p><strong>4.3.1 Relationship between sector and amount raised.</strong></p><p>we can see that the average amount raised for most sectors is below $ 3000000. However, other sectors such as Finance. E-commerce and health have higher amounts raised above $3500000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*k0to4TN0Vwn5ELUE3vBsOg.png" /><figcaption>Figure 10. Relationship between sector and amount attributes</figcaption></figure><p><strong>4.3.2 Relationship between stage and amount raised.</strong></p><p>we can see that the average amount raised in most stages is below $2000000, with the highest amounts raised at the series C, series B, and series A stages, as well as later stages and debt financing. we can deduce that at series C a startup has likely achieved significant growth and success, which makes it more appealing to investors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*O1St53gI6EWGx3WuHIJXwQ.png" /><figcaption>Figure 11. Relationship between stage and amount attributes</figcaption></figure><p><strong>4.4 MULTIVARIATE ANALYSIS</strong></p><p>For multivariate analysis, I investigated the correlation between numeric attributes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*L6iKd5VuPpGUTZfWLukgPg.png" /></figure><p>This resulted in the output below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*7I-U5AVXuEgiaS1MM2w_0g.png" /><figcaption><strong>Figure 12. heatmap showing the relationship between numeric attributes</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*RMaNEQTWfvFcHmXmN1dcIg.png" /></figure><p>As it can be observed the amount raised is more correlated to the age of the startup.</p><p><strong>5. EVALUATION</strong></p><p><strong>5.1</strong> <strong>Answering the business questions</strong></p><p><strong>5.1.1 To what extent do cities influence funding?</strong></p><p>I needed to identify the top 10 locations (cities) in the dataset that received the most funding for startups, based on the cumulative funding amount in the ‘Amount($)’ column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*AjbcjPxvCaFHwFXt1IUVSw.png" /></figure><p>The output result can be observed below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*LEspY19Ih7Cp21NLm_1RLg.png" /></figure><p>The results are visualized below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*tzQFx3098k97bkUOFuffaw.png" /><figcaption>Figure 13. Top 5 locations with the highest amount funded</figcaption></figure><p>Bangalore is leading when it comes to startup funding with about $2,741,151,000 in total investments and is the third largest city in India with a population of about 8,443,675. Mumbai, which is the largest city follows closely with about $1,241,584,000 total investments.</p><p><strong>5.1.2</strong> <strong>Which Sectors are preferred by investors for funding?</strong></p><p>I needed to show the top 5 stages along with their respective counts. Sectors with a significant number of startups are particularly attractive to investors. This indicates that the sector has shown success in fundraising, and investors see the potential for continued growth and development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*u-jbVauqoBA05flFHD8cyA.png" /></figure><p>The top 5 sectors are as visualized below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*YDmoTwYE51R-YJALyrsUSw.png" /><figcaption>Figure 14. Top 5 sectors preferred for funding</figcaption></figure><p>Technology is the most preferred sector with about 32.8% startups followed by Finance with 24.7% established startups. Education, healthcare, and e-commerce are also preferred with 16.7%, 16.5%, and 9.2% startups respectively.</p><p><strong>5.1.3</strong> <strong>At which stage do start-ups get more funding from investors?</strong></p><p>I needed to identify the top 5 stages in the dataset that received the most funding for startups, based on the cumulative funding amount in the ‘Amount($)’ column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*84UyHt7VQ59qNcMdC_RE6g.png" /></figure><p>The output is as seen below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*b1ehp_DQFxp5FJ8LE_KbVg.png" /></figure><p>The top 5 stages are visualized below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*0UqZRIWYNfBbo--3awd7Pw.png" /><figcaption>Figure 15. Top 5 stages with the highest amount funded</figcaption></figure><p>we can see at the series A stage startups raise the highest amounts. The high amount is because, at series A, the startup has typically demonstrated some market traction, has a minimum viable product (MVP), and has gained initial customers. we can also see that a high amount is raised at the seed stage as startups typically seek funding from angel investors, friends, and family, and sometimes venture capital firms that focus on early-stage investments. lastly, we can also see that a significant amount is raised at the series B, Pre-series, and series C stages.</p><p><strong>5.1.4</strong> <strong>What is the typical funding amount that startups receive in India?</strong></p><p>I needed to identify the typical funding of startups by looking at the sectors in the dataset that received the most funding for startups, based on the cumulative funding amount in the ‘Amount($)’ column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*beHZFpOPU1r-q6jufNxBeQ.png" /></figure><p>The output is as follows;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*GrUD_6fkt5G9JusY_ytf9Q.png" /></figure><p>The funding of the top 5 sectors is visualized below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*byzCr9T2Hht3pcTm85TRnw.png" /><figcaption>Figure 16. Typical funding of startups</figcaption></figure><p>In the Indian startup, the typical funding amount varies across sectors, where finance and technology receive the highest amounts of about $1,474,923,000 and $1,271,999,000 respectively. on the other hand, healthcare, education, and e-commerce also receive significant amounts of funding. other sectors such as hospitality, sports, and engineering sectors are the least funded with amounts of less than $29,380,000.</p><p><strong>5.1.5</strong> <strong>Which type of investors invest the most money?</strong></p><p>I needed to identify the top 5 investors in the dataset with the highest investments for startups, based on the cumulative funding amount in the ‘Amount($)’ column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*fhVBpKHGFaFyuE2jCkseNQ.png" /></figure><p>The output is as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*mrdBnzguCrd1pMUFbAZJOQ.png" /></figure><p>The visualization of the top 5 investors is as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*h56zWXoy_mnjqBIyM-h62A.png" /><figcaption>Figure 17. Investors who invest the most money</figcaption></figure><p>Inflection Point Ventures are the top investor with about $124,925,000 in investments, followed by venture catalysts and Elevation capital with $85,000,000 and $41,100,000 investments respectively. Mumbai Angels Network and Chiratae Ventures have also invested $34,113,500 and $32,700,000 respectively.</p><p><strong>5.1.6</strong> <strong>Can the age of the startup affect the amount received from investors?</strong></p><p>I needed to identify the top 5 startup ages in the dataset with the highest funding, based on the cumulative funding amount in the ‘Amount($)’ column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*TgroBqcu0hu9J2wM1mg00g.png" /></figure><p>The output is as follows;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*e_FKlwQq17ptytfzhQ1DPA.png" /></figure><p>The top 10 ages with the highest funding are as visualized below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*bSQ5GJDZsD8wK4-Cvg3orw.png" /><figcaption>Figure 18. Age of the startup vs amount received from investors</figcaption></figure><p>Although the relationship is complex, we can see that most startups are highly funded between 1 and 5 years of establishment.</p><p><strong>5.2 Hypothesis:</strong></p><p>Null: The location of a startup doesn’t affect the amount of funding received from investors.</p><p>Alternate: the location of a startup significantly affects the amount of funding issued by investors.</p><p>To test the hypothesis, I applied the Kruskal-Wallis test, which is a non-parametric statistical test used to compare the distribution of data from two or more independent groups. It is used as an alternative to the one-way ANOVA test when the assumptions of normality and equal variances are not met, or when the data is ordinal or not normally distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*xnbRVWaBJUzXDJkQm18URA.png" /></figure><p>In this code, the data in the ‘Amount($)’ column is grouped by the ‘Location’ column using the ‘groupby’ function. The Kruskal-Wallis test is then performed on these grouped samples using the kruskal function from the scipy.stats module.</p><p>The resulting p-value indicates the level of significance for the test. If the p-value is less than the chosen significance level (e.g., 0.05), it suggests that there is a significant difference between the groups in terms of the amount raised. If the p-value is greater than the significance level, it indicates that there is no significant difference between the groups in terms of the amount raised.</p><p>The output is as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*OuI8EE-bq2A8q9hWjyQTHQ.png" /></figure><p>we, therefore, reject the null hypothesis and conclude that the location of a business affects the amount of funding issued by investors.</p><p><strong>6.1</strong> <strong>Deployment</strong></p><p>After completing the data mining process and analyzing the dataset of startup funding from (2018–2021), I obtained insightful results regarding the relationship between the location of a startup and the amount received from investors.</p><p><strong>Hypothesis Testing Results:</strong></p><p>I performed a statistical analysis using the Kruskal-Wallis test to examine the potential impact of a startup’s location on the funding amount. The Kruskal-Wallis test is a non-parametric method suitable for comparing multiple independent groups when the data does not meet the assumptions of traditional parametric tests.</p><p><strong>Hypothesis:</strong></p><p>Null Hypothesis (H0): The location of a startup has no significant effect on the amount received from investors.</p><p>Alternative Hypothesis (H1): The location of a startup significantly influences the amount received from investors.</p><p><strong>Analysis:</strong></p><p>Based on the Kruskal-Wallis test results, we observed a significant difference in the amount raised among different startup locations (p &lt; 0.05). Therefore, we reject the null hypothesis (H0) and accept the alternative hypothesis (H1), suggesting that the location of a startup does affect the amount of funding received from investors.</p><p><strong>Conclusions:</strong></p><p>The data clearly indicate that the geographic location of a startup plays a crucial role in determining the funding it receives. Certain locations demonstrate a higher tendency to attract more significant investments, while others might face challenges in attracting substantial funding.</p><p><strong>Recommendations:</strong></p><p>These findings offer valuable insights to potential investors and startup founders alike. Investors may consider directing their attention to locations that have shown to be more favorable for funding such as Bangalore, Mumbai, and Gurugram, potentially maximizing their investment opportunities. On the other hand, startup founders may strategize their business plans to take advantage of the funding trends in specific regions, increasing their chances of securing substantial financial backing.</p><p><strong>Limitations:</strong></p><p>While our analysis presents compelling evidence for the impact of startup location on funding, it is essential to acknowledge the limitations of the study. The dataset used for this analysis may not encompass all startups in the Indian ecosystem, and there might be other unaccounted factors influencing funding decisions. Additionally, the results are based on historical data and may not fully predict future funding trends.</p><p><strong>Further Research:</strong></p><p>To deepen our understanding of the relationship between startup location and funding, future research could explore additional factors that contribute to this phenomenon. Conducting surveys and interviews with investors and startup founders may provide valuable qualitative insights to complement the quantitative analysis.</p><p>In the deployment section, it’s important to summarize your findings clearly, acknowledge any limitations, and offer practical recommendations based on the results. Keep in mind that your deployment report should be tailored to your specific analysis and audience, providing actionable insights for stakeholders and decision-makers.</p><p>Read more in my notebook:</p><p><a href="https://github.com/phinmaiyo/India-startup-ecosytem-analysis">https://github.com/phinmaiyo/India-startup-ecosytem-analysis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8c9df3eb9ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>