<?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 Fiifi Abassah-Konadu on Medium]]></title>
        <description><![CDATA[Stories by Fiifi Abassah-Konadu on Medium]]></description>
        <link>https://medium.com/@fiifi.abassah?source=rss-a6608f8cb1f9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*M8--5-mV5DFiKuxh</url>
            <title>Stories by Fiifi Abassah-Konadu on Medium</title>
            <link>https://medium.com/@fiifi.abassah?source=rss-a6608f8cb1f9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 02:59:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fiifi.abassah/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[Sepsis Prediction API with FastAPI]]></title>
            <link>https://medium.com/@fiifi.abassah/sepsis-prediction-api-with-fastapi-2519851a1b8d?source=rss-a6608f8cb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2519851a1b8d</guid>
            <dc:creator><![CDATA[Fiifi Abassah-Konadu]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 00:21:06 GMT</pubDate>
            <atom:updated>2023-11-08T00:21:06.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*-1dG84VYOhbCMR8bALYsXQ.jpeg" /><figcaption>Source:<a href="https://www.educba.com/predictive-modeling/">https://www.educba.com/predictive-modeling/</a></figcaption></figure><p>Building a machine learning model is just one aspect of the process. For it to be practical in real-world applications, it needs to be accessible to users and developers. One widely adopted method for deploying machine learning models is by encapsulating them in a REST API, and in this case, we’ll be using FastAPI.</p><p>Sepsis is a critical medical condition that demands swift diagnosis and intervention (Manning, 2021). The model at the core of this project has been meticulously trained to provide precise predictions, which can be invaluable in assisting healthcare professionals in making timely and well-informed decisions. The full spectrum of components, including Exploratory data analysis, Data Processing, Model building, and the dataset, is available in my GitHub repository.</p><p>The primary objective of this undertaking is to establish a Sepsis Prediction API using FastAPI. The ultimate goal is to develop an efficient, user-friendly, and well-documented API that harnesses machine learning models to forecast the probability of sepsis based on input parameters. This API is hosted on Hugging Face, making it easily accessible and integrable. You can engage with the API by visiting [link here].</p><p>FastAPI, as per the official documentation, is a contemporary and high-performance web framework designed for crafting APIs with Python 3.6+ (“FastAPI,” 2022). In terms of performance, it can compete with technologies like NodeJS and Go. What’s more, it boasts a gentle learning curve and comes with built-in interactive documentation.</p><p>Getting the Environment Ready:</p><p>Our journey commences with the creation of a Python virtual environment, which helps isolate the project’s dependencies. This is crucial for preventing clashes with other projects and ensuring that the project operates with the specific library versions required. To create and activate this virtual environment, follow these steps:</p><pre># To create the virtual environment<br>python -m venv venv<br># To activate it<br>venv\Scripts\activate</pre><p>We’ll go on to install the necessary libraries from our requirements file</p><pre># To upgrade pip<br>python -m pip install -q --upgrade pip<br># To install the dependencies in the requirements file<br>python -m pip install -qr requirements.txt</pre><p>Next we import the necessary libraries and set up our FastAPI instance. The machine learning components, including a trained model, scaler, and label encoder, are loaded using a function (`Ml_loading_components`) from a saved file.</p><pre># Importations<br>from typing import Union<br>from fastapi import FastAPI<br>import pickle<br>import pandas as pd<br>import os<br>from fastapi import HTTPException, status<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import LabelEncoder<br><br># Setup Section<br># Create FastAPI instance<br>app = FastAPI(title=&quot;Sepsis Prediction API&quot;, description=&quot;API for Predicting Sepsis&quot;)<br># Load machine learning components<br>ml_components_dict = Ml_loading_components(fp=ml_core_fp)<br>label_encoder = ml_components_dict[&#39;label_encoder&#39;]<br>scaler = ml_components_dict[&#39;scaler&#39;]<br>model = ml_components_dict[&#39;model&#39;]</pre><h4>Input Data</h4><p>We’ll be using the <a href="https://docs.pydantic.dev/">pydantic</a> library for the data validation layer of our API. This library plays a crucial role in safeguarding the API against erroneous parameter inputs by users.</p><pre>from pydantic import BaseModel<br>class InputData(BaseModel):<br>    PRG: int<br>    PL: int<br>    BP: int<br>    SK: int<br>    TS: int<br>    BMI: float<br>    BD2: float<br>    Age: int</pre><h4>Prediction Endpoint</h4><p>We’ve defined a FastAPI endpoint, “/predict” which is designed to accept HTTP POST requests. When a request is made to this endpoint, the “predict” function is triggered. This function anticipates user inputs, adhering to the specifications outlined in the “InputData” class mentioned earlier.</p><pre># Create prediction endpoint<br>@app.post(&quot;/predict&quot;)<br>def predict(df: InputData):</pre><h4>Structure and Preprocess the Inputs</h4><p>The data provided by the user will be received and converted into a Pandas DataFrame, maintaining a structure similar to the one used in the notebook. Subsequently, we’ll proceed with the essential preprocessing steps, which include encoding, scaling, and imputing missing values. For scaling, we’ll utilize the preloaded scaler we previously stored while constructing the model.</p><pre># Prepare the feature and structure them like in the notebook<br>    df = pd.DataFrame([df.dict().values()],columns=df.dict().keys())<br>    print(f&quot;[Info] The inputed dataframe is : {df.to_markdown()}&quot;)<br>    <br>    # Scaling the inputs<br>    df_scaled = scaler.transform(df)</pre><h4>Make Prediction</h4><p>To make predictions based on the scaled input data, we’ll employ the loaded machine learning model.</p><pre># Prediction<br>raw_prediction = model.predict(df_scaled)</pre><h4>Prediction Results</h4><p>Based on the prediction result, the API will generate the appropriate HTTP responses. If the prediction yields a value of 0 or 1, a success response will be raised accordingly. However, if the prediction falls outside of this range, a server error response will be raised.</p><pre>if raw_prediction == 0:<br>    raise HTTPException(status_code=status.HTTP_200_OK, detail=&quot;The patient does not have Sepsis&quot;)<br>elif raw_prediction == 1:<br>    raise HTTPException(status_code=status.HTTP_200_OK, detail=&quot;The patient has Sepsis&quot;)<br>else:<br>    raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=&quot;Prediction E</pre><h4>Run FastAPI using Uvicorn</h4><p>We’ve implemented a block of code that initiates the FastAPI application using Uvicorn when the script is executed directly. This sets up the app to run on the host “127.0.0.1,” making it externally accessible, and on port 8000. The “reload=True” flag is enabled, allowing for automatic code reloading, which is particularly useful during the development phase.</p><pre>if __name__ == &quot;__main__&quot;:<br>    uvicorn.run(&quot;main:app&quot;, host=&quot;127.0.0.1&quot;, port=8000, reload=True)</pre><h4>Dockerizing the API</h4><p>To ensure a consistent and isolated environment, we containerize our FastAPI application using Docker. The Dockerfile specifies the base image, sets up the working directory, installs dependencies, and runs the FastAPI application. You can access the dockerfile <a href="https://github.com/Newton23-nk/Sepsis-Prediction-FastApi/blob/main/Dockerfile">here.</a></p><pre># Specifying the base image<br>FROM python:3.11<br># Set the working directory to /Sepsis<br>WORKDIR /Sepsis<br> <br># Copy the current directory contents into the container at /Sepsis<br>COPY ./requirements.txt /Sepsis/requirements.txt<br> <br># Install requirements.txt <br>RUN pip install --no-cache-dir --upgrade -r /Sepsis/requirements.txt<br> <br># Set up a new user named &quot;user&quot; with user ID 1000<br>RUN useradd -m -u 1000 user<br># Switch to the &quot;user&quot; user<br>USER user<br># Set home to the user&#39;s home directory<br>ENV HOME=/home/user \<br>    PATH=/home/user/.local/bin:$PATH<br> <br># Set the working directory to the user&#39;s home directory<br>WORKDIR $HOME/app<br> <br># Copy the current directory contents into the container at $HOME/app setting the owner to the user<br>COPY --chown=user . $HOME/app<br> <br># Start the FastAPI app on port 7860, the default port expected by Spaces<br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;127.0.0.1&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>The Dockerfile has been tailored to construct a containerized environment suitable for running a FastAPI application. It guarantees the installation of all required dependencies and ensures that the app operates under a non-root user, enhancing security and isolation.</p><h4>Testing and Running the API Locally</h4><pre># To build a docker image<br> docker build -t fastapi-app </pre><p>After creating the Docker container as per the Dockerfile, we can proceed to run the container locally for testing the API. This allows us to check the functionality of the API within the controlled container environment.</p><pre># To run the container<br> docker run -it -p 8000:7860 fastapi-app</pre><h4>Endpoint Access and Results</h4><p>Once the Docker container is running, you can access the API at <a href="http://127.0.0.1:8000/docs">http://127.0.0.1:8000/docs</a> and make predictions by sending POST requests to the `/predict` endpoint.</p><h4>Conclusion</h4><p>With this project, access to our machine learning model has been opened up and we can now use it in more practical settings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2519851a1b8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis App with Gradio]]></title>
            <link>https://medium.com/@fiifi.abassah/sentiment-analysis-app-with-streamlit-d6e87e140a13?source=rss-a6608f8cb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6e87e140a13</guid>
            <dc:creator><![CDATA[Fiifi Abassah-Konadu]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 18:28:13 GMT</pubDate>
            <atom:updated>2023-10-10T08:18:00.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Jq1VukTWETw173oX4f48w.png" /></figure><h3>Introduction</h3><p>Sentiment Analysis is an important feat that can be accomplished with machine learning. What is sentiment analysis you ask? <a href="https://aws.amazon.com/what-is/sentiment-analysis/#:~:text=Sentiment%20analysis%20is%20the%20process,social%20media%20comments%2C%20and%20reviews.">Sentiment analysis is the process of analyzing digital text to determine if the emotional tone of the message is positive, negative, or neutral</a>. Social media is a good place to get text to analyse, where discussions regarding a trending issue usually have a spectrum of emotional tones. One such topic is the COVID-19 virus and particularly, the vaccines prescribed by health bodies worldwide for managing the COVID-19 pandemic. This project seeks to offer insights into public opinions regarding vaccines using machine learning models. We will fine-tune an existing Huggingface model to classify tweets as positive, neutral or negative.</p><h3>Data Understanding</h3><p>Below are the relevant libraries that were imported to be used throughout the project</p><pre>##for handling path of my datasets<br>import os<br>from google.colab import drive<br><br>##for data handling:<br>import pandas as pd<br>import numpy as np<br>from datasets import load_dataset<br>from sklearn.model_selection import train_test_split<br><br>##for visualization<br>import matplotlib.pyplot as plt<br>from collections import Counter<br>from wordcloud import WordCloud<br>import neattext.functions as nfx<br>import re<br><br>##modelling:<br>import nltk<br>from nltk.corpus import stopwords<br>import string<br>from transformers import AutoTokenizer<br>from transformers import AutoModelForSequenceClassification<br>from sklearn.metrics import mean_squared_error<br>from datasets import load_metric<br>from sklearn.metrics import f1_score<br></pre><pre>df_train = pd.read_csv(&#39;/content/NLP-Sentiment-Analysis/data/Train.csv&#39;)<br>df_test = pd.read_csv(&#39;/content/NLP-Sentiment-Analysis/data/Test.csv&#39;)<br><br># A way to eliminate rows containing NaN values<br>df_train = df_train[~df_train.isna().any(axis=1)]<br><br># A way to eliminate rows containing NaN values<br>df_test = df_test[~df_test.isna().any(axis=1)]</pre><p>The data on which the model will be trained was sourced from Zindi Africa. The tweets were classified as pro-vaccine (1), neutral (0) or anti-vaccine (-1) and the usernames and web addresses were removed. Below is a description of the variables</p><ul><li>tweet_id: Unique identifier of the tweet</li><li>safe_tweet: Text contained in the tweet. Some sensitive information has been removed like usernames and urls.</li><li>label: Sentiment of the tweet (-1 for negative, 0 for neutral, 1 for positive)</li><li>agreement: The tweets were labeled by three people. Agreement indicates the percentage of the three reviewers that agreed on the given label. You may use this column in your training, but agreement data is not to be shared for the test set.</li></ul><h4>Exploratory Data Analysis</h4><p>After data was loaded into our data frame, we proceeded with an exploratory data analysis (EDA) phase. During this phase, we conducted initial data inspections, including examining a random sample of 5 rows using train_data.sample(5), checking the dataset information using .info(), reviewing label counts, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*wET650crY7-mdtihznRrQw.jpeg" /></figure><p>We constructed some visualisations to understand the data better.</p><pre># Plot the distribution of &#39;agreement&#39;<br>plt.hist(train_data[&#39;agreement&#39;])<br>plt.xlabel(&#39;Agreement&#39;)<br>plt.ylabel(&#39;Count&#39;)<br>plt.title(&#39;Distribution of Agreement&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*-SzMrvUPyjrODDSzjp1lMA.jpeg" /></figure><p>A word map to find out the words which appear the most.</p><pre>#Having a word count<br><br># Concatenate all the &#39;safe_text&#39; into a single string<br>text = &#39; &#39;.join(train_data[&#39;safe_text&#39;])<br><br># Split the text into words<br>words = text.split()<br><br># Count the frequency of each word<br>word_counts = Counter(words)<br><br># Display the most common words<br>print(word_counts.most_common(10))<br><br># Generate the word cloud with a white background<br>cloud_two_cities = WordCloud(width=800, height=400, background_color=&#39;white&#39;).generate(text)<br><br># Display the word cloud<br>plt.figure(figsize=(8, 5))<br>plt.imshow(cloud_two_cities, interpolation=&#39;bilinear&#39;)<br>plt.axis(&#39;off&#39;)<br>plt.tight_layout(pad=1)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*L7CdMEQApNLghM7TVs5Dfw.jpeg" /></figure><h4>Data Preparation</h4><p>In preparing the data set, we performed the following</p><ul><li>Checking for missing values</li></ul><pre>#Checking for missing values<br>data=[train_data, test_data]<br>names=[&quot;df_train&quot;, &quot;df_test&quot;]<br><br>for m, i in zip(data, names):<br>  print(f&quot;the missing values in the&quot;, i,&quot;dataset are: &quot;, &quot;\n\n&quot;, m.isna().sum(), &quot;\n\n&quot;, &quot;---&quot;*20 )<br><br>#check for duplicates<br>train_data.duplicated().sum()</pre><ul><li>Remove URLs and special characters</li></ul><pre># Clean the &#39;safe_text&#39; column (example: remove URLs and special characters)<br>train_data[&#39;safe_text&#39;] = train_data[&#39;safe_text&#39;].str.replace(r&#39;&lt;url&gt;&#39;, &#39;&#39;)  # Remove &lt;url&gt; tag<br>test_data[&#39;safe_text&#39;] = test_data[&#39;safe_text&#39;].str.replace(r&#39;&lt;url&gt;&#39;, &#39;&#39;)  # Remove &lt;url&gt; tag<br><br># Remove emojis and other special characters<br>emojis = re.compile(r&#39;[^\w\s@#$%^*()&lt;&gt;/|}{~:&amp;]&#39;)<br>train_data[&quot;safe_text&quot;] = train_data[&quot;safe_text&quot;].str.replace(emojis, &#39;&#39;)<br>test_data[&quot;safe_text&quot;] = test_data[&quot;safe_text&quot;].str.replace(emojis, &#39;&#39;)<br><br># # Remove punctuation<br>punctuation = string.punctuation<br>train_data[&quot;safe_text&quot;] = train_data[&quot;safe_text&quot;].str.translate(str.maketrans(&#39;&#39;, &#39;&#39;, punctuation))<br>test_data[&quot;safe_text&quot;] = test_data[&quot;safe_text&quot;].str.translate(str.maketrans(&#39;&#39;, &#39;&#39;, punctuation))<br><br># remove hashtags<br>train_data[&#39;safe_text&#39;] = train_data[&#39;safe_text&#39;].apply(nfx.remove_hashtags)<br>test_data[&#39;safe_text&#39;] = test_data[&#39;safe_text&#39;].apply(nfx.remove_hashtags)</pre><ul><li>Convert all text to lowercase and remove multiple white spaces</li></ul><pre># Turn the safe_text column into lowercase<br>train_data[&quot;safe_text&quot;] = train_data[&quot;safe_text&quot;].str.lower()<br>test_data[&quot;safe_text&quot;] = test_data[&quot;safe_text&quot;].str.lower()<br><br># remove multiple white spaces<br>def stripSpace(text):<br>    return text.strip()<br>train_data[&#39;safe_text&#39;] = train_data[&#39;safe_text&#39;].apply(nfx.remove_multiple_spaces)<br>train_data[&#39;safe_text&#39;] = train_data[&#39;safe_text&#39;].apply(stripSpace)</pre><ul><li>Remove “RT” and user handles</li></ul><pre># remove RT and user handles<br>def removeRT(text):<br>    return text.replace(&quot;RT&quot; , &quot;&quot;)<br>train_data[&#39;safe_text&#39;] = train_data[&#39;safe_text&#39;].apply(lambda x: nfx.remove_userhandles(x))<br>train_data[&#39;safe_text&#39;] = train_data[&#39;safe_text&#39;].apply(removeRT)</pre><ul><li>Remove stop words (words that are so commonly used that they carry very little information)</li></ul><pre># Remove stop words<br>stop_words = set(stopwords.words(&#39;english&#39;))<br>train_data[&#39;safe_text&#39;] = train_data[&#39;safe_text&#39;].apply(lambda x: &#39; &#39;.join([word for word in x.split() if word.lower() not in stop_words]))<br>test_data[&#39;safe_text&#39;] = test_data[&#39;safe_text&#39;].apply(lambda x: &#39; &#39;.join([word for word in x.split() if word.lower() not in stop_words]))<br><br><br>#REMOVING STOPWORDS<br># Download the stop words (only required for the first time)<br>nltk.download(&#39;stopwords&#39;)</pre><h3>Modelling</h3><p>We first split the train and test datasets using train_test_split</p><pre># Split the train data =&gt; {train, eval}<br>train, eval = train_test_split(df, test_size=0.2, random_state=42, stratify=df[&#39;label&#39;])</pre><p>As mentioned earlier, for this project, we’ll be fine-tuning an existing model. When we talk about fine-tuning a model, we’re referring to taking an already pre-trained model and training it further so it performs better on a specific task. For this sentiment analysis, we will be fine-tuning language models from Huggingface (a popular machine-learning hosting site). The models we will be using have been extensively trained on large bodies of text data and are useful for tasks such as text generation, sentiment analysis and many others. Below are the models we will be fine-tuning</p><ul><li>DistilBert from Huggingface</li><li>Roberta from Facebook</li><li>xlnet-bert-case from Huggingface</li></ul><p>To be able to evaluate the performance of our models after fine-tuning, we will split our datasets into training and evaluation data.</p><pre>dataset = load_dataset(&#39;csv&#39;,<br>                        data_files={&#39;train&#39;: &#39;/content/NLP-Sentiment-Analysis/data/train_subset.csv&#39;,<br>                        &#39;eval&#39;: &#39;/content/NLP-Sentiment-Analysis/data/eval_subset.csv&#39;}, encoding = &quot;ISO-8859-1&quot;)</pre><p>Next is to tokenize the data, which means breaking the sentences into their individual words.</p><pre>#Setting up our tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(&quot;distilbert-base-uncased&quot;)</pre><p>We also created a function to map the label transformation. -1 becomes 0, 0 becomes 1 and 1 becomes 2.</p><pre># Function to transform labels<br>def transform_labels(label):<br><br>    label = label[&#39;label&#39;]<br>    num = 0<br>    if label == -1: #&#39;Negative&#39;<br>        num = 0<br>    elif label == 0: #&#39;Neutral&#39;<br>        num = 1<br>    elif label == 1: #&#39;Positive&#39;<br>        num = 2<br><br>    return {&#39;labels&#39;: num}<br><br># Function to tokenize data<br>def tokenize_data(example):<br>    return tokenizer(example[&#39;safe_text&#39;], padding=&#39;max_length&#39;)<br><br># Change the tweets to tokens that the models can exploit<br>dataset = dataset.map(tokenize_data, batched=True)<br><br># Transform labels and remove the unwanted columns<br>remove_columns = [&#39;tweet_id&#39;, &#39;label&#39;, &#39;safe_text&#39;, &#39;agreement&#39;]<br>dataset = dataset.map(transform_labels, remove_columns=remove_columns)</pre><h4>Fine-tuning</h4><p>Create your training arguments; most importantly the number of times the model should go over the dataset also known as epoch.</p><pre>from transformers import TrainingArguments<br><br># Configure the training parameters like `num_train_epochs`:<br># the number of time the model will repeat the training loop over the dataset<br>training_args = TrainingArguments(<br>    &quot;Sentiment-Analysis-Model&quot;,<br>    num_train_epochs=10,<br>    load_best_model_at_end=True,<br>    evaluation_strategy=&quot;steps&quot;,<br>    save_strategy=&quot;steps&quot;,<br>    push_to_hub=True<br>    )</pre><p>Load your pre-trained model and apply your random seed to the train and evaluation data. The random seed ensures your results are reproducible</p><pre># Loading a pretrain model while specifying the number of labels in our dataset for fine-tuning<br>model = AutoModelForSequenceClassification.from_pretrained(&quot;distilbert-base-uncased&quot;, num_labels=3)<br><br>train_dataset = dataset[&#39;train&#39;].shuffle(seed=10) #.select(range(40000)) # to select a part<br>eval_dataset = dataset[&#39;eval&#39;].shuffle(seed=10)</pre><p>We also define our evaluation parameters, using the F1 score since we are dealing with a classification dataset.</p><pre>def compute_f1_score(pred):<br>    labels = pred.label_ids<br>    preds = np.argmax(pred.predictions, axis=1)<br>    f1 = f1_score(labels, preds, average=&quot;weighted&quot;)<br>    return {&quot;f1_score&quot;: f1}</pre><p>Now to the actual training, we import the Trainer and initiate our training.</p><pre>from transformers import Trainer<br><br><br># Model Training Setup<br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=train_dataset,<br>    eval_dataset=eval_dataset,<br>    tokenizer=tokenizer,<br>    compute_metrics=compute_f1_score,<br>)<br><br># Launch the learning process: training<br>trainer.train()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*tJxBiOQPacYSP3deLlx04A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eYlMNp-DDdzg05R2-tQQlw.jpeg" /></figure><h3>Deployment</h3><p>For easy use, we created a Streamlit app to which we connected our fine-tuned model. Our fine-tuned model was also uploaded to HuggingFace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pTJiyA7WaVhmoLaOlLqCQ.png" /></figure><h3>Conclusion</h3><p>The Sentiment Analysis App, powered by the distilbert-uncased model, enables individuals to perform instant sentiment assessment, providing insightful glimpses into the emotional tone of text information. The app has a very simple layout, users from various backgrounds can easily tap into the potential of Natural Language Interpretation without needing into extensive technical knowledge .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6e87e140a13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning App with Streamlit]]></title>
            <link>https://medium.com/@fiifi.abassah/machine-learning-app-with-streamlit-4823a5fe055b?source=rss-a6608f8cb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4823a5fe055b</guid>
            <dc:creator><![CDATA[Fiifi Abassah-Konadu]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 10:20:27 GMT</pubDate>
            <atom:updated>2023-08-28T07:50:58.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vjxts6ma3us2Xvt5tZup0g.jpeg" /></figure><p>For this project, we will make use of another open-source Python package; Streamlit that allows us to share our machine learning models. In a world increasingly driven by data, the ability to transform raw information into meaningful insights is invaluable. Leveraging the capabilities of Streamlit, a cutting-edge Python library, I set out to develop a project that would not only simplify data exploration but also enable dynamic interaction with the underlying datasets.</p><p>Our project revolves around tackling the challenge of predicting the sales of a grocery store, taking into account an array of variables including the store’s locale, economic factors and interconnected attributes. Through scrutiny of historical sales data and relevant parameters, our code aims to deliver precise foresight into future sales trends. This predictive algorithm can serve as a guide for grocery owners, aiding in inventory planning, and workforce scheduling, leading to an elevation of overall profitability. The web-based application introduces an instinctive interface, allowing users to seamlessly input relevant information and conjure up real-time sales projections.</p><h3>App Building Overview</h3><p>The steps undertaken in building the app can be summarized as below</p><ol><li>Importing necessary Python libraries &amp; ML components (model, scaler &amp; encoder)</li><li>Creating Input fields</li><li>Converting received data into a pandas dataframe</li><li>Choosing categorical columns and numerical columns for encoding and scaling respectively</li><li>Apply imputers to handle missing data</li><li>Encoding and scaling the columns as mentioned in Step 4</li><li>Merging the encoded and scaled columns to a single dataframe</li><li>Running the pretrained model to make the predictions</li><li>Displaying the prediction.</li></ol><p>We shall go over the above implementation in detail below.</p><h4>Implementation</h4><ol><li>We first begin by loading the Python libraries which will be using. These are scikit-learn, pandas, numpy, pickle and streamlit. We also import our previously trained model and our encoder, scaler and imputer</li></ol><pre>import streamlit as st<br>import pickle<br>import numpy as np<br>import pandas as pd<br>import pickle<br><br>model = pickle.load(open(&quot;sales_model.pkl&quot;, &quot;rb&quot;))<br>encoder = pickle.load(open(&quot;encoder.pkl&quot;, &quot;rb&quot;))<br>scaler = pickle.load(open(&quot;scaler.pkl&quot;, &quot;rb&quot;))</pre><p>Pickle is a Python library that is used to cache Python objects. In this case, we used it to save our model as an object; which we are importing now. We also imported our encoder and scaler which were also saved in the same manner as the model.</p><p>2. Second stage is creating our input fields which our app user will interact with to feed data into the model for prediction. Streamlit has inbuilt features that allows creation of various types of input fields such as checkboxes, text input, etc.</p><pre># Inputs <br>date = st.date_input(&quot;Enter date&quot;)<br>store_nbr = st.number_input(&quot;Enter store number&quot;)<br>family = st.selectbox(&quot;Choose item family&quot;,(&#39;AUTOMOTIVE&#39;, &#39;BABY CARE&#39;, &#39;BEAUTY&#39;, &#39;BEVERAGES&#39;, &#39;BOOKS&#39;, &#39;BREAD/BAKERY&#39;, &#39;CELEBRATION&#39;, &#39;CLEANING&#39;, &#39;DAIRY&#39;, &#39;DELI&#39;, &#39;EGGS&#39;, &#39;FROZEN FOODS&#39;, &#39;GROCERY I&#39;, &#39;GROCERY II&#39;, &#39;HARDWARE&#39;, &#39;HOME AND KITCHEN I&#39;, &#39;HOME AND KITCHEN II&#39;, &#39;HOME APPLIANCES&#39;, &#39;HOME CARE&#39;, &#39;LADIESWEAR&#39;, &#39;LAWN AND GARDEN&#39;, &#39;LINGERIE&#39;, &#39;LIQUOR,WINE,BEER&#39;, &#39;MAGAZINES&#39;, &#39;MEATS&#39;, &#39;PERSONAL CARE&#39;, &#39;PET SUPPLIES&#39;, &#39;PLAYERS AND ELECTRONICS&#39;, &#39;POULTRY&#39;, &#39;PREPARED FOODS&#39;, &#39;PRODUCE&#39;, &#39;SCHOOL AND OFFICE SUPPLIES&#39;, &#39;SEAFOOD&#39;))     <br>on_promotion = st.selectbox(&#39;Is the item on promotion?&#39;,(&#39;0 - No&#39;, &#39;1 - Yes&#39;))<br>city = st.selectbox(&quot;Enter city&quot;,(&#39;Ambato&#39;, &#39;Babahoyo&#39;, &#39;Cayambe&#39;, &#39;Cuenca&#39;, &#39;Daule&#39;, &#39;El Carmen&#39;, &#39;Esmeraldas&#39;, &#39;Guaranda&#39;, &#39;Guayaquil&#39;, &#39;Ibarra&#39;, &#39;Latacunga&#39;, &#39;Libertad&#39;, &#39;Loja&#39;, &#39;Machala&#39;, &#39;Manta&#39;, &#39;Playas&#39;, &#39;Puyo&#39;, &#39;Quevedo&#39;, &#39;Quito&#39;, &#39;Riobamba&#39;, &#39;Salinas&#39;, &#39;Santo Domingo&#39;))<br>state = st.selectbox(&quot;Enter state&quot;,(&#39;Azuay&#39;, &#39;Bolivar&#39;, &#39;Chimborazo&#39;, &#39;Cotopaxi&#39;, &#39;El Oro&#39;, &#39;Esmeraldas&#39;, &#39;Guayas&#39;, &#39;Imbabura&#39;, &#39;Loja&#39;, &#39;Los Rios&#39;, &#39;Manabi&#39;, &#39;Pastaza&#39;, &#39;Pichincha&#39;, &#39;Santa Elena&#39;, &#39;Santo Domingo de los Tsachilas&#39;, &#39;Tungurahua&#39;)) <br>type_x = st.selectbox(&#39;type_x&#39;,(&#39;Holiday&#39;, &#39;Additional&#39;, &#39;Transfer&#39;, &#39;Event&#39;, &#39;Bridge&#39;))<br>cluster = st.selectbox(&#39;Choose cluster&#39;,(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17))<br>oil_price = st.number_input(&quot;Enter oil price&quot;)<br>type_y = st.selectbox(&#39;type_y&#39;,(&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;))</pre><p>The ones we used for this project are described below</p><ul><li>st.selectbox(): This creates a drop-down menu widget for the input. The drop-down menu allows the user to select from the given options.</li><li>st.number_input(): This creates a number input widget. The widget accepts integer values, and the step value is set to 1.</li><li>st.date_input(): This creates a date input widget for the input. The widget accepts dates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3S4v7LkjQNmBwoMWMneWFQ.png" /><figcaption>Date input field in Streamlit</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N0dkEK544M7E2xALTGcpDQ.png" /><figcaption>Selectbox with drop down in Streamlit</figcaption></figure><p>3. Convert the input data to a pandas DataFrame: After creating the input fields, the user inputs are stored as variables. We then use these variables to create a pandas DataFrame that can be used as input to the model for predictions.</p><pre># Dataframe creation <br>input_df = pd.DataFrame(<br>        {<br>        &quot;date&quot;: [date], <br>        &quot;store_nbr&quot;: [store_nbr], <br>        &quot;family&quot;: [family], <br>        &quot;promotion&quot;: [on_promotion], <br>        &quot;city&quot;: [city], <br>        &quot;state&quot;: [state], <br>        &quot;type_x&quot;: [type_x], <br>        &quot;cluster&quot;: [cluster ], <br>        &quot;oil_price&quot;: [oil_price], <br>        &quot;type_y&quot;: [type_y]<br>        }<br>    )</pre><p>4. Because we will be preprocessing our categorical and numerical columns differently, it’s important that we separate them beforehand</p><pre>categoric_columns = input_df[&#39;family&#39;, &#39;city&#39;, &#39;holiday_type&#39;]<br>numeric_columns = [i for i in columns if i not in categoric_columns]</pre><p>5. We then have to apply our imputer to handle missing values from the numerical columns. For the categorical columns, we impute missing values using the mode value of each column.</p><pre># Apply the imputers on the input data<br>input_df_imputed_cat = cat_imputer.transform(input_df[cat_columns])<br>input_df_imputed_num = num_imputer.transform(input_df[num_columns])</pre><p>6. Our categorical columns need to be converted to binary before our machine learning model can handle them. We imported our encoder earlier for this purpose and will apply it to our categorical columns at this point.</p><pre># Encode the categorical columns<br>encoded_cat = encoder.transform(input_df[categoric_columns])7. We do the same with our scaler; also imported earlier.</pre><pre>#Scale the numeric columns<br>scaled_num = scaler.transform(input_df[numeric_columns])</pre><p>7. Next stage is to join our scaled and encoded columns to give our final dataframe that will serve as input for our model</p><pre># Convert input_data to a numpy array before concatenating<br>input_data = np.concatenate([scaled_num, encoded_cat], axis=1)<br><br>#Convert back to Pandas dataframe<br>final_df = pd.DataFrame(input_data)</pre><p>8. Finally, we make our prediction and display that prediction.</p><pre># Make Prediction<br>prediction = model.predict(input_data)<br><br># Display prediction<br>st.write(f&quot;The predicted sales are: {prediction}.&quot;)<br>        input_df.to_csv(&quot;data.csv&quot;, index=False)<br>        st.table(input_df)</pre><h3>Conclusion</h3><p>Streamlit with its graphical interface features provides a “less scary” platform for non-technical persons to make use of and appreciate machine learning models and their capabilities.</p><p>Data scientists can also more easily share their models and the work done with the general public.</p><p>The GitHub repository for this project can be found <a href="https://github.com/odee0405/Sales-Forecasting-App---Streamlit">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4823a5fe055b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Churn Prediction App with Gradio]]></title>
            <link>https://medium.com/@fiifi.abassah/customer-churn-prediction-app-with-gradio-a8c7a3127cdc?source=rss-a6608f8cb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8c7a3127cdc</guid>
            <dc:creator><![CDATA[Fiifi Abassah-Konadu]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 22:33:04 GMT</pubDate>
            <atom:updated>2023-08-26T00:07:16.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Image Source: https://www.youtube.com/watch?app=desktop&amp;v=RiCQzBluTxU" src="https://cdn-images-1.medium.com/max/1024/1*aI8UIkxyzP9jOcuySKINZg.jpeg" /><figcaption>Image Source: <a href="https://www.youtube.com/watch?app=desktop&amp;v=RiCQzBluTxU">https://www.youtube.com/watch?app=desktop&amp;v=RiCQzBluTxU</a></figcaption></figure><h3>Introduction</h3><p>In an earlier <a href="https://medium.com/@fiifi.abassah/customer-churn-analysis-a-telecommunications-case-study-da3ade0933a3">project</a>, we built a machine learning model to predict whether a customer would stay with a company or not, otherwise known as customer churn. This project was entirely executed in a Jupyter Notebook and is not the most friendly platform for non-technical persons who may need to take advantage of your prediction model.</p><p>This is where Gradio comes in. Gradio is an open-source platform that allows data scientists to share their models using a graphical interface that can be easily interacted with. For this project, we will deploy our customer churn prediction model using the Gradio app.</p><h3>Requirements</h3><p>To get our Gradio app fully functional, we need to install a few Python packages. These have been listed in a requirements file which can be installed with pip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*6MURD5Xtez2hN3aPVbnJqA.png" /></figure><p>We also need to export our best-performing prediction model and other ML components which in this case is our scaler and encoder. This we did with the help of the ‘pickle’ package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*st4nlQD-h-7mSSC5dfYA2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*Q1T0bbuF-u440vfEn0SEeg.png" /></figure><p>These ML components will be applied to the cleaned dataset which will also need to be imported for the Gradio app to perform.</p><h3>Building Gradio</h3><p>The Gradio library has several functions for creating various types of input fields which we will take advantage of. But before that, we will load the ML components and cleaned dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*mP9amNIxS6EZBkdmNDfqUg.png" /></figure><h4>Input and Output Interfaces</h4><p>We need to define our interfaces which will be accepting the data points to run the prediction. This will consist of dropdowns, sliders, radio buttons and data input fields. The output interface will display the prediction to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5g_T8ZgoNGgY_-_jnALMA.png" /></figure><p>Now we need our input components in a Dataframe. We will define a function that receives this input and creates the dataframe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z1QfurrXH_asqOgq1BYFLA.png" /></figure><h4>Preprocessing &amp; Prediction</h4><p>Moving forward, we’ll handle the preprocessing of user input, predict churn, and display the outcome in the output interface. We’ll create a function called predict_churn responsible for these tasks. It will accept the user input, preprocess it, predict churn, and provide the result as a string.</p><p>Below is the code for the predict_churn function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*haUmGU0Zra1-lC-2Z-TYcA.png" /></figure><h4>Launch Time!</h4><p>To bring all these together, we run our app using the launch method of the iface object. Running the app will open a browser page where predictions can be made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qEdWPDkL-flf2ee9d4NSrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDpKxD6vS5_dKpWvF5wzew.png" /></figure><h3>Conclusion</h3><p>We now have our app ready to make predictions. The app is simple to use and can be easily deployed to the cloud or integrated into a web application. <a href="https://github.com/UnhookedMonk/Customer_Churn_Regression_Gradio">Here</a> is the repository with all the code used.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8c7a3127cdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forecasting Grocery Store Sales with Machine Learning]]></title>
            <link>https://medium.com/@fiifi.abassah/forecasting-grocery-store-sales-with-machine-learning-521c345650b0?source=rss-a6608f8cb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/521c345650b0</guid>
            <dc:creator><![CDATA[Fiifi Abassah-Konadu]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 01:27:05 GMT</pubDate>
            <atom:updated>2023-07-30T20:37:10.841Z</atom:updated>
            <content:encoded><![CDATA[<h3>INTRODUCTION</h3><p>One of the powerful capabilities of Machine Learning is prediction. This is where a target variable is determined using previously measured variables. For this project, I sought to predict future sales of various products sold by a chain retail store in Ecuador; Corporacion Favorita. I employed the use of different time series forecasting machine learning models. The training data provided contained the chain store’s products on sale, their previous sales, dates of sales, whether or not some products were on promotion, and the locations of their stores. Separate files are also provided with further information that could be helpful in developing the models. To aid in structuring my work, I used the CRoss Industry Standard Process for Data Mining (CRISP-DM).</p><h3>Business Understanding</h3><p>This project aims to build a model that accurately predicts the unit sales for items sold at different Favorita stores. I developed a hypothesis to guide in my data analysis which is stated as below</p><p>Null: Oil prices do not have an effect on sales</p><p>Alternate: Oil prices have an effect on sales</p><p>I also posed some business questions which had the aim of revealing some insights about the company’s operations</p><p>1. What family brings in the most money across all stores?</p><p>2. Which locales are the busiest in terms of transactions?</p><p>3. In which year did most of the transactions happen?</p><p>4. How have sales been over the years?</p><p>5. What are the dates of the top 10 sales?</p><p>6. What were the dates of the highest sales for each year?</p><p>7. How many transactions happen in the christmas period(20th — 31st December) each year?</p><p>Below is a dashboard showing my findings. The results will be tackled in greater detail later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PEX8Z6lP7tuQRokRBANogA.png" /></figure><h3>Data Understanding</h3><p>The data to be used for this project was in 6 separate files; Train Dataset, Oil Dataset, Holiday Dataset, Stores Dataset, Transactions Dataset, Test Dataset. I imported the relevant Python libraries and loaded the data in order to carry out the analysis.</p><pre># Data Handling<br>import pandas as pd <br>import numpy as np <br><br># Visualization<br>import matplotlib.pyplot as plt<br>import matplotlib.ticker as ticker<br>import matplotlib.dates as mdates<br>import mplcursors<br>import seaborn as sns<br><br># Stationarity <br>from statsmodels.tsa.stattools import kpss<br># Encoding<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import OneHotEncoder<br><br># Evaluation<br>from sklearn.metrics import mean_squared_error, mean_squared_log_error<br><br># Model Selection<br>from skforecast.ForecasterAutoreg import ForecasterAutoreg<br><br>#Saving Model<br>import pickle <br><br># Warnings<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><pre>train = pd.read_csv(&quot;train.csv&quot;)<br>transactions = pd.read_csv(&quot;transactions.csv&quot;)<br>holiday = pd.read_csv(&quot;holiday.csv&quot;)<br>oil  = pd.read_csv(&quot;oil.csv&quot;)<br>stores = pd.read_csv(&quot;stores.csv&quot;)<br>test = pd.read_excel(&#39;test.xlsx&#39;)</pre><p>Exploring the data with Pandas revealed the following:</p><p><strong>Train Dataset</strong></p><p>The training data contains information about dates, store numbers, product families, promotions, and sales figures. The data shows sales and time series data for the features store_nbr, family, and onpromotion. The store_nbr feature indicates the specific location where the goods are sold by the retailer. The family feature describes the category of goods being sold. The sales column provides the total sales for a particular product family at a specific retailer on a given day. Sales can involve fractional units so decimal values are possible. The onpromotion column indicates the total number of promoted products within a family at a specific store on a specific date.</p><p><strong>Holiday Dataframe</strong></p><p>Shows events and holidays, their descriptions and whether or not it’s transferred</p><p><strong>Oil Dataframe</strong></p><p>Oil prices play a crucial role in how things are purchased in Ecuador. This dataframe shows the oil prices per barrel based on dates</p><p><strong>Stores Dataframe</strong></p><p>Keeps information on various stores. Contains information such as store type, city, cluster, and state the store is located. Cluster refers to a grouping of related stores</p><p><strong>Test Dataframe</strong></p><p>Contains same information as train dataframe. Contains information that will be used to test the model yet to be trained</p><h4>Data Processing</h4><p>The data needed to made ready for analysis. This involved handling missing values, duplicates, incorrect data types .</p><pre># Change date column to date time <br>train[&#39;date&#39;] = pd.to_datetime(train[&#39;date&#39;])<br>transactions[&#39;date&#39;] = pd.to_datetime(transactions[&#39;date&#39;])<br>holiday[&#39;date&#39;] = pd.to_datetime(holiday[&#39;date&#39;])<br>oil[&#39;date&#39;] = pd.to_datetime(oil[&#39;date&#39;])<br>test[&#39;date&#39;] = pd.to_datetime(test[&#39;date&#39;])</pre><p>With the code above, I changed the data type of the ‘date’ column to a standard datetime format. I went on to check for missing values in each of the dataframes.</p><pre>train.isna().sum()<br>transactions.isna().sum()<br>store.isna().sum()<br>holiday.isna().sum()<br>oil.isna().sum()<br>test.isna().sum()</pre><p>Oil had 43 missing values. The missing values in the oil dataframe have to be filled. Since the range between minimum and maximum values is very large and the values progress or decrease steadily it will be good to use the forward fill technique.</p><pre># Replace nan value with np.nan<br>oil.replace(&#39;nan&#39;, np.nan, inplace=True)<br><br># Fill null values with forward fill<br>oil = oil.fillna(method = &#39;ffill&#39;)</pre><p>I went on to merge the datasets with the date and the store numbers. This merger did not include the test dataset.</p><pre>#Set date as the index<br>train.set_index(&#39;date&#39;, inplace=True)<br>transactions.set_index(&#39;date&#39;, inplace=True)<br>stores.set_index(&#39;date&#39;, inplace=True)<br>holiday.set_index(&#39;date&#39;, inplace=True)<br>oil.set_index(&#39;date&#39;, inplace=True)</pre><pre># Merge the train and transactions dataframes based on the date and store number columns<br>merged = pd.merge(train, transactions, on=[&#39;date&#39;, &#39;store_nbr&#39;])<br># Merge the merged dataframe with the holiday dataframe based on the date column<br>merged = pd.merge(merged, holiday, on=&#39;date&#39;)<br># Merge the merged data with the oil dataframe on the date column<br>merged = pd.merge(merged, oil, on=&#39;date&#39;)<br><br># Reset index<br>merged.reset_index(inplace=True)<br><br># Merge the merged data with the stores dataframe on the stores number column<br>train = pd.merge(merged, stores, on=&#39;store_nbr&#39;)</pre><p>Further processing was carried out such as renaming the columns to ease understanding</p><h4>Answering Business Questions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*yrWWne6Ecwh6fhAjGZiCXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*RifydQGCnt80fYaVst3OYw.png" /><figcaption>Question 1 (Left): Grocery 1 was by far the most patronized product family. Question 2 (Right): Ecuador had the most transactions in the period.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*bcXCFykgD1oYo5veacQBDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*v779UWtEq1cWGJVJKnl37g.png" /><figcaption>Question 3 (Left): 2016 had the most transactions with 30.8%. Question 4: Sales rose steadily from 2013 to 2014, dipped slightly in 2015, then peaked sharply in 2016 before dipping sharply in 2017</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*qbSc7952nRgL5kvmjDpbnA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*3vLyW1xTS2_4T01ny2aCUg.png" /><figcaption>Question 5 (Left): 2nd May 2016 had the highest ever sale in the period under study. Question 6 (Right): The dates with the highest sales for each year</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*7bVsk_7PktelORcbFDBPXA.png" /><figcaption>Question 7: Transactions for the Christmas periods of each year are shown above with 2014 having the highest number of transactions.</figcaption></figure><h3>Hypothesis Testing</h3><p>For our correlation testing, we applied a correlation matrix to demonstrate correlation or otherwise between the oil prices and sales</p><pre># Finding the correlation between the sales and oil price<br>correlation = train[&#39;sales&#39;].corr(train[&#39;oil_price&#39;])<br><br># Plotting a Correlation Matrix<br>columns_to_analyze = [&#39;sales&#39;, &#39;oil_price&#39;]<br>correlation_matrix = train[columns_to_analyze].corr()<br><br># Plotting the correlation matrix<br>plt.figure(figsize=(8, 6))<br>sns.heatmap(correlation_matrix, annot=True, cmap=&#39;coolwarm&#39;, square=True)<br>plt.title(&#39;Correlation Matrix&#39;)<br><br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*CLxJJIK75omu_x-w6ERceA.png" /></figure><p>Correlation value of -0.061 is too weak to establish any form of connection between the two parameters. We therefore reject the alternate hypothesis that oil prices have an effect on sales.</p><h3>MODELLING</h3><h4>Feature Engineering</h4><p>We drop the columns that won’t be necessary going forward</p><pre>train = train.drop(columns = [&#39;id&#39;, &#39;locale&#39;,&#39;locale_name&#39;,&#39;description&#39;,&#39;transferred&#39;,&#39;state&#39;,&#39;store_type&#39;,&#39;Year&#39;], axis=1)</pre><h4>Feature Encoding</h4><p>Machine learning models can only work with numbers hence we have to convert our categorical columns to a format that can be worked with. We employ OneHotEncoder in scikit-learn to accomplish this.</p><pre># Select the categorical columns<br>categorical_columns = [&quot;family&quot;, &quot;city&quot;, &quot;holiday_type&quot;]<br>categorical_data = time_data[categorical_columns]<br><br># Initialize the OneHotEncoder<br>encoder = OneHotEncoder()<br><br># Fit and transform the data to one hot encoding<br>one_hot_encoded_data = encoder.fit_transform(categorical_data)<br><br># Get the categories for each column<br>categories = [encoder.categories_[i] for i in range(len(encoder.categories_))]<br><br># Create the column names for the one hot encoded data<br>column_names = []<br>for i in range(len(categories)):<br>    for j in range(len(categories[i])):<br>        column_names.append(f&#39;{categorical_columns[i]}_{categories[i][j]}&#39;)<br><br># Convert the one hot encoding data to a DataFrame<br>one_hot_encoded_data = pd.DataFrame(one_hot_encoded_data.toarray(), columns=column_names)<br><br><br># Reset the index of both dataframes<br>time_data = time_data.reset_index(drop=True)<br>one_hot_encoded_data = one_hot_encoded_data.reset_index(drop=True)<br><br># Concatenate the original dataframe with the one hot encoded data<br>time_data_encoded = pd.concat([time_data, one_hot_encoded_data], axis=1)<br><br># Drop the original categorical columns<br>time_data_encoded.drop(categorical_columns, axis=1, inplace=True)</pre><h4>Split Data</h4><p>We split the data into two, one for training and another for testing/evaluation. This split was done using the dates rather than random split as this data is a time series.</p><pre>train_set = time_data_encoded.loc[time_data[&#39;Year&#39;].isin([2013, 2014, 2015, 2016])]<br>test_set = time_data_encoded.loc[time_data[&#39;Year&#39;].isin([2017])]</pre><p>We define the target variable for our models; which in this case is the sales</p><pre># Define input features (X) and target variable (y)<br>X_train = train_set.drop(&#39;sales&#39;, axis=1)  <br>y_train = train_set[&#39;sales&#39;] <br><br>X_test = test_set.drop(&#39;sales&#39;, axis=1)  <br>y_test = test_set[&#39;sales&#39;]</pre><p>From here, we can begin our actual modelling</p><h4>Model 1: XGBoost</h4><pre>xgb = XGBRegressor()<br>xgb.fit(X_train, y_train)<br>xgb_predictions = xgb.predict(X_test)<br><br>plt.scatter(y_test, xgb_predictions)<br>plt.xlabel(&quot;True Values&quot;)<br>plt.ylabel(&quot;Predictions&quot;)<br>plt.title(&quot;XGBoost&quot;)<br>plt.grid(False)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*og4MkwgXFjSITm-lKeTnKQ.png" /></figure><p><strong>Evaluation Metrics for XGBoost</strong></p><pre>xgb_mse = mean_squared_error(y_test, xgb_predictions).round(2)<br>xgb_rmse = np.sqrt(xgb_mse).round(2)<br><br># apply the absolute value function to y_test to remove negative signs<br>y_test_abs = abs(y_test)<br>xgb_predictions_abs = abs(xgb_predictions)<br><br># calculate the mean squared logarithmic error using the new y_test_abs and xgb_predictions_abs array<br>xgb_rmsle = np.sqrt(mean_squared_log_error(y_test_abs, xgb_predictions_abs)).round(2)<br><br>from tabulate import tabulate<br># Define the evaluation results in a list<br>results = [<br>    [&quot;MSE&quot;, xgb_mse],<br>    [&quot;RMSE&quot;, xgb_rmse],<br>    [&quot;RMSLE&quot;, xgb_rmsle]<br>]<br><br># Print the evaluation results in a table<br>print(&quot;\nEvaluation Results for XGBoost:&quot;)<br>print(tabulate(results, headers=[&quot;Metric&quot;, &quot;Value&quot;], tablefmt=&quot;fancy_grid&quot;))</pre><h4>Model 2: Decision Tree</h4><pre># Decision Tree Regression Model<br>dt = DecisionTreeRegressor()<br>dt.fit(X_train, y_train)<br><br># Make prediction on X_test<br>dt_predictions = dt.predict(X_test)<br>dt_predictions<br><br>plt.scatter(y_test, dt_predictions)<br>plt.xlabel(&quot;True Values&quot;)<br>plt.ylabel(&quot;Predictions&quot;)<br>plt.title(&quot;Decision Tree Regression&quot;)<br>plt.grid(False)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*Nwe_G6ANQJKPYTxkirgmcw.png" /></figure><p><strong>Evaluation Metrics for Decision Tree Regression</strong></p><pre>dt_mse = mean_squared_error(y_test, dt_predictions).round(2)<br><br>dt_rmse = np.sqrt(dt_mse).round(2)<br><br># apply the absolute value function to y_test to remove negative signs<br>y_test_abs = abs(y_test)<br>dt_predictions_abs = abs(dt_predictions)<br><br># calculate the mean squared logarithmic error using the new y_test_abs and dt_predictions_abs array<br>dt_rmsle = np.sqrt(mean_squared_log_error(y_test_abs, dt_predictions_abs)).round(2)<br><br># Define the evaluation results in a list<br>results = [<br>    [&quot;MSE&quot;, dt_mse],<br>    [&quot;RMSE&quot;, dt_rmse],<br>    [&quot;RMSLE&quot;, dt_rmsle]<br>]<br><br># Print the evaluation results in a table<br>print(&quot;\nEvaluation Results for Decision Tree Regression:&quot;)<br>print(tabulate(results, headers=[&quot;Metric&quot;, &quot;Value&quot;], tablefmt=&quot;fancy_grid&quot;))</pre><h4>Model 3: Linear Regression</h4><pre># Linear Regression Model<br>lr = LinearRegression()<br>lr.fit(X_train, y_train)<br><br># Make prediction on X_test<br>lr_predictions = lr.predict(X_test)<br><br>plt.scatter(y_test, lr_predictions)<br>plt.xlabel(&quot;True Values&quot;)<br>plt.ylabel(&quot;Predictions&quot;)<br>plt.title(&quot;Linear Regression&quot;)<br>plt.grid(False)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*hpPUR8nbwt4a1-2xZqyxPw.png" /></figure><p><strong>Evaluation Metrics for Linear Regression</strong></p><pre>lr_mse = mean_squared_error(y_test, lr_predictions).round(2)<br>lr_rmse = np.sqrt(lr_mse).round(2)<br><br># apply the absolute value function to y_test to remove negative signs<br>y_test_abs = abs(y_test)<br>lr_predictions_abs = abs(lr_predictions)<br><br># calculate the mean squared logarithmic error using the new y_test_abs and lr_predictions_abs array<br>lr_rmsle = np.sqrt(mean_squared_log_error(y_test_abs, lr_predictions_abs)).round(2)<br><br># Define the evaluation results in a list<br>results = [<br>    [&quot;MSE&quot;, lr_mse],<br>    [&quot;RMSE&quot;, lr_rmse],<br>    [&quot;RMSLE&quot;, lr_rmsle]<br>]<br><br># Print the evaluation results in a table<br>print(&quot;\nEvaluation Results for Linear Regression:&quot;)<br>print(tabulate(results, headers=[&quot;Metric&quot;, &quot;Value&quot;], tablefmt=&quot;fancy_grid&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*SbYeBSN0AvxmnCygIeHx4g.png" /></figure><h4>Model 4 : Random Forest Regressor</h4><pre># Random Forest Regression Model<br>rf = RandomForestRegressor()<br>rf.fit(X_train, y_train)<br><br># Make prediction on X_test<br>rf_predictions = rf.predict(X_test)<br><br>plt.scatter(y_test, rf_predictions)<br>plt.xlabel(&quot;True Values&quot;)<br>plt.ylabel(&quot;Predictions&quot;)<br>plt.title(&quot;Random Forest Regression&quot;)<br>plt.grid(False)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*GjrXtyBRv93NKKB7J40YcA.png" /></figure><p><strong>Evaluation Metrics for Random Forest Regression</strong></p><pre>rf_mse = mean_squared_error(y_test, rf_predictions).round(2)<br>rf_rmse = np.sqrt(rf_mse).round(2)<br><br># apply the absolute value function to y_test to remove negative signs<br>#y_test_abs = abs(y_test)<br>rf_predictions_abs = abs(rf_predictions)<br><br># calculate the mean squared logarithmic error using the new y_test_abs and rf_predictions_abs array<br>rf_rmsle = np.sqrt(mean_squared_log_error(y_test_abs, rf_predictions_abs)).round(2)<br><br># Define the evaluation results in a list<br>results = [<br>    [&quot;MSE&quot;, rf_mse],<br>    [&quot;RMSE&quot;, rf_rmse],<br>    [&quot;RMSLE&quot;, rf_rmsle]<br>]<br><br># Print the evaluation results in a table<br>print(&quot;\nEvaluation Results for Random Forest Regressor:&quot;)<br>print(tabulate(results, headers=[&quot;Metric&quot;, &quot;Value&quot;], tablefmt=&quot;fancy_grid&quot;))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*YOw51Em-LgyePtI048WQ_g.png" /></figure><h4>Stationarity Test</h4><p>Stationarity test is a function to determine if the statistical properties of a test do not change with time.</p><p><strong>KPSS Test</strong></p><p>Null Hypothesis: Series is not stationary</p><p>Alternate Hypothesis: Series is stationary</p><pre># Run kpss test <br>stats, p, lags, critical_values = kpss(train[&#39;sales&#39;], &#39;ct&#39;)</pre><pre># Displaying test results<br>print(f&#39;Test statistics: {stats}&#39;)<br>print(f&#39;p-value:{p}&#39;)<br>print(f&#39;critical values: {critical_values}&#39;)<br>if p &lt; 0.05 :<br>    print(&quot;Series is not stationary&quot;)<br>else:<br>    print(&quot;Series is Stationary&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMp1MBX4IXLrm7fgFy-1Vg.png" /><figcaption>The KPSS test shows that the series is not stationary</figcaption></figure><h4>Make Data Stationary</h4><pre># Perform differencing to make the series stationary<br>train_set[&#39;stationary_sales&#39;] = train_set[&#39;sales&#39;].diff().fillna(0)<br><br># Run KPSS test on the differenced series<br>stats, p, lags, critical_values = kpss(train_set[&#39;stationary_sales&#39;], &#39;ct&#39;)<br><br># Display test results<br>print(f&#39;Test statistics: {stats}&#39;)<br>print(f&#39;p-value: {p}&#39;)<br>print(f&#39;Critical values: {critical_values}&#39;)<br>if p &lt; 0.05:<br>    print(&quot;Series is not stationary&quot;)<br>else:<br>    print(&quot;Series is stationary&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Is7P9jrYYNkQ-Lh5Pem8zQ.png" /></figure><h4><strong>Model 5 : Auto Regressive Model</strong></h4><pre># Create an instance of the AR model<br>ar = AutoReg(y_train, lags=1)<br># Fit the model to the training data<br>ar_fit = ar.fit()<br><br># Make predictions on the test data<br>ar_predictions = ar_fit.predict(start=len(y_train), end=len(y_train) + len(X_test) - 1)</pre><p><strong>Evaluation for AR model</strong></p><pre>ar_mse = mean_squared_error(y_test, ar_predictions).round(2)<br>ar_rmse = np.sqrt(ar_mse).round(2)<br><br># apply the absolute value function to y_test to remove negative signs<br>#y_test_abs = abs(y_test)<br>ar_predictions_abs = abs(ar_predictions)<br><br># calculate the mean squared logarithmic error using the new y_test_abs and ar_predictions_abs array<br>ar_rmsle = np.sqrt(mean_squared_log_error(y_test_abs, ar_predictions_abs)).round(2)<br><br># Define the evaluation results in a list<br>results = [<br>    [&quot;MSE&quot;, ar_mse],<br>    [&quot;RMSE&quot;, ar_rmse],<br>    [&quot;RMSLE&quot;, ar_rmsle]<br>]<br><br># Print the evaluation results in a table<br>print(&quot;\nEvaluation Results for Auto Regressive Model:&quot;)<br>print(tabulate(results, headers=[&quot;Metric&quot;, &quot;Value&quot;], tablefmt=&quot;fancy_grid&quot;))</pre><h4><strong>Model 6 : ARIMA Model</strong></h4><pre>p = 1<br>d = 0 <br>q = 0 # --&gt; p and q are equal to zero as data is already stationary<br><br># Create an instance of the ARIMA model<br>arima_model = ARIMA(y_train, order=(p,d, q))<br><br># Fit the model to the training data<br>arima_model_fit = arima_model.fit()<br><br># Make predictions on the test data<br>arima_predictions = arima_model_fit.predict(start=len(y_train), end=len(y_train) + len(X_test) - 1)</pre><p><strong>Evaluation for ARIMA model</strong></p><pre>arima_mse = mean_squared_error(y_test, arima_predictions).round(2)<br>arima_rmse = np.sqrt(arima_mse).round(2)<br><br># apply the absolute value function to y_test to remove negative signs<br>#y_test_abs = abs(y_test)<br>arima_predictions_abs = abs(arima_predictions)<br><br># calculate the mean squared logarithmic error using the new y_test_abs and arima_predictions_abs array<br>arima_rmsle = np.sqrt(mean_squared_log_error(y_test_abs, arima_predictions_abs)).round(2)<br><br># Define the evaluation results in a list<br>results = [<br>    [&quot;MSE&quot;, arima_mse],<br>    [&quot;RMSE&quot;, arima_rmse],<br>    [&quot;RMSLE&quot;, arima_rmsle]<br>]<br><br># Print the evaluation results in a table<br>print(&quot;\nEvaluation Results for ARIMA Model:&quot;)<br>print(tabulate(results, headers=[&quot;Metric&quot;, &quot;Value&quot;], tablefmt=&quot;fancy_grid&quot;))</pre><h4><strong>Model 7: SARIMAX</strong></h4><pre># Set the seasonal order parameters<br>P = 0  # Seasonal autoregressive order<br>D = 0  # Seasonal differencing order<br>Q = 0  # Seasonal moving average order<br>m = 0  # Number of time steps in each season<br><br># Create an instance of the SARIMAX model<br>sarimax = SARIMAX(y_train, order=(p, d, q), seasonal_order=(P, D, Q, m))<br><br># Fit the model to the training data<br>sarimax_fit = sarimax.fit()<br><br># Make predictions on the test data<br>sarimax_predictions = sarimax_fit.get_prediction(start=len(y_train), end=len(y_train) + len(X_test) - 1)<br><br># Extract the predicted values<br>sarimax_predictions_values = sarimax_predictions.predicted_mean<br>sarimax_predictions_values</pre><p><strong>Evaluation for SARIMAX model</strong></p><pre>sarimax_mse = mean_squared_error(y_test, sarimax_predictions_values).round(2)<br>sarimax_rmse = np.sqrt(sarimax_mse).round(2)<br><br># apply the absolute value function to y_test to remove negative signs<br>y_test_abs = abs(y_test)<br>sarimax_predictions_abs = np.abs(sarimax_predictions_values)<br><br># calculate the mean squared logarithmic error using the new y_test_abs and sarimax_predictions_abs array<br>sarimax_rmsle = np.sqrt(mean_squared_log_error(y_test_abs, sarimax_predictions_abs)).round(2)<br><br># Define the evaluation results in a list<br>results = [<br>    [&quot;MSE&quot;, sarimax_mse],<br>    [&quot;RMSE&quot;, sarimax_rmse],<br>    [&quot;RMSLE&quot;, sarimax_rmsle]<br>]<br><br># Print the evaluation results in a table<br>print(&quot;\nEvaluation Results for SARIMAX Model:&quot;)<br>print(tabulate(results, headers=[&quot;Metric&quot;, &quot;Value&quot;], tablefmt=&quot;fancy_grid&quot;))</pre><p><strong>Model Selection</strong></p><p>In selecting the best model, we consider the RMSLE values arrived at in the evaluation of the models trained. From these, we can tell which models performed best.</p><pre>RMSLES = [<br>    [&quot;XG Boost&quot;, xgb_rmsle],<br>    [&quot;Linear Regression&quot;, lr_rmsle],<br>    [&quot;Decision Tree Regressor&quot;, dt_rmsle],<br>    [&quot;Random Forest Regressor&quot;, rf_rmsle],<br>    [&quot;AR Model&quot;, ar_rmsle],<br>    [&quot;ARIMA Model&quot;, arima_rmsle],<br>    [&quot;SARIMAX Model&quot;, sarimax_rmsle]<br>]<br><br># Print the evaluation results in a table<br>print(&quot;\n RMSLE of all the Models:&quot;)<br>print(tabulate(RMSLES, headers=[&quot;Model&quot;, &quot;RMSLE&quot;], tablefmt=&quot;fancy_grid&quot;))</pre><p>The Linear Regression had the best scores so we selected it for Model Improvement</p><h4>Model Improvement</h4><pre># Perform one-hot encoding on categorical variables<br>X_train = pd.get_dummies(X_train)<br>X_test = pd.get_dummies(X_test)<br><br> <br><br># Align the dataframes to ensure they have the same columns after encoding<br>X_train, X_test = X_train.align(X_test, join=&#39;outer&#39;, axis=1, fill_value=0)<br><br> <br><br># Create the Random Forest Regressor model with the initial/default hyperparameters<br>rf_model = RandomForestRegressor(random_state=42)<br><br> <br><br># Train the Random Forest model on the training data<br>rf_model.fit(X_train, y_train)<br><br> <br><br># Make predictions on the test set using the trained Random Forest model<br>y_pred = rf_model.predict(X_test)<br><br> <br><br> <br><br>#y_test_abs = abs(y_test)<br>rf_predictions_abs = abs(rf_predictions)<br><br># Calculate RMSLE for backtesting evaluation (using absolute values)<br>rmsle = np.sqrt(mean_squared_log_error(np.abs(y_test), np.abs(y_pred)))<br>print(&quot;RMSLE on Test Set:&quot;, rmsle)<br><br> <br><br>#mse = mean_squared_error(y_test, y_pred)<br>#print(&quot;MSE on Test Set:&quot;, mse)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521c345650b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Churn Analysis— A Telecommunications Case Study]]></title>
            <link>https://medium.com/@fiifi.abassah/customer-churn-analysis-a-telecommunications-case-study-da3ade0933a3?source=rss-a6608f8cb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/da3ade0933a3</guid>
            <dc:creator><![CDATA[Fiifi Abassah-Konadu]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 00:35:04 GMT</pubDate>
            <atom:updated>2024-01-16T17:35:35.980Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*kU_mPtwcjfEUSkSflUikxw.jpeg" /><figcaption>Source: <a href="https://www.r-bloggers.com/2018/07/predict-customer-churn-with-gradient-boosting/">https://www.r-bloggers.com/2018/07/predict-customer-churn-with-gradient-boosting/</a></figcaption></figure><p>The backbone of every business is its patrons, in this case customers. They are the ones that determine the value of products or services that businesses offer. Every business is built around the customer, for which reason, without the customer, there really is no business. Businesses strive to get new customers all the time but are also concerned about customer retention. This has made customer churn a very important metric for any serious company or business.</p><p>Customer churn is the loss of any customer for any reason possible. In this analysis, we will be taking a look at the possible reasons for the loss of customers in a telecommunications company. We also aim to build predictive models that will identify customers that are likely to churn and the factors that lead to them doing so to enable the company to take proactive steps to keep customers.</p><h4>Project Structure</h4><p>In conforming with the <strong>Cross Industry Standard Process for Data Mining</strong>(CRISP-DM) approach for Data Science, we began with our Business Understanding, where we probed the data set to ask some questions to guide our analysis. We followed this up with Data Understanding where the datasets were explored in detail to answer the questions asked earlier. We also performed bivariate and multivariate analysis to extract more detail. After this, we prepared our data for the modelling and selected our models. These models were evaluated and the best one underwent hyperparameter tuning for improvement.</p><p>The datasets for this project were from three sources, one sourced from an SQL Database, another from a GitHub repository and the last from a OneDrive folder.</p><p>These datasets were explored using the .head, .shape and .info functions which gave us a sense of the dimensions and possible insights that could be extracted.</p><h4>Business Understanding</h4><p>After this initial EDA, the questions we asked to guide our analysis are as below:</p><ol><li>Does the gender of the customer affect the churn rate?</li><li>Are senior citizens more likely to churn than non-senior citizens?</li><li>How does the monthly charge affect the churn rate?</li><li>How important is customer service in customer retention?</li><li>Does internet service subscription affect the payment method used?</li><li>Which tenure range is most likely to churn?</li><li>Does having a partner and dependents influence churn rate positively or negatively?</li><li>Do customers with both phone service and internet service churn more than customers with just one of the two?</li><li>What is the distribution of the churn rates of customers that have both internet service and online security against those that have internet service and no online security?</li></ol><p>We also stated our hypothesis as Customers on yearly contracts are less likely to churn and our alternate being customers on yearly contracts are more likely to churn.</p><p>Before answering the above, we cleaned our datasets by taking out duplicates and taking care of missing values; which we did by filling it with the most frequent values. We also dropped one column “CustomerID” as it is a unique value field and cannot be used for any analysis.</p><p>To answer the questions above, we employed the use of plots. The code we used in constructing the plots can be found in the GitHub repo linked below.</p><figure><img alt="It is difficult to tell if gender affects churn rate as the difference is almost insignificant" src="https://cdn-images-1.medium.com/max/935/1*wF3Tiir8-HVnGGfe_pjzFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*JMD0Ig0gfzFbCi7YTV_Q7w.png" /><figcaption>It is difficult to tell if gender affects churn rate as the difference is almost insignificant. There is a significant difference in the churn rate for Senior Citizens showing that they are less likely to churn</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*dPZ8Hrktc0geoDGq9Pip2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*9oH_A_AVkBITmYSOqLrIdw.png" /><figcaption>Customers within the 81 to 100 monthly charge range had the highest churn rate. Having tech support greatly reduced the churn rate among customers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*1eS7SpcuIyFE0QoVNiEYdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*8kFjh2SF_kxf2rKN4F30iQ.png" /><figcaption>There was a noticeable increase in the use of electronic check for clients with internet service. Clients who had been with the company with the company for less than 12 months were most likely to churn.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*_Qk_OHliGdM68FHoQEFO2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*37ETfk4jUyMZ3ohXCP7xFA.png" /><figcaption>Customers with partners and/or dependents had a low churn rate. Churn rate for customers with both Phone and Internet service is about 32.9% and Churn rate for customers with either Phone or Internet Service is 26.7%</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*aKbXmCyLdxTI_XchykQ-Dw.png" /><figcaption>Customers with internet service and online security had a churn rate of 14.9% whereas customers with internet service and no online security had a churn rate of 41.7%</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*XbhMuKOqieH99_63Q45_Pg.png" /><figcaption>Customers on the Month-to-Month contract type had a higher churn rate than customers on the One-year or two-year contracts so we reject the Null Hypothesis</figcaption></figure><p>We also conducted some bivariate and multivariate analysis. Below are a few of the plots. The other plots can be found in the full notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*D_tOBFVsjskL6ceiF65GyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*721Q9x3pAPBfulFHCr1BFw.png" /><figcaption>Violin plot showing the churn rate vs the monthly charges and a correlation heatmap showing the correlation between four attributes in the dataset.</figcaption></figure><h4>Machine Learning Modeling</h4><p>We began our modeling process by splitting our training dataset into two. 80% of the total dataset was to be used for training and the remaining 20% was for performance assessment.</p><pre># Split the data into features (X) and target variable (y)<br>X = train_data.drop(&#39;churn&#39;, axis=1)<br>y = train_data[&#39;churn&#39;]<br><br># Split the data into train and test sets<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br># Print the shape of the train and test sets<br>print(&quot;Train set shape:&quot;, X_train.shape, y_train.shape)<br>print(&quot;Test set shape:&quot;, X_test.shape, y_test.shape)</pre><p>We also conducted some preprocessing on the dataset in the form of feature encoding. This involved converting categorical columns to numerical representations to allow for the ML model to be trained with the data.</p><pre># Apply one-hot encoding on the training set<br>encoder = OneHotEncoder(drop=&#39;if_binary&#39;)<br>X_train_encoded = pd.DataFrame(encoder.fit_transform(X_train[categorical]).toarray(),<br>                               columns=encoder.get_feature_names_out(categorical),<br>                               index=X_train.index)<br><br># Apply the same encoding on the testing set<br>X_test_encoded = pd.DataFrame(encoder.transform(X_test[categorical]).toarray(),<br>                              columns=encoder.get_feature_names_out(categorical),<br>                              index=X_test.index)</pre><p>With a churn rate of 26%, our dataset is an imbalanced one. We addressed the imbalance in our dataset with the use of a technique called SMOTE-Tomek (Synthetic Minority Over-sampling Technique with Tomek Links). The first part of this technique generates synthetic examples of the minority class (churned customers) while the second part removes some of the majority class). This allows for better representation of the minority class and makes for a more balanced dataset; eliminating bias and improving prediction success.</p><p>For our prediction, we applied several classification algorithms such as Logistic Regression, Support Vector Machines (SVM), Decision Tree, Adaboost, Random Forest, K-Nearest Neighbors (KNN), and Naive Bayes. Each of these algorithms was applied to both the balanced and imbalanced datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*dbQxvdzYlaFYGDWDKsi97w.png" /><figcaption>Initializing the models to be trained</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*hKY5aqiFuqBEfuTwHj2fdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*PukmO4yDT7yioqAJnEqjYw.png" /><figcaption>Applying the models on both the balanced and imbalanced datasets</figcaption></figure><p>The same modeling processes were applied to the other models and the best models were chosen by looking at their F1 scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*zwJtv3bQzMnf8PjgJ_egFA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*yqYw53Ib57yYqpV5mJqFhw.png" /><figcaption>F1 Scores for the models on the Balanced and Imbalanced Dataset</figcaption></figure><h4>Selecting the best models</h4><p>To gain insights into the decision-making process of our best-performing model, Random Forest, we utilized the SHapley Additive exPlanations (SHAP) technique. SHAP provides interpretability by generating explanations for individual predictions made by the model.</p><p>By applying SHAP, we were able to understand the factors and features that influenced the Random Forest model’s predictions. It helped us identify the key variables and their impact on the likelihood of churn for individual customers. This interpretability aids in making informed business decisions and understanding the underlying factors driving customer churn.</p><p>The SHAP technique provides a valuable tool for explaining the predictions of complex machine learning models, allowing us to gain a deeper understanding of how and why the model arrived at its decisions in the context of customer churn prediction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*oAqQfnEj36BCw3np5n-Vdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OVIEG2friknHqmhIVemuNQ.png" /></figure><p>Based on the interpretation of the Random Forest model using LIME, the model predicts a higher probability of belonging to class 0 (non-churn) with a probability of 0.46.</p><p>The analysis highlights that the “MonthlyCharges_TotalCharges_Ratio” feature has a stronger influence on predicting class 0(churn).</p><h4>Hyperparameter Tuning</h4><p>We conducted hyperparameter tuning to optimize the performance of our models.</p><pre># Define the top 5 models and their respective parameter grids<br>top_models_and_parameters = {<br>    &#39;Random Forest&#39;: (RandomForestClassifier(), {&#39;n_estimators&#39;: [50, 100, 200], &#39;max_depth&#39;: [None, 5, 10]}),<br>    &#39;SVM&#39;: (SVC(), {&#39;C&#39;: [0.1, 1, 10], &#39;kernel&#39;: [&#39;linear&#39;, &#39;rbf&#39;]}),<br>    &#39;Logistic Regression&#39;: (LogisticRegression(), {&#39;C&#39;: [0.001, 0.01, 0.1, 1, 10], &#39;penalty&#39;: [&#39;l1&#39;, &#39;l2&#39;]}),<br>    &#39;Gradient Boosting&#39;: (GradientBoostingClassifier(), {&#39;n_estimators&#39;: [50, 100, 200], &#39;learning_rate&#39;: [0.01, 0.1, 0.2]}),<br>    &#39;AdaBoost&#39;: (AdaBoostClassifier(), {&#39;n_estimators&#39;: [50, 100, 200], &#39;learning_rate&#39;: [0.01, 0.1, 0.2]})<br>}<br><br># Perform hyperparameter tuning for each top model on the imbalanced dataset<br>results_imbalanced = []<br>for model_name, (model, param_grid) in top_models_and_parameters.items():<br>    print(f&quot;\n{model_name} - Imbalanced Dataset:&quot;)<br>    <br>    # Set up GridSearchCV<br>    grid_search = GridSearchCV(model, param_grid, cv=5, scoring=&#39;f1&#39;, n_jobs=-1)<br>    <br>    # Fit the grid search to the imbalanced data<br>    grid_search.fit(X_train_encoded, y_train)<br>    <br>    # Print the best parameters and tuned F1 score<br>    best_params = grid_search.best_params_<br>    best_f1_score = grid_search.best_score_<br>    print(&quot;Best Parameters:&quot;, best_params)<br>    print(&quot;Tuned F1 Score:&quot;, best_f1_score)<br>    <br>    # Save the results for ranking<br>    results_imbalanced.append({<br>        &#39;Models&#39;: model_name,<br>        &#39;Best Parameters&#39;: best_params,<br>        &#39;Tuned F1 Score&#39;: best_f1_score<br>    })<br><br># Perform hyperparameter tuning for each top model on the balanced dataset<br>results_balanced = []<br>for model_name, (model, param_grid) in top_models_and_parameters.items():<br>    print(f&quot;\n{model_name} - Balanced Dataset:&quot;)<br>    <br>    # Set up GridSearchCV<br>    grid_search = GridSearchCV(model, param_grid, cv=5, scoring=&#39;f1&#39;, n_jobs=-1)<br>    <br>    # Fit the grid search to the balanced data<br>    grid_search.fit(X_train_balanced, y_train_balanced)<br>    <br>    # Print the best parameters and tuned F1 score<br>    best_params = grid_search.best_params_<br>    best_f1_score = grid_search.best_score_<br>    print(&quot;Best Parameters:&quot;, best_params)<br>    print(&quot;Tuned F1 Score:&quot;, best_f1_score)<br>    <br>    # Save the results for ranking<br>    results_balanced.append({<br>        &#39;Models&#39;: model_name,<br>        &#39;Best Parameters&#39;: best_params,<br>        &#39;Tuned F1 Score&#39;: best_f1_score<br>    })<br><br># Rank the models based on F1 score for both datasets<br>results_imbalanced_df = pd.DataFrame(results_imbalanced).sort_values(by=&#39;Tuned F1 Score&#39;, ascending=False)<br>results_balanced_df = pd.DataFrame(results_balanced).sort_values(by=&#39;Tuned F1 Score&#39;, ascending=False)<br><br>print(&quot;\nRanking of Models based on F1 Score - Imbalanced Dataset:&quot;)<br>print(results_imbalanced_df[[&#39;Models&#39;, &#39;Tuned F1 Score&#39;]])<br><br>print(&quot;\nRanking of Models based on F1 Score - Balanced Dataset:&quot;)<br>print(results_balanced_df[[&#39;Models&#39;, &#39;Tuned F1 Score&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*jm_ZDk4JYcqnzMHDRK0QSg.png" /></figure><p>After performing hyperparameter tuning, the Random Forest model emerged as the top performer with a score of 0.8778. It outperformed the Support Vector model, which achieved a score of 0.8566, and the Gradient Boost model, which achieved a score of 0.8435.</p><p>Given these results, it is recommended to utilize the Random Forest model for predicting churn. The Random Forest algorithm is well-suited for handling complex relationships in the data, reducing overfitting through ensemble learning, and providing insights into feature importance. Its superior performance on the training data suggests that it has the potential to generalize well to unseen data and make accurate predictions.</p><p>Therefore, the Random Forest model should be selected as the final model for predicting churn based on its robust performance and suitability for the given task.</p><h4>Conclusion</h4><p>This project demonstrates how a business can address the loss of customers and take preemptive steps to retain these customers. The models developed in this project, such as Random Forest, Decision Tree, SVM, and Logistic Regression, provide valuable tools for predicting churn and enabling companies to take proactive measures.</p><p>Overall, this project highlights the significance of using machine learning and data analysis techniques to address customer churn. By employing these methodologies, businesses can enhance customer retention, drive growth, and make informed decisions based on actionable insights derived from their data.</p><p>The full notebook for this project can be found <a href="https://github.com/UnhookedMonk/Customer-Churn-Analysis">here</a>. As always, all comments and feedback are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da3ade0933a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indian Startup Ecosystem — A Data Study]]></title>
            <link>https://medium.com/@fiifi.abassah/indian-startup-ecosystem-a-data-study-f3650277a963?source=rss-a6608f8cb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3650277a963</guid>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fiifi Abassah-Konadu]]></dc:creator>
            <pubDate>Wed, 31 May 2023 23:50:24 GMT</pubDate>
            <atom:updated>2023-05-31T23:50:24.717Z</atom:updated>
            <content:encoded><![CDATA[<h3>Indian Startup Ecosystem — A Data Study</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*e_tiwW6MsDvfjtIVv4J7Jw.png" /><figcaption>Source: <a href="https://cio.eletsonline.com/news/india-maintains-3rd-rank-for-largest-startup-ecosystem-in-world/63620/">https://cio.eletsonline.com/news/india-maintains-3rd-rank-for-largest-startup-ecosystem-in-world/63620/</a></figcaption></figure><h3><strong>Introduction</strong></h3><p>India has become an attractive location for investors and has seen a number of successful startups achieve the coveted “unicorn” status. For this project, we seek to analyse funding received by startups in India. The aim is to prescribe the best course of action for a startup looking into the Indian business ecosystem. To guide our quest for the best course of action as an upcoming startup, we asked a few questions which we will attempt to answer using data. The analysis was conducted in conformance with the Cross Industry Standard Process for Data Mining(CRISP-DM) approach.</p><h3>Business Understanding</h3><p>In developing our business understanding, we asked a few questions to guide our analysis and subsequently develop a hypothesis.</p><p><strong>Questions</strong></p><ol><li>Does the age of the startup affect the funding received?</li><li>Which sectors received the most funding?</li><li>Can location affect the success of receiving funding from investors?</li><li>At what stage do startups receive the most funding?</li><li>What is the average amount received each year per stage?</li></ol><p><strong>Hypothesis</strong></p><p>NULL: Technological industries do not have a higher success rate of being funded</p><p>ALTERNATE: Technological industries have a higher success rate of being funded</p><h3>Data Understanding</h3><p>The data for this project spanned 2018–2021 and some of the attributes contained were: Name of the company/start-up, Year start-up was founded, Sector of service, What it does, Founders, Investors, Funds Raised, Round of funding reached.</p><h3>Data Processing</h3><p>To prepare the data for the analysis, we had to perform some operations on the data. This we did using a few Python libraries which had to be imported.</p><pre># Data handling<br>import numpy as np <br>import pandas as pd <br><br># Vizualisation (Matplotlib, Plotly, Seaborn, etc. )<br>import matplotlib.ticker as ticker<br>import matplotlib.pyplot as plt <br>%matplotlib inline <br>import seaborn as sns <br>sns.set_style(&#39;whitegrid&#39;)<br>plt.style.use(&quot;fivethirtyeight&quot;)<br><br><br><br>import plotly.express as px<br><br># EDA (pandas-profiling, etc. )<br><br>from scipy import stats<br><br>from scipy.stats import pearsonr<br><br>from scipy.stats import chi2_contingency</pre><p>The datasets were imported as 4 separate CSV files. These were explored and cleaned individually. The cleaning process involved going through each attribute of each dataset; assessing its relevance to the project, checking for and handling nulls and duplicates, correcting data types, looking at the unique entries to determine if there were outliers or strange entries.</p><pre>#To convert the column to a numerical one, there is the need to remove some symbols including commas and currency<br><br>startup_funding_2019[&#39;Amount&#39;] = startup_funding_2019[&#39;Amount&#39;].apply(lambda x:str(x).replace(&#39;₹&#39;, &#39;&#39;))<br><br>startup_funding_2019[&#39;Amount&#39;] = startup_funding_2019[&#39;Amount&#39;].apply(lambda x:str(x).replace(&#39;$&#39;, &#39;&#39;))<br><br>startup_funding_2019[&#39;Amount&#39;] = startup_funding_2019[&#39;Amount&#39;].apply(lambda x:str(x).replace(&#39;,&#39;, &#39;&#39;))<br><br>#startup_funding_2019[&#39;Amount&#39;] = startup_funding_2019[&#39;Amount&#39;].apply(lambda x:str(x).replace(&#39;—&#39;, &#39;0&#39;))<br>startup_funding_2019[&#39;Amount&#39;] = startup_funding_2019[&#39;Amount&#39;].replace(&#39;—&#39;, np.nan)</pre><p>After cleaning was completed on the datasets, they had to be combined for the analysis to proceed. As the shape for 2018 was different from that of 2019, 2020 &amp; 2021, we first combined the latter 3 along their rows before combining with 2018 along the columns</p><pre># concatenating 2019, 2020 and 2021 dataframes along rows<br>startup_funding_concatenate = pd.concat([startup_funding_2019, startup_funding_2020, startup_funding_2021], axis=0)</pre><pre>startup_funding_Full = pd.merge(startup_funding_2018, startup_funding_concatenate, on=[&#39;Company Name&#39;,&#39;Sector&#39;,&#39;Stage&#39;,&#39;Amount&#39;,&#39;Location&#39;, &#39;Funding Year&#39;], how=&#39;outer&#39;)</pre><p>Afterwards, we performed some univariate and bivariate analysis on the resultant dataset to extract our first insights. We did this using pyplot and seaborn from which our visuals told an easy-to-read story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-q_NRMWuDlGFUWZJwu5FjA.png" /><figcaption>Pie chart showing the amount distribution in the various stages of funding.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*_aqJG8A6j8lV7EXsuCgBmw.png" /><figcaption>Histogram showing the distribution of startups in the years they were founded</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h6F5jjTUogSsRh0gb-CXQQ.png" /><figcaption>Pie chart showing the top 5 locations producing the most startups</figcaption></figure><h4>Answering the Business Questions</h4><p>In answering our questions, we had to extract some information from the existing attributes in a process known as Feature Processing. An example is deriving the age of the Startup using the Year founded and the Year of Funding.</p><pre># create a new attribute called startup age <br>startup_funding_Full[&quot;Startup_Age&quot;] = abs(startup_funding_Full[&quot;Funding Year&quot;] - startup_funding_Full[&quot;Founded&quot;])</pre><p>From this point, we could answer all our questions with the help of relevant visuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*pxOkfZQnFY6zJzJxsXzeXw.png" /><figcaption>Question 1: This graph shows the startups which received the highest funding and their ages</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*nAvOgNEc_vIUuhPXVpJFwg.png" /><figcaption>Question 2: This graph shows the highest-funded sectors</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*jYCgzbrb6oQQ1-Y2ctUE9g.png" /><figcaption>Question 3: This graph shows the locations whose startups received the most funding</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*SBDBswP4djrLcUmMFf64tw.png" /><figcaption>Question 4: This graph shows the stage at which most funding was received</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*083S5FHeFO2EXgYqznOGQw.png" /><figcaption>Question 5: This graph shows the average amounts of investment received over the years</figcaption></figure><h3>Hypothesis Testing</h3><p>NULL: Technological industries do not have a higher success rate of being funded</p><p>ALTERNATE: Technological industries have a higher success rate of being funded</p><p>To test our hypothesis stated above, we grouped the sectors into Technology and Non-Technology. We used a loop which iterated through the rows and counted unique instances of the “tech” string. We then constructed a bar chart to show how much funding went to Technological sectors as compared with Non-technological.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*-1ZckY-LfyAYZYQdA6ayvA.png" /><figcaption>Total funding for Technology as compared with Non-Technology</figcaption></figure><h3>Conclusion</h3><p>It seems almost evident that the Hypothesis is correct but this would be a hasty conclusion as further investigations revealed that Technological startups were higher in number and this may account for the large gap in investment funding received between the two categories.</p><p>The major takeaways are listed below:</p><ol><li>Bangalore is the place to be as startups from this region received the most funding.</li><li>Fintech and edtech are favourites to receive funding in the Indian ecosystem</li><li>Large amounts of funding are being pumped into the Technological sectors</li></ol><p>The entire GitHub repository for this analysis can be viewed <a href="https://github.com/UnhookedMonk/Career_Accelerator_LP1-Data_Analysis.git"><em>here</em></a>. All comments, feedback and shares are very welcome. Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3650277a963" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Personal Project — I for lef Ghana]]></title>
            <link>https://medium.com/@fiifi.abassah/personal-project-i-for-lef-ghana-c7625e11f489?source=rss-a6608f8cb1f9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7625e11f489</guid>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Fiifi Abassah-Konadu]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 08:32:30 GMT</pubDate>
            <atom:updated>2023-02-06T08:32:30.079Z</atom:updated>
            <content:encoded><![CDATA[<p>Personal Project — I for lef Ghana</p><p>My name is Fiifi and I decided to pivot to a career in tech a year ago. This led me to complete the Google Data Analytics Professional Certificate on Coursera. It was a solid introductory course that highlighted the fundamentals of data analytics including data collection, cleaning, analysis, visualization and communication.</p><p>For new data analysts, undertaking personal projects is essential to your career truly taking flight. It not only gives you a chance to practise the skills learned but also presents a chance to flex your data muscles to would-be employers. This is my first personal project. All comments and feedback are very welcome.</p><p><strong>Background</strong></p><figure><img alt="Illustration of two guys lying in bed at night thinking of how they have to escape their country Ghana" src="https://cdn-images-1.medium.com/max/1024/1*YSgQPjcL8L5ANHKIbgzcgA.jpeg" /><figcaption>Credit: Welbie <a href="https://www.facebook.com/photo/?fbid=1448500275596704&amp;set=ecnf.100064024243694">https://www.facebook.com/photo/?fbid=1448500275596704&amp;set=ecnf.100064024243694</a></figcaption></figure><p>The aftermath of the COVID-19 pandemic and the looming global recession has seen my home country of Ghana hit with immense economic challenges leading to sky-high inflation rates and increased cost of living. A large section of the population has expressed the desire to escape the difficult times by leaving the country for seemingly greener pastures in foreign countries. This desire is typically expressed in local parlance as “I for lef Ghana” which translates to “I have to leave Ghana”. For this project, I sought to perform a basic analysis of this trend on a popular social media network, Twitter. A few questions I sought to answer are as below:</p><ol><li>How many tweets were made on this trend within a specified period?</li><li>Which users really, really wanted to leave Ghana?</li><li>How did the tweets on this trend increase or decrease over time?</li></ol><h3><strong>Process</strong></h3><p>My process can be broken down into data collection, assessment, cleaning, and visualization.</p><p><strong>Data Gathering</strong></p><p>I used two Python libraries in the data gathering; snscrape and pandas. snscrape to pull the tweets and pandas to arrange the tweets into a dataframe. I used the twitter module of the snscrape library to pull up tweets containing the phrase “I for lef Ghana” from Twitter. I selected a start date of 1st January 2021 for the search query and also collected tweet.date, tweet.user.username, tweet.content and tweet.sourceLabel with a limit of 5,000 tweets.</p><p>After this, I arranged the tweets into a dataframe with 4 columns; ‘Date’, ‘User’ , ‘Tweet’ and ‘Tweet Source’ with the use of the pandas library.</p><p>The script returned a total of 3508 tweets which I exported to a CSV file.</p><pre>import snscrape.modules.twitter as sntwitter<br>import pandas as pd</pre><pre>query = &quot;i for lef ghana until:2022-10-20 since:2021-01-01&quot;<br>tweets = []<br>limit = 5000</pre><pre>for tweet in sntwitter.TwitterSearchScraper(query).get_items():<br>if len(tweets) == limit:</pre><pre>break</pre><pre>else:</pre><pre>tweets.append([tweet.date, tweet.user.username, tweet.content,tweet.sourceLabel])</pre><pre>df = pd.DataFrame(tweets, columns=[&#39;Date&#39;, &#39;User&#39;, &#39;Tweet&#39;])</pre><pre>df.to_csv(&#39;tweets.csv&#39;)</pre><p><strong>Data Assessment</strong></p><p>My first step was to inspect the data to get a feel of it.</p><pre>df.info()<br>df.dtypes<br>df.head(10)<br>df.tail(10)</pre><p>Upon inspecting the data, I decided to shorten the dates as I only had intentions of using the day of the tweet and not the time.</p><pre>pd.to_datetime(df[&#39;Date&#39;]).dt.date</pre><p>Examining the data further, I realized an individual had made his desire his whole personality and had changed his handle to “@i_for_lef_ghana”. The script ended up pulling all their tweets as part of the data. I decided to filter out all tweets from the user. This significantly dropped the number of tweets from 3508 to 2431.</p><pre>df = df[df[&quot;User&quot;].str.contains(&quot;i_for_lef_ghana&quot;) == False]</pre><p>Further inspection revealed that other interactions with this account also appeared in the tweets pulled. These tweets also had to be filtered out.</p><pre>unwantedAccount = [&quot;@i_for_lef_ghana&quot;]<br>df[~df.Tweet.str.contains(&#39;|&#39;.join(unwantedAccount))]<br></pre><p>By this point, I was satisfied with the state of the data and I proceeded to the Analysis stage. I exported the data as a CSV file and continued to PowerBI.</p><p><strong>PowerBI</strong></p><p>I loaded my CSV file into PowerBI and examined the columns to check if the data types were all correctly recognized. Once I was satisfied, I begin my visualization of the data.</p><p>To answer my first question about the total tweets in the period, I used a card with a count of the tweets column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*K8-rW4bKm2ZdP5QAAyGxRg.png" /><figcaption>The total tweet count in the period came to 2431 tweets</figcaption></figure><p>I also sought to find out which tweeps really, really wanted to leave the country. I used a bar chart that showed the usernames which had tweeted the most within the period. I used a Top-N filter on the username filter and limited it to 5. The chart is as below. All the best guys; may your visas be granted 🙏</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*IrSrhDO23k8dP3m-K3WQHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*l6ry8TLZZMSOVkIPBADxog.png" /><figcaption>The 5 Twitter handles which tweeted the most kidkhaddyjnr — 23, pope_alorgy — 15, elchico_negro — 13, shadohhw — 12, misterrjam — 11</figcaption></figure><p>I was also interested in how the tweets were coming in over the period. Which months recorded the most number of tweets, and which recorded the least? Which year did more people want to ‘japa’? I used a line graph to plot the number of tweets for each month which is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*QBZoODBaiPIM3uwfV8jWPg.png" /><figcaption>Tweet Count over the time period of 01/01/2021 to 19/01/2023</figcaption></figure><p>The month with the highest number of tweets was June 2021 with 261 unique tweets and the lowest was January 2021 with just 3 tweets. For such a steep rise, the first half of 2021 must have been rough for y’all huh? Kafra. 2021 also recorded significantly higher tweets than 2022; 1422 in 2021 and 979 in 2022. More research will be needed to pinpoint the exact reasons for these trends. From the top of my head as a citizen, I can speculate that most people had resigned themselves to the reality of how difficult it actually is to leave the country for good. Another speculation is the novelty of the trend had worn off.</p><p>I also plotted a pie chart showing the distribution of tweet source. My Apple people are suffering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*3VHJ0DQiYKRLvci7Pg8Q9g.png" /></figure><p>99.6% of the tweets were from Twitter for iPhone, Twitter for Android &amp; Twitter Web. The remaining 0.4% were from Hootsuite Inc., TweetDeck, DadGumBot, Twitter for Mac &amp; Twitter for iPad. I used the calculated column feature in PowerBI to group these under an ‘Other’ heading. The formula for the calculated column is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*kJ5E_SdQ6udUEiWqvQWxLg.png" /></figure><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwXpIOBYMi1Vjs5BKtaevg.png" /></figure><p>The major insights gained;</p><ul><li>June 2021 had the highest number of tweets (261) about wanting to leave Ghana while January 2021 had the lowest (3).</li><li>Twitter user kidkhaddyjnr wanted to leave Ghana the most with 23 tweets</li><li>The iPhone people wanted to leave the most with 67% of the tweets from Twitter for iPhone.</li></ul><p>As mentioned earlier, more research and a deeper dive would be needed to ascribe reasons for these trends and patterns.</p><p>This project challenged me immensely as I had to do quite a bit of research to manipulate the data the way I wanted. Altogether it was a fun experience and I enjoyed myself immensely while developing my Python skills working with the different packages of pandas and snscrape. The link to the GitHub repo can be found <a href="https://github.com/UnhookedMonk/I-for-Lef-Ghana.git">here</a>.</p><p>Kindly share comments, critiques and feedback with me. What do you think I could’ve done better? Which other areas could I explore better? Could my scripts be improved? You can reach me on <a href="https://twitter.com/Mr_Fiifi">Twitter</a> and <a href="https://www.linkedin.com/in/ebenezer-fiifi-abassah-konadu-8a6b0915b/">LinkedIn</a>.</p><p>Thank you and cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7625e11f489" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>