<?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 Alberta Cofie on Medium]]></title>
        <description><![CDATA[Stories by Alberta Cofie on Medium]]></description>
        <link>https://medium.com/@albiecofie2000?source=rss-429e195b95c6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RWWsHpPtbA7Ggm8XO2lT8g.jpeg</url>
            <title>Stories by Alberta Cofie on Medium</title>
            <link>https://medium.com/@albiecofie2000?source=rss-429e195b95c6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:52:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@albiecofie2000/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[A Classification Project: Sepsis Prediction with Machine Learning & FastAPI]]></title>
            <link>https://medium.com/@albiecofie2000/a-classification-project-sepsis-prediction-with-machine-learning-fastapi-c351d2c892a4?source=rss-429e195b95c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c351d2c892a4</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[medical]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sepsis-diagnostics]]></category>
            <category><![CDATA[sepsis]]></category>
            <dc:creator><![CDATA[Alberta Cofie]]></dc:creator>
            <pubDate>Sun, 25 Jun 2023 18:56:14 GMT</pubDate>
            <atom:updated>2023-06-25T18:56:14.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Part 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5sNl5Tx1I7VM-qcMrEz_A.png" /></figure><h4>Sepsis: A summary</h4><p>Sepsis is a severe and potentially life-threatening condition that occurs when the body’s response to an infection triggers widespread inflammation. It is often referred to as blood poisoning.</p><p>Sepsis can develop when the immune system releases chemicals into the bloodstream to combat an infection but instead causes widespread inflammation throughout the body. The aim of this project is to explore the various factors that can cause sepsis in order to predict the occurence of sepsis.</p><h4>Why Predict Sepsis?</h4><p>Here are a few reasons why the ability to predict sepsis is valuable:</p><p><strong>Timely intervention:</strong> Early detection of sepsis allows healthcare professionals to intervene promptly and initiate appropriate treatment. This can include administering antibiotics, providing intravenous fluids, and supporting vital organ functions. Timely intervention can prevent sepsis from progressing to severe sepsis or septic shock, which have higher mortality rates.</p><p><strong>Improved outcomes:</strong> Identifying sepsis early can lead to improved patient outcomes. Studies have shown that early recognition and treatment of sepsis can reduce mortality rates, decrease the length of hospital stays, and lower the risk of complications.</p><p><strong>Resource allocation:</strong> Predicting sepsis can help healthcare facilities allocate resources effectively. By identifying patients at high risk of developing sepsis, hospitals can ensure that appropriate monitoring and interventions are in place. This helps optimize the utilization of staff, equipment, and medications.</p><p><strong>Research and quality improvement:</strong> Predictive models for sepsis can provide valuable insights into risk factors, disease progression, and potential interventions. Analyzing data from these models can contribute to ongoing research efforts and quality improvement initiatives, leading to advancements in sepsis management and care.</p><p><strong>Public health monitoring:</strong> Predictive models can aid in public health monitoring of sepsis outbreaks or trends. By analyzing data on sepsis cases, healthcare systems can identify areas with higher incidence rates, track patterns, and implement targeted interventions or preventive measures.</p><p>Overall, the ability to predict sepsis helps healthcare providers deliver timely and appropriate care, improve patient outcomes, allocate resources effectively, contribute to research efforts, and enhance public health surveillance.</p><h4>About the Data</h4><p>The <a href="https://github.com/AlbieCofie/ML_API_Using_FastAPI"><strong>data</strong></a> for this project is in csv format and it is a medical dataset that contains information about patients who were either in ICU or not and whether they developed sepsis or not. The dataset includes the following features for each patient:</p><blockquote>ID: An identifier for each patient.</blockquote><blockquote>Plasma glucose: The concentration of glucose in the patient’s blood plasma.</blockquote><blockquote>Blood Work Result-1: The value of the first blood work test (mu U/ml).</blockquote><blockquote>Blood Pressure: The patient’s blood pressure (mm Hg).</blockquote><blockquote>Blood Work Result-2: The value of the second blood work test (mm).</blockquote><blockquote>Blood Work Result-3: The value of the third blood work test (mu U/ml).</blockquote><blockquote>Body mass index (BMI): The ratio of the patient’s weight to the square of their height (weight in kg/(height in m)²).</blockquote><blockquote>Blood Work Result-4: The value of the fourth blood work test (mu U/ml).</blockquote><blockquote>Patients age: The age of the patient in years.</blockquote><blockquote>Positive/Negative: Whether the patient developed sepsis (1) or not (0).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0XCvvRCc5BQJL4FDs4Dw4g.png" /><figcaption><strong>A Snapshot of the data</strong></figcaption></figure><h4>Hypothesis</h4><p>Null Hypothesis (H0): Age does not determine whether a patient will develop Sepsis.</p><p>Alternative Hypothesis (H1): Age determines whether a patient will develop Sepsis.</p><p><strong>Hypothesis Validation</strong></p><p>In hypothesis testing and validation, the <strong>p-value</strong> and <strong>t-statistic</strong> are key statistical measures used to evaluate the significance of the results and make conclusions about the hypotheses. They work together to assess the evidence against the null hypothesis.</p><p>A small p-value (below the significance level) indicates that the observed data is unlikely to have occurred by chance alone if the null hypothesis is true. The t-statistic provides a measure of the magnitude of the difference between the observed data and the hypothesized value.</p><p>By considering both the p-value and t-statistic, researchers can determine whether the observed results are statistically significant and provide support for the alternative hypothesis.</p><blockquote>P-value: The p-value is a probability measure that quantifies the strength of evidence against the null hypothesis. It represents the probability of obtaining the observed data (or more extreme) if the null hypothesis is true.</blockquote><blockquote>T-statistic: The t-statistic is a test statistic that measures the difference between the sample mean and the hypothesized population mean, relative to the variability within the data. It is calculated as the ratio of the difference between the sample mean and the hypothesized mean to the standard error of the sample mean.</blockquote><pre># Split the data into two groups based on the Sepssis variable<br>target_positive = train_df[train_df[&#39;Target&#39;] == &#39;Positive&#39;]<br>target_negative= train_df[train_df[&#39;Target&#39;] == &#39;Negative&#39;]<br><br># Extract the Age(Patient_age) values for each group<br>age_target_positive = target_positive[&#39;Patient_age&#39;]<br>age_target_negative = target_negative[&#39;Patient_age&#39;]<br><br># Perform independent samples t-test<br>t_statistic, p_value = ttest_ind(age_target_positive, age_target_negative)<br><br># Print the results<br>print(&quot;P-Value:&quot;, p_value)<br>print(&quot;T-Statistic:&quot;, t_statistic)</pre><p><strong>The output</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTtvBW_gIokikLlCiUvinA.png" /></figure><p><strong>Interpreting the Results</strong></p><p>Based on the given results, with a p-value of 3.4577022949183645e-07 (which is very small) and a t-statistic of 5.1556614056454775, we can conclude the following:</p><p><strong>P-Value: </strong>The p-value is significantly smaller than the commonly used significance level of 0.05. This indicates strong evidence against the null hypothesis.</p><p><strong>T-Statistic:</strong> The t-statistic value of 5.1556614056454775 indicates a substantial difference between the observed data and the hypothesized value under the null hypothesis.</p><p>Based on these findings, we reject the null hypothesis (H0) that age does not determine whether a patient will develop sepsis.</p><blockquote>In summary, the results suggest that age is a significant factor in determining the likelihood of developing sepsis among patients.</blockquote><h4>Asking Questions About the Data</h4><p>Asking questions about the data serves several purposes in <strong>Exploratory Data analysis</strong> and hypothesis testing. Here is a list of questions that would help us better understand the data.</p><ol><li>Is the train dataset complete?</li></ol><p>2. What are the ages of the youngest and oldest patients?</p><p>3. What are the youngest and oldest patients with Sepssis?</p><p>4. What is the average age ?</p><p>5. What is the ratio of patients who are positive for sepssis to the negative patients ?</p><p>6. What is the highest and lowest BMI?</p><p>7. What is the average BMI ?</p><p>8. Is there a corelation between the Sepssis status and the other attributes?</p><h4>Univariate Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qz4t_q43Kf-TSpl1exSHqA.png" /><figcaption><strong>Histogram of Each Numerical Variable</strong></figcaption></figure><p><strong>Observations:</strong></p><p>Most patients showed up for blood work 1 and 3</p><p>Most patients have a blood pressure between 60 and 80</p><p>Most patients have glucose level less than five</p><p>The majority of patients are younger than 40</p><h4>Bivariate Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGiy4oN4Fwb-bZrGbZtM1Q.png" /><figcaption><strong>Distribution of Ages of Patients with &amp; without Sepsis</strong></figcaption></figure><p>The observation suggests that there is a relationship between age and the occurrence of sepsis. Specifically, younger patients appear to have a higher likelihood of negative sepsis cases compared to older patients.</p><p>This observation contradicts the null hypothesis, which stated that age does not determine whether a patient will develop sepsis.</p><p>Therefore, based on the observed data, we have evidence to reject the null hypothesis and suggest that age does play a role in determining the likelihood of sepsis in patients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLvO5oV_iTGf7TM-s-yvcw.png" /><figcaption>Distribution of BMI of Patients with &amp; without Sepsis</figcaption></figure><p>The likelihood of sepsis is lower among patients with lower body mass index (BMI).</p><figure><img alt="Correlation Map for all numerical variables" src="https://cdn-images-1.medium.com/max/1024/1*GZ4evJJMWFOIG0tOYTKd_A.png" /><figcaption>Correlation Map for all numerical variables</figcaption></figure><p><strong>Calculating the Correlation Matrix</strong></p><pre># Calculate the correlation matrix<br>correlation_matrix = num_df.corr()<br><br># Set the threshold for high correlation<br>threshold = 0.5<br><br># Find the highly correlated variables<br>high_correlation = (correlation_matrix.abs() &gt; threshold) &amp; (correlation_matrix != 1)<br><br># Get the variable pairs with high correlation<br>high_correlation_pairs = [(i, j) for i in high_correlation.columns for j in high_correlation.columns if high_correlation.loc[i, j]]<br><br># Print the highly correlated variables<br>for pair in high_correlation_pairs:<br>    var1, var2 = pair<br>    correlation_value = correlation_matrix.loc[var1, var2]<br>    print(f&quot;{var1} and {var2} are highly correlated (correlation value: {correlation_value})&quot;)</pre><p>The output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*phP-_pR18N53dWrdihK_Rg.png" /><figcaption>The results of the above code</figcaption></figure><p>We will identify pairs of columns that have a correlation coefficient of 0.5 and above.</p><p>For each of these pairs, we will remove one column from the pair.</p><p>By doing so, we aim to eliminate redundancy and multicollinearity in the data, which can affect the accuracy and interpretability of the analysis.</p><p><strong>Does Insurance impact the probability of a patients getting sepsis?</strong></p><blockquote>By considering the insurance column in our analysis, we can gain insights into how insurance status may impact the likelihood of developing sepsis and the associated outcomes.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qdDpsOn5ca_rJDC4HRUeGA.png" /></figure><p><strong>Observation:</strong> The presence or absence of insurance has no impact on the status of sepsis.</p><p><strong>Conclusion:</strong> Therefore, we can conclude that the insurance column is not relevant for predicting sepsis status. As a result, we will later remove the insurance column from our analysis.</p><h4>Data Preparation and Cleaning for Analysis</h4><p>At this stage, our main objectives are to organize the data in a way that is suitable for analysis and to ensure that the data is clean and consistent.</p><p>We aim to achieve data cleanliness and consistency by performing tasks such as removing duplicates, handling missing values, correcting data formats, standardizing variables, and addressing any other data quality issues.</p><p>The ultimate goal is to have a well-prepared dataset that is ready for further analysis and modeling.</p><h4>Issues and Corresponding Solutions:</h4><ol><li><strong>High Frequency of Zeros:</strong> The dataset contains a significant number of zero values in each column. These zeros may affect the analysis and modeling process.</li></ol><p><strong>Solution: </strong>We need to determine the reason behind these zeros and decide whether to keep or remove them based on domain knowledge and the specific context of the problem.</p><p>2. <strong>Non-Descriptive Column Names: </strong>The column names in the dataset are not clear or descriptive, making it difficult to understand the variables they represent.</p><p><strong>Solution:</strong> We should rename the columns to be more informative and descriptive, providing a better understanding of the data.</p><p>3. <strong>Imbalanced Classes in the Target Variable: </strong>The target variable ‘Sepsis’ may have imbalanced classes, meaning there could be a significant difference in the number of instances between the positive and negative classes.</p><p><strong>Solution: </strong>We need to address this class imbalance issue by employing techniques such as oversampling, undersampling, or synthetic data generation to ensure balanced representation of the classes.</p><p>4. <strong>Presence of Outliers: </strong>Some numerical columns exhibit a large number of outliers, which can significantly impact the analysis and modeling results.</p><p>Solution: We should identify and handle these outliers appropriately, either by removing them or applying statistical techniques such as winsorization or robust estimators.</p><p>5. <strong>Correlations and Multicollinearity:</strong> There might be correlations among predictor variables, leading to multicollinearity issues. Multicollinearity can affect the model’s interpretability and stability.</p><p><strong>Solution:</strong> We should investigate the correlations between variables and take appropriate actions such as removing highly correlated variables or performing dimensionality reduction techniques like principal component analysis (PCA) to address multicollinearity.</p><blockquote>By addressing these issues and implementing the corresponding solutions, we can ensure a cleaner and more reliable dataset for subsequent analysis and modeling tasks.</blockquote><p>You will find more information about how these issues were fixed <a href="https://github.com/AlbieCofie/ML_API_Using_FastAPI"><strong>here</strong></a><strong>.</strong></p><h4>Answers for Questions About the Data</h4><p>You will find more information about how the below questions were answered here. For now, see below for the answers to these questions:</p><p>1. Is the train dataset complete?</p><p><strong>Answer: </strong>There are no missing values in the dataset</p><p>2. What are the ages of the youngest and oldest patients?</p><p><strong>Answer: </strong>The youngest and oldest patients are 21.0 and 64.0 years respectively</p><p>3. What are the youngest and oldest patients with Sepsis?</p><p><strong>Answer: </strong>The youngest and oldest patient with Sepssis is 21.0 and 64.0 years respectively</p><p>4. What is the average age ?</p><p><strong>Answer: </strong>The Average age is 33.32 years old</p><p>5. What is the ratio of patients who are positive for sepssis to the negative patients ?</p><p><strong>Answer: </strong>The ratio of patientrs positive for sepssis to negative patients is 0.54.</p><p>6. What is the highest and lowest BMI?</p><p><strong>Answer: </strong>The highest and lowest BMI is 50.51 and 18.20 respectively.</p><p>7. What is the average BMI ?</p><p><strong>Answer: </strong>The average BMI is 32.34</p><p>8. Is there a corelation between the Sepssis status and the other attributes?</p><p><strong>Answer: </strong>Blood_Work_R1 &amp; BMI have a moderate correlation with Sepssis status.</p><h4>Feature Processing &amp; Engineering</h4><p>This section focuses on cleaning and processing the dataset, as well as generating new features.</p><h4>Check for Duplicates and Drop them:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6rVZRhGY7QnHXG8eWgy24Q.png" /><figcaption>Checking for duplicates</figcaption></figure><p>Per the above result, there are no duplicates in the dataset</p><h4>Dropping Irrelevant Columns</h4><p>The following columns were dropped: Blood_Work_R2, ID &amp; Insurance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVfFyCJGidxWsw7NpnzK0A.png" /></figure><h4>Data Splitting</h4><p>The training data has been split into two sets: the training set and the evaluation/test set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fsvIwlvKE8OAAyIOD4ULcw.png" /></figure><h4>Data Imbalance Check</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTPXR6pGTDcRPvVVFw2_zA.png" /></figure><p>Since our dataset is imbalanced, we cannot rely solely on the Accuracy Score to select our model.</p><p>To address this issue, we will use the RandomOverSampler technique to oversample the minority class, ensuring a more balanced representation in our data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gj0SMxGHu9i4jaoUoEaeNQ.png" /></figure><p>Based on the results of the code above, we can verify from the above that the dataset imbalance has been sorted.</p><h4>Feature Scaling</h4><pre># Create an instance of StandardScaler and set output to be a DataFrame<br>scaler = StandardScaler().fit(X_train).set_output (transform=&quot;pandas&quot;)<br><br># Scale the training data<br>X_train_df = scaler.transform(X_train)<br><br># Scale the test data using the same scaler<br>X_test_df = scaler.transform(X_test)</pre><h4>Selecting a right Machine Model</h4><p>Analyzing several models is important because it allows us to compare the performance and predictive capabilities of different algorithms. Each model may have its own strengths and weaknesses, and by evaluating multiple models, we can gain insights into which ones are most suitable for our specific problem.</p><p>1. Logistic Regression</p><p>2. RandomForest Classifier</p><p>3. XGBoost Classifier</p><p>4. K Nearest Neighbors</p><p>5. Support Vector Machines</p><p>6. DecisionTreeClassifier</p><p>7. Gradient Boosting Classifier Model</p><h4>Model Comparison</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bf0CKW0-4fnaPV2ct_YVvw.png" /></figure><p>The best model is Gradient Boosting Classifier since it has the highest f1 score.</p><p>Model Evaluation</p><p>Two models, namely the RandomForest Classifier and the Gradient Boosting Classifier, were chosen for the purpose of hyperparameter tuning.</p><p>At this stage, the dataset has already been divided into a training set, which is used for learning the model’s parameters, and a testing set, which is used for evaluating its performance. The next step in the machine learning process involves hyperparameter tuning. This process entails testing the model’s performance with various combinations of hyperparameters and selecting the ones that yield the best results based on a chosen evaluation metric and validation method.</p><p>For the RandomForest Classifier, we begin by creating a set of parameters that will be iterated over by the grid_search_cv method. This method will test thousands of different parameter combinations to identify the optimal configuration for the model.</p><pre># Number of trees in random forest<br>n_estimators = [int(x) for x in np.linspace(start = 15, stop = 80, num = 10)]<br><br># Number of features to consider at every split<br>max_features = [&#39;auto&#39;, &#39;sqrt&#39;, &#39;log2&#39;]<br><br># maximum number of levels in tree<br>max_depth = [2,4,10, None]<br> <br># minimum number of samples required to split a node<br>min_samples_split = [2,5]<br><br># minimum number of samples required at each leaf node<br>min_samples_leaf = [1,2]<br><br># Method of selecting Samples for training each tree<br>bootstrap = [True]<br><br># create param grid<br><br>param_grid = {&#39;n_estimators&#39;:n_estimators,<br>              &#39;max_features&#39;:max_features,<br>              &#39;max_depth&#39;:max_depth,<br>              &#39;min_samples_split&#39;:min_samples_split,<br>              &#39;min_samples_leaf&#39;:min_samples_leaf,<br>              &#39;bootstrap&#39;:bootstrap}<br>print(param_grid)</pre><p>After performing hyperparameter tuning, the process will provide us with the best combination of hyperparameters for each model. Additionally, it will give us the corresponding score for the best combination.</p><p>By obtaining the best combination and its associated score, we can determine which configuration of hyperparameters yields the most favorable results for each model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Ww6N9dQZodjMHk1bVCwRw.png" /></figure><p>The f1 score of our model has shown an improvement from 0.83 to 0.85, indicating an enhancement in its performance. This increase in the f1 score suggests that the model has become more effective in capturing both precision and recall.</p><p>Moving on to the Gradient Boosting Classifier, we will follow a similar process of hyperparameter tuning. By evaluating the model’s performance using different combinations of hyperparameters, we aim to identify the best configuration.</p><p>The resulting score will help us assess the effectiveness of the model and compare it to other models in consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sj_KW7l-CDRHIpbgy7zDYg.png" /></figure><p>Exporting Machine Learning Components</p><p>We will utilize the pickle library to export our best model and scaler. This will allow us to save them as files that can be later used in building a web application using FastAPI.</p><p>By exporting the model and scaler, we can ensure that the trained model and data preprocessing steps are preserved and can be readily loaded and used within the web app environment. This enables seamless integration of the machine learning model into the FastAPI framework for making predictions on new data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8tkJ58UPxUGMmsyRQBleA.png" /></figure><p>Before we dive into building our ML app using FastAPI, it’s important to understand what an API is and its purpose.</p><p>An API, or Application Programming Interface, is a set of rules and protocols that allows different software applications to communicate and interact with each other. It defines the methods and data formats that applications can use to request and exchange information.</p><p>APIs serve various purposes, such as:</p><ol><li>Data Retrieval: APIs enable applications to retrieve data from external sources, such as databases, web services, or other applications. This allows developers to access and utilize data without needing to know the internal workings or structures of the data source.</li><li>Integration: APIs facilitate the integration of different software systems. By providing a standardized interface, APIs enable different applications to interact and share data seamlessly. This promotes interoperability and allows for the creation of complex systems composed of multiple integrated components.</li><li>Functionality Extension: APIs allow developers to extend the functionality of their applications by incorporating features and services provided by external sources. For example, integrating a payment gateway API into an e-commerce application enables secure payment processing.</li><li>Service Provision: APIs can be used to provide services or functionalities to other developers or applications. By defining a set of endpoints and operations, developers can create APIs that offer specific capabilities to be utilized by other applications.</li></ol><p>In the context of machine learning, APIs can be used to expose trained models, allowing other applications or systems to make predictions or perform operations using the model’s capabilities.</p><blockquote>In part two, we will proceed with building our ML app using FastAPI, leveraging the knowledge of APIs to create a web application that can interact with our trained model.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c351d2c892a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a COVID-19 Vaccine Sentiment Analysis App Using Pre-trained Huggingface Models]]></title>
            <link>https://medium.com/@albiecofie2000/building-a-covid-19-vaccine-sentiment-analysis-app-using-pre-trained-huggingface-models-961c00bfc7c3?source=rss-429e195b95c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/961c00bfc7c3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[hugging-face]]></category>
            <dc:creator><![CDATA[Alberta Cofie]]></dc:creator>
            <pubDate>Sun, 11 Jun 2023 17:17:15 GMT</pubDate>
            <atom:updated>2023-06-11T17:17:15.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JSZY4yELuyvwzTkrLN2bFw.png" /></figure><h3>Part 1</h3><p>In the wake of the COVID-19 pandemic, our world has witnessed unprecedented challenges and changes in various aspects of life. Alongside the rapid spread of the virus, the internet and social media platforms have become critical sources of information and communication for people across the globe. These platforms have not only provided an avenue for disseminating vital updates but have also become a space for expressing emotions, opinions, and sentiments related to the pandemic.</p><p>The development and distribution of COVID-19 vaccines have been monumental milestones in our battle against the global pandemic. These vaccines have provided hope and a pathway to recovery, offering protection against the severe effects of the virus. As vaccination efforts continue to progress worldwide, it becomes increasingly important to gauge public sentiment and understand the prevailing attitudes towards COVID-19 vaccines.</p><p>Sentiment analysis, a powerful technique in natural language processing (NLP), allows us to extract insights from text data and uncover the sentiments expressed within it. By employing sentiment analysis, we can analyze vast amounts of online text, such as social media posts, news articles, and public opinions, to discern the prevailing attitudes, opinions, and emotions related to COVID-19 vaccines.</p><p>In this article, we will explore the process of building a COVID-19 vaccines sentiment analysis app using pre-trained models from Hugging Face. Hugging Face has established itself as a prominent provider of NLP technologies and frameworks, offering pre-trained models that have learned to recognize patterns and nuances in language with exceptional accuracy. By harnessing the power of these models, we can develop an app that automatically analyzes text and provides valuable insights into the sentiments expressed by individuals regarding COVID-19 vaccines.</p><p>So, join us on this journey as we leverage the power of pre-trained Hugging Face models to build a COVID-19 vaccines sentiment analysis app, and unlock valuable insights that can shape the discourse surrounding COVID-19 vaccination efforts.</p><blockquote>To access the datasets used, check out this link to my Github: <a href="https://github.com/AlbieCofie/sentimentanalysis"><strong>https://github.com/AlbieCofie/sentimentanalysis</strong></a></blockquote><h4>1. Install packages</h4><p>To install the required packages for building a COVID-19 vaccines sentiment analysis app, you can use the following commands:</p><pre>!pip install datasets<br>!pip install transformers<br>!pip install sentencepiece</pre><p>These commands will install the necessary packages: datasets, transformers, and sentencepiece.</p><p>The datasets package provides a collection of popular NLP datasets, the transformers package offers pre-trained models and tools for NLP tasks, and sentencepiece is a library for tokenization.</p><h4>2. Import Libraries &amp; Load Dataset</h4><p>The below import statements set up the required dependencies and libraries for subsequent steps in building the sentiment analysis model.</p><pre>import os<br>import pandas as pd<br>url = &quot;https://raw.githubusercontent.com/AlbieCofie/sentimentanalysis/main/Train.csv&quot;<br>df = pd.read_csv(url)<br>from datasets import load_dataset<br>from sklearn.model_selection import train_test_split<br>import numpy as np<br>from transformers import AutoModelForSequenceClassification<br>from transformers import TFAutoModelForSequenceClassification<br>from transformers import AutoTokenizer, AutoConfig<br># from scipy.special import softmax<br>from transformers import TrainingArguments, Trainer, DataCollatorWithPadding<br># from transformers import HubManager<br>from sklearn.metrics import mean_squared_error</pre><p>import os: This line imports the os module, which provides a way to interact with the operating system and perform operations such as reading or writing files.</p><p>import pandas as pd: This line imports the pandas library and assigns it the alias pd. pandas is a powerful data manipulation library that allows you to work with structured data, such as CSV files, in an efficient manner.</p><p>url = &quot;https://raw.githubusercontent.com/AlbieCofie/sentimentanalysis/main/Train.csv&quot;: This line assigns a URL to the variable url. It points to a CSV file containing the training data for the sentiment analysis model. The file is hosted on GitHub.</p><p>from datasets import load_dataset: This line imports the load_dataset function from the datasets library. This function is used to load and access datasets, including pre-defined datasets and custom datasets.</p><p>from sklearn.model_selection import train_test_split: This line imports the train_test_split function from the sklearn.model_selection module. This function is commonly used to split data into training and validation sets for model training and evaluation.</p><p>import numpy as np: This line imports the numpy library and assigns it the alias np. numpy is a fundamental package for scientific computing in Python and is commonly used for numerical operations on multi-dimensional arrays.</p><p>from transformers import AutoModelForSequenceClassification: This line imports the AutoModelForSequenceClassification class from the transformers library. This class provides a pre-trained model specifically designed for sequence classification tasks, such as sentiment analysis.</p><p>from transformers import TFAutoModelForSequenceClassification: This line imports the TFAutoModelForSequenceClassification class from the transformers library. This class is a TensorFlow-compatible version of the AutoModelForSequenceClassification and can be used for training and inference with TensorFlow.</p><p>from transformers import AutoTokenizer, AutoConfig: This line imports the AutoTokenizer and AutoConfig classes from the transformers library. These classes are used for automatically selecting and loading the appropriate tokenizer and model configuration based on the chosen pre-trained model.</p><p>from transformers import TrainingArguments, Trainer, DataCollatorWithPadding: This line imports the TrainingArguments, Trainer, and DataCollatorWithPadding classes from the transformers library. These classes provide the necessary tools and configurations for training a model, including training arguments, the training loop, and data collation.</p><p>from sklearn.metrics import mean_squared_error: This line imports the mean_squared_error function from the sklearn.metrics module. This function is used to evaluate the performance of a regression model by calculating the mean squared error between predicted and true values.</p><p>Next, the line of code df = df[~df.isna().any(axis=1)] is used to remove rows from a DataFrame (df) that contain any missing values (NaN).</p><h4>3. The Data</h4><p>Split a DataFrame (df) into training and evaluation sets.</p><pre>train, eval = train_test_split(df, test_size=0.2, random_state=42, stratify=df[&#39;label&#39;])</pre><p>The line of code above splits the DataFrame df into training and evaluation sets, with 80% of the data assigned to the training set (train) and 20% assigned to the evaluation set (eval). The random seed ensures reproducibility, and the stratify parameter preserves the class distribution in the original dataset during the split.</p><p>Let’s get a snapshot of the first 5 rows of the data</p><p><strong>Train Dataset</strong></p><pre>train.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzSDKwQ_SECpjdP9HAMujw.png" /><figcaption>Snapshot of the train dataset</figcaption></figure><p><strong>Evaluation Dataset</strong></p><pre>eval.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4hIxwQJShJfpotdHgrPOw.png" /></figure><p>Next, we use the codeeval.label.unique() to retrieve the unique values in the &#39;label&#39; column of the evaluation set (eval). It is used to determine the distinct classes or categories present in the &#39;label&#39; column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*npnxoWgQfO9PqegnbmMzdA.png" /></figure><p>We then createDatasetDict object using the Dataset class from the datasets library. It also removes a redundant column from the dataset.</p><pre>from datasets import DatasetDict, Dataset<br>train_dataset = Dataset.from_pandas(train[[&#39;tweet_id&#39;, &#39;safe_text&#39;, &#39;label&#39;, &#39;agreement&#39;]])<br>eval_dataset = Dataset.from_pandas(eval[[&#39;tweet_id&#39;, &#39;safe_text&#39;, &#39;label&#39;, &#39;agreement&#39;]])<br><br>dataset = DatasetDict({&#39;train&#39;: train_dataset, &#39;eval&#39;: eval_dataset})<br>dataset = dataset.remove_columns(&#39;__index_level_0__&#39;)<br>dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiN1FSHHVOv8B5sPVfv-Fg.png" /></figure><h4>4. Text Preprocessing &amp; Tokenizer Initialization</h4><pre>def preprocess(text):<br>    new_text = []<br>    for t in text.split(&quot; &quot;):<br>        t = &#39;@user&#39; if t.startswith(&#39;@&#39;) and len(t) &gt; 1 else t<br>        t = &#39;http&#39; if t.startswith(&#39;http&#39;) else t<br>        new_text.append(t)<br>    return &quot; &quot;.join(new_text)<br><br>checkpoint = &quot;cardiffnlp/twitter-xlm-roberta-base-sentiment&quot;<br><br>tokenizer = AutoTokenizer.from_pretrained(checkpoint</pre><p>The preprocess function takes a text parameter and processes it by replacing Twitter usernames starting with &#39;@&#39; with &#39;@user&#39; and replacing URLs starting with &#39;http&#39; with &#39;http&#39;. The function splits the input text by spaces, performs the necessary replacements, and joins the processed text back into a single string. This function can be used to preprocess the text data before feeding it into the sentiment analysis model.</p><p>The code then initializes a tokenizer using the AutoTokenizer class from the transformers library.</p><p>The tokenizer is created using the <strong><em>&quot;cardiffnlp/twitter-xlm-roberta-base-sentiment&quot;</em></strong> checkpoint, which represents the<strong> pre-trained Huggingface model</strong> checkpoint for sentiment analysis on Twitter data. The tokenizer is responsible for tokenizing the input text and preparing it for input to the sentiment analysis model.</p><h4>5. Transform and Prepare the Dataset for Model Training</h4><p>These steps are essential in preparing the dataset for training a sentiment analysis model.</p><pre>def transform_labels(label):<br><br>    label = label[&#39;label&#39;]<br>    num = 0<br>    if label == -1: #&#39;Negative&#39;<br>        num = 0<br>    elif label == 0: #&#39;Neutral&#39;<br>        num = 1<br>    elif label == 1: #&#39;Positive&#39;<br>        num = 2<br><br>    return {&#39;labels&#39;: num}<br><br>def tokenize_data(example):<br>    return tokenizer(example[&#39;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 useless 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)<br>data_collator = DataCollatorWithPadding(tokenizer=tokenizer)</pre><p>The code above includes two functions, transform_labels and tokenize_data, as well as additional code to transform and prepare the dataset for model training.</p><p>The transform_labels function takes a label parameter, which represents the label column of the dataset. It extracts the label value using label[&#39;label&#39;]. Then, it assigns a numerical value to the label based on its original value. In this case, if the label is -1, it is assigned a numerical value of 0 (representing &#39;Negative&#39;). If the label is 0, it is assigned a value of 1 (representing &#39;Neutral&#39;). If the label is 1, it is assigned a value of 2 (representing &#39;Positive&#39;). The function returns a dictionary with the transformed label stored under the key ‘labels’.</p><p>The tokenize_data function takes an example parameter, representing a single example from the dataset. It tokenizes the &#39;safe_text&#39; column of the example using the previously initialized tokenizer. The padding=&#39;max_length&#39; argument ensures that all tokenized sequences have the same length by padding or truncating them to the maximum sequence length defined by the tokenizer.</p><p>The tokenize_data function is then applied to the entire dataset using the map method. It tokenizes the &#39;safe_text&#39; column of each example in the dataset, modifying the dataset in place. The batched=True argument indicates that the mapping operation should be applied in a batched manner for improved efficiency.</p><p>Next, the list named remove_columns is created, containing the column names to be removed from the dataset. The map method is then used to apply the transform_labels function to each example in the dataset while removing the specified columns. This step transforms the labels and removes unnecessary columns, modifying the dataset in place.</p><h4>5. Training</h4><p><strong>5.1. </strong>The TrainingArguments object in the code below specifies training-related configurations such as the number of epochs, saving and evaluation strategies, logging settings, and batch size. These settings define how the sentiment analysis model will be trained and monitored during the training process.</p><p>Let’s break down the arguments used in the TrainingArguments object:</p><ul><li>&quot;test_trainer&quot;: This argument specifies the output directory where the trained model and training logs will be saved.</li><li>num_train_epochs=10: This argument sets the number of training epochs, which determines how many times the model will iterate over the entire training dataset during training.</li><li>load_best_model_at_end=True: This argument specifies that the best model based on evaluation metrics will be loaded at the end of training. The best model is determined by the evaluation strategy, which in this case is set to &#39;epoch&#39;.</li><li>save_strategy=&#39;epoch&#39;: This argument determines when to save the model checkpoints during training. Setting it to &#39;epoch&#39; ensures that the model is saved after each training epoch.</li><li>evaluation_strategy=&#39;epoch&#39;: This argument specifies when to perform evaluation during training. Setting it to &#39;epoch&#39; means that evaluation will be performed after each training epoch.</li><li>logging_strategy=&#39;epoch&#39;: This argument determines when to log training metrics. Setting it to &#39;epoch&#39; means that metrics will be logged after each training epoch.</li><li>logging_steps=100: This argument sets the frequency of logging during training. The training metrics will be logged every 100 steps.</li><li>per_device_train_batch_size=8: This argument sets the training batch size per device. It determines how many examples will be processed in parallel during each training step.</li></ul><p><strong>5.2. Loading a pretrained model while specifying the number of labels in our dataset for fine-tuning</strong></p><pre>model=AutoModelForSequenceClassification.from_pretrained(checkpoint, num_labels=3)</pre><p><strong>5.3. Shuffle Training &amp; Evaluation datasets</strong></p><p>By shuffling the training and evaluation datasets, the order of the examples is randomized, which helps in preventing any potential biases or patterns related to the order of the examples during training and evaluation. Shuffling the datasets can lead to better model generalization and performance.</p><pre>train_dataset = dataset[&#39;train&#39;].shuffle(seed=10) <br>eval_dataset = dataset[&#39;eval&#39;].shuffle(seed=10) </pre><p><strong>5.4. Compute evaluation metrics for the sentiment analysis model.</strong></p><pre>def compute_metrics(eval_pred):<br>    logits, labels = eval_pred<br>    predictions = np.argmax(logits, axis=-1)<br>    return {&quot;rmse&quot;: mean_squared_error(labels, predictions, squared=False)}</pre><p>Defines a function named compute_metrics which takes a single parameter, eval_pred, which represents the evaluation predictions made by the model.</p><p>logits and labels are unpacked from the eval_pred parameter. The logits represent the predicted scores or probabilities for each class, while the labels represent the true labels of the examples.</p><p>predictions is computed by taking the argmax along the last axis of the logits array. This gives the index of the class with the highest score or probability as the predicted class for each example.</p><p>Finally, the function calculates the root mean squared error (RMSE) using the mean_squared_error function from sklearn.metrics. It compares the true labels with the predictions and computes the RMSE value. The squared=False argument ensures that the RMSE value is returned instead of the squared value.</p><p>The compute_metrics function is typically used as an argument in the Trainer class during evaluation. It allows for the computation of custom evaluation metrics based on the model&#39;s predictions and the true labels. In this case, the function computes the RMSE metric, which can be useful for evaluating the model&#39;s performance in regression tasks where the sentiment labels are continuous values.</p><p><strong>5.5. Train the Model</strong></p><p>During training, the sentiment analysis model will iterate over the training dataset for the specified number of epochs. In each epoch, the model will process batches of training examples, compute the gradients, and update the model’s parameters to minimize the loss function. The training process continues until the specified number of epochs is reached.</p><pre>trainer.train()</pre><p>During training, the Trainer class will handle various aspects such as batch processing, gradient computation, parameter updates, logging training metrics, and saving model checkpoints according to the specified configurations in the TrainingArguments object.</p><h4>6. Push the Model &amp; Tokenizer to Huggingface</h4><p>How to push a trained model and tokenizer to the Hugging Face Model Hub, making them accessible to others and allowing for easy sharing and collaboration.</p><pre>token = &quot;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&quot;<br>model.push_to_hub(&quot;AlbieCofie/xlm_roberta_base&quot;, use_auth_token=token, commit_message=&quot;Pushed model&quot;)<br>tokenizer.push_to_hub(&quot;AlbieCofie/xlm_roberta_base&quot;, use_auth_token=token, commit_message=&quot;pushed tokenizer&quot;)</pre><p>The token variable contains an authentication token required to access the Hugging Face Model Hub and push the model. It is a private token associated with the user&#39;s Hugging Face account.</p><p>model.push_to_hub() is used to push the trained model to the Model Hub. The function takes three arguments: the model name (&quot;AlbieCofie/xlm_roberta_base&quot; in this case), use_auth_token to authenticate the user&#39;s account, and commit_message to provide a brief description of the commit.</p><p>By calling model.push_to_hub(), the trained model will be uploaded to the Hugging Face Model Hub under the specified model name.</p><p>Similarly, tokenizer.push_to_hub() is used to push the tokenizer associated with the trained model to the Model Hub. It takes the tokenizer name, use_auth_token, and commit_message as arguments.</p><p>By executing tokenizer.push_to_hub(), the tokenizer will be uploaded to the Hugging Face Model Hub under the specified tokenizer name.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=961c00bfc7c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide on Building a Customer Churn Prediction Web App with Gradio]]></title>
            <link>https://medium.com/@albiecofie2000/a-guide-on-building-a-customer-churn-prediction-web-app-with-gradio-89c1e5a2ec01?source=rss-429e195b95c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/89c1e5a2ec01</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[gradio]]></category>
            <dc:creator><![CDATA[Alberta Cofie]]></dc:creator>
            <pubDate>Sat, 22 Apr 2023 10:16:26 GMT</pubDate>
            <atom:updated>2023-04-22T10:16:26.300Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUb7F7obfoEqVZh3dyx4DA.jpeg" /></figure><p><strong>Introduction</strong></p><p>Customer churn refers to the rate at which customers stop doing business with a company. It is a significant problem for many businesses, as losing customers can have a negative impact on revenue and profitability. Data can be used to help predict customer churn and take proactive measures to prevent it.There are various factors that can contribute to customer churn, including poor customer service, dissatisfaction with products or services, and competition from other businesses. By analyzing customer data, companies can identify patterns and trends that may indicate a customer is at risk of churning. This data can include demographic information, purchase history, customer service interactions, and other behavioral data.</p><p>To predict customer churn, companies can use a variety of analytical techniques, including machine learning algorithms, predictive modeling, and statistical analysis. These techniques can help identify the key drivers of churn, such as customer demographics, product usage patterns, and customer sentiment.</p><p>Once potential churners have been identified, companies can take proactive measures to retain these customers. This can include targeted marketing campaigns, personalized promotions, improved customer service, and other efforts to enhance the overall customer experience.</p><p>In summary, customer churn is a critical challenge for businesses, and data can be a valuable tool for predicting and preventing it. By analyzing customer data and using advanced analytical techniques, companies can gain valuable insights into customer behavior and take proactive steps to retain customers and improve business performance.</p><p>In this article, we will explore a step-by-step process of building a customer churn prediction web app using Gradio. The idea is use this app to help businesses to predict which customers are most likely to churn and take proactive measures to retain them.</p><p><strong>The MACHINE LEARNING MODEL</strong></p><p>Creating a machine learning (ML) model involves several key steps, which typically follow a general process. Here’s an overview of the steps involved in creating an ML model:</p><ol><li>Define the problem: The first step in creating an ML model is to define the problem you want to solve. This includes clearly identifying the objective of the model, understanding the data available, and determining the performance metrics to evaluate the model’s success.</li><li>Data collection and preparation: Next, you need to gather and prepare the data that will be used to train and test the ML model. This can involve collecting data from various sources, cleaning and preprocessing the data, and performing feature engineering to select relevant variables or create new features that may improve model performance.</li><li>Model selection: Once the data is prepared, you need to choose the appropriate ML algorithm for your problem. There are various types of ML algorithms, such as linear regression, decision trees, support vector machines, and neural networks, among others. The choice of the algorithm depends on the problem, the data, and the desired outcome.</li><li>Model training: After selecting the algorithm, you need to train the model using the prepared data. This involves feeding the data into the model, which then learns from the data and adjusts its parameters to make predictions or classifications. The model is typically trained on a subset of the data, called the training set, while holding out another subset, called the validation or test set, for model evaluation.</li><li>Model evaluation: Once the model is trained, you need to evaluate its performance on the validation or test set. This involves measuring how well the model is performing based on the chosen performance metrics, such as accuracy, precision, recall, F1 score, or others. If the model’s performance is not satisfactory, you may need to iterate on the previous steps, such as adjusting hyperparameters, improving feature engineering, or trying different algorithms.</li><li>Model deployment: Once you are satisfied with the model’s performance, you can deploy it in a production environment. This involves integrating the model into a real-world system or application, making it accessible to users or other systems, and setting up monitoring and maintenance processes to ensure its ongoing performance.</li><li>Model monitoring and maintenance: After deploying the model, it’s important to monitor its performance and make necessary updates or improvements as needed. This can involve monitoring the model’s predictions, evaluating its accuracy over time, updating the model with new data, and addressing any issues or limitations that may arise in the production environment.</li><li>Model iteration and improvement: Finally, the process of creating an ML model is iterative, and it’s important to continuously monitor, evaluate, and improve the model’s performance over time. This may involve refining the model based on feedback from users, incorporating new data, or exploring different techniques to enhance its accuracy and usefulness.</li></ol><p>It’s worth noting that creating an ML model is an iterative process that requires domain expertise, data understanding, model selection, training, evaluation, and deployment.</p><p><strong>A Summary of GRADIO</strong></p><p>Gradio is an open-source Python library that makes it easy to create interactive user interfaces for machine learning models. It provides a simple and intuitive way to deploy and share machine learning models with a graphical user interface (GUI), allowing users to interact with the models using input controls and see the model’s predictions in real-time.</p><p><strong>Set up your virtual environment and install the necessary pacakges</strong></p><p>When you’re working on a Python project, it’s commonly advised to utilize a virtual environment to effectively handle your dependencies and make sure that the packages used in your project don’t conflict with other packages that are installed globally on your computer system.</p><p>Here are the steps for setting up a virtual environment:</p><ol><li>Install virtual environment: You can install a virtual environment package, such as virtualenv or conda, depending on your preference.</li><li>Create a virtual environment: Use the installed virtual environment package to create a new virtual environment in your project directory. You can choose a name for your virtual environment.</li><li>Activate the virtual environment: Depending on your operating system, the command to activate the virtual environment may vary. For example, on Windows, you can use the activate script, while on Unix-based systems, you can use the source command.</li><li>Install dependencies: Once the virtual environment is activated, you can use pip or conda to install the necessary dependencies for your project. These dependencies will be installed within the virtual environment, separate from the global packages on your system.</li><li>Work on your project: You can now run your Python scripts or work on your project within the virtual environment. The virtual environment will isolate your project’s dependencies from the global packages, ensuring that your project runs smoothly without conflicts.</li><li>Deactivate the virtual environment: When you’re done working on your project, you can deactivate the virtual environment using the appropriate command for your operating system. This will switch back to your system’s global Python environment.</li></ol><p>By following these steps, you can effectively manage your project’s dependencies and avoid conflicts with other packages on your system.</p><p><strong>Constructing and training a machine learning model using Python and scikit-learn.</strong></p><p>Once you have constructed and trained a machine learning model using Python and scikit-learn, it’s crucial to save the trained model for future use in making predictions on new data. This is where the utility of joblib.dump() becomes valuable.</p><p>In the code snippet below, the dump function from the joblib library is imported, along with the os module. The destination path is set to the current directory (&quot;export&quot; directory).</p><p>A dictionary named models is created to store the objects and their corresponding filenames. The objects are numerical_imputer, categorical_imputer, encoder, scaler, and best_model.</p><p>The for loop iterates through the items in the models dictionary, and for each item, the dump function is used to save the model object with its respective filename in the destination directory using os.path.join().</p><p>The filenames are created by concatenating the name from the dictionary with the extension .joblib. This process will save the models to separate files in the designated directory using joblib.dump() for later reuse.</p><pre>from joblib import dump<br>import os<br><br># set the destination path to the &quot;export&quot; directory<br>destination = &quot;.&quot;<br><br># create a dictionary to store the objects and their filenames<br>models = {&quot;numerical_imputer&quot;: numerical_imputer,<br>          &quot;categorical_imputer&quot;: categorical_imputer,<br>          &quot;encoder&quot;: encoder,<br>          &quot;scaler&quot;: scaler,<br>          &quot;Final_model&quot;: best_model}<br><br># loop through the models and save them using joblib.dump()<br>for name, model in models.items():<br>    dump(model, os.path.join(destination, f&quot;{name}.joblib&quot;))</pre><p><strong>Create a user interface for a web application using Gradio</strong></p><p>The process of creating a user interface for a web application using Gradio typically involves the following steps:</p><ol><li>Install Gradio: Start by installing the Gradio library in your Python environment using a package manager, such as pip or conda. This can be done through the command line or within your Python script.</li><li>Import Gradio: Once Gradio is installed, import it into your Python script using the appropriate import statement.</li><li>Define Input and Output Functions: Define functions that will handle the input and output for your web application. Gradio allows you to easily specify the input format, such as text input, image input, or audio input, and the expected output format, such as text output or image output.</li><li>Create Interface: Use the functions provided by Gradio to create the user interface for your web application. You can customize the appearance and behavior of the interface, such as adding input and output fields, buttons, and sliders, and specifying the layout and style.</li></ol><pre>gr.components.Radio([&#39;male&#39;, &#39;female&#39;], label=&#39;Select your gender&#39;),<br>gr.components.Number(label=&quot;Are you a Seniorcitizen; No=0 and Yes=1&quot;),<br>gr.components.Radio([&#39;Yes&#39;, &#39;No&#39;], label=&#39;Do you have Partner&#39;),<br>gr.components.Dropdown([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have any Dependents? &#39;),<br>gr.components.Number(label=&#39;Lenght of tenure (no. of months with Telco)&#39;),<br>gr.components.Radio([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have PhoneService? &#39;),<br>gr.components.Radio([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have MultipleLines&#39;),<br>gr.components.Radio([&#39;DSL&#39;, &#39;Fiber optic&#39;, &#39;No&#39;], label=&#39;Do you have InternetService&#39;),<br>gr.components.Radio([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have OnlineSecurity?&#39;),<br>gr.components.Radio([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have OnlineBackup?&#39;),<br>gr.components.Radio([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have DeviceProtection?&#39;),<br>gr.components.Radio([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have TechSupport?&#39;),<br>gr.components.Radio([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have StreamingTV?&#39;),<br>gr.components.Radio([&#39;No&#39;, &#39;Yes&#39;], label=&#39;Do you have StreamingMovies?&#39;),<br>gr.components.Dropdown([&#39;Month-to-month&#39;, &#39;One year&#39;, &#39;Two year&#39;], label=&#39;which Contract do you use?&#39;),<br>gr.components.Radio([&#39;Yes&#39;, &#39;No&#39;], label=&#39;Do you prefer PaperlessBilling?&#39;),<br>gr.components.Dropdown([&#39;Electronic check&#39;, &#39;Mailed check&#39;, &#39;Bank transfer (automatic)&#39;,<br>                                        &#39;Credit card (automatic)&#39;], label=&#39;Which PaymentMethod do you prefer?&#39;),<br>gr.components.Number(label=&quot;Enter monthly charges&quot;),<br>gr.components.Number(label=&quot;Enter total charges&quot;)</pre><ol><li>Define Prediction Function: Define a function that will handle the prediction or processing logic of your web application. This function will be called when the user interacts with the interface created using Gradio.</li><li>Run Web App: Finally, run the web application using Gradio’s gradio.Interface() function, passing in the input and output functions, the prediction function, and any other configuration settings.</li></ol><p>By following these steps, you can create a user-friendly web application interface using Gradio, allowing users to interact with your machine learning or data processing models easily through a web browser.</p><p>DEPLOYING YOUR WEB APP</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*GnDduoSY7SNAW0q3yYmMXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*5tStsEge7YCqfOZs3zZIuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*bL9uJ8knMWTcbXLrZIXNcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*ZRlY6H8fLtTJvS0pra7YiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*6FFyUh4mV5qMmtHtJvDCww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*gaHWXSHBeIYe5IExrE-SsQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*pCxNVJuzUQzwdRd7_6JIzw.png" /></figure><h3>Testing the web app</h3><p>The user inputs the following data;</p><pre>Select your gender: male <br>Are you a Seniorcitizen; No=0 and Yes=1 : 0 <br>Do you have Partner: No <br>Do you have any Dependents: Yes<br>Lenght of tenure (no. of months with Telco): No<br>Do you have PhoneService? No<br>Do you have MultipleLines: No<br>Do you have InternetService: DSL<br>Do you have OnlineSecurity? No<br>Do you have OnlineBackup? No<br>Do you have DeviceProtection? No<br>Do you have TechSupport? No<br>Do you have StreamingTV? No<br>Do you have StreamingMovies? No<br>which Contract do you use? No<br>Do you prefer PaperlessBilling? No<br>Which PaymentMethod do you prefer? Mailed check<br>Enter monthly charges: 345 <br>Enter total charges: 12</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*Rut0B6ZyysOJ8Lu1rr0XtA.png" /></figure><pre>Select your gender: male <br>Are you a Seniorcitizen; No=0 and Yes=1 : 1<br>Do you have Partner: No <br>Do you have any Dependents: Yes<br>Lenght of tenure (no. of months with Telco): No<br>Do you have PhoneService? No<br>Do you have MultipleLines: No<br>Do you have InternetService: DSL<br>Do you have OnlineSecurity? No<br>Do you have OnlineBackup? No<br>Do you have DeviceProtection? No<br>Do you have TechSupport? No<br>Do you have StreamingTV? No<br>Do you have StreamingMovies? No<br>which Contract do you use? No<br>Do you prefer PaperlessBilling? No<br>Which PaymentMethod do you prefer? Mailed check<br>Enter monthly charges: 345 <br>Enter total charges: 1234</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*bo0y6bxOPQ533kAkMwdvxg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89c1e5a2ec01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use Classification Models to predict factors that drive Customer Churn]]></title>
            <link>https://medium.com/@albiecofie2000/how-to-use-classification-models-to-predict-factors-that-drive-customer-churn-e1a44428051?source=rss-429e195b95c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1a44428051</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification-models]]></category>
            <dc:creator><![CDATA[Alberta Cofie]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 19:42:47 GMT</pubDate>
            <atom:updated>2023-03-19T19:42:47.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JzAhiAtY2FIRp_LmkqYJXA.jpeg" /></figure><p>Classification is a type of supervised learning in machine learning where the goal is to predict the categorical class labels of new data points based on a labeled dataset. In other words, given a set of data points with known class labels, the objective of classification is to learn a model that can accurately classify new, unseen data points into one of the known classes.</p><p>There are several algorithms that can be used for classification, including logistic regression, decision trees, random forests, support vector machines (SVM), naive Bayes, and k-nearest neighbors (KNN). The choice of algorithm depends on the nature of the data, the number of classes, and the desired performance metrics.</p><p>Classification problems can be binary, where there are only two possible classes, or multi-class, where there are more than two classes. Some common applications of classification include spam filtering, sentiment analysis, image recognition, and medical diagnosis.</p><p>Let’s take practical look at the different types of classification models given a sample dataset.</p><h3>About the Dataset</h3><p>Here, I am using a sample dataset from a Telecommunications company. The goal is analysing the dataset is to find the likelihood of a customer leaving the organization and the key indicators of churn.</p><p>Features of the sample dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RrSEi4hmGFPFBHuOG89lIg.png" /><figcaption>The above describes the columns present in the data</figcaption></figure><p>After importing the required python library,</p><pre># Data handling<br>import pandas as pd<br>import numpy as np <br><br># Vizualisation (Matplotlib, Plotly, Seaborn, etc. )<br>import matplotlib.pyplot as plt <br>import seaborn as sns<br>import plotly.express as px<br><br># EDA (pandas-profiling, etc. )<br>...<br><br># Feature Processing (Scikit-learn processing, etc. )<br>from sklearn import preprocessing</pre><p>a series of steps were taken to explore the data and it was found that:</p><ul><li>The data contains 7043 customers with 21 columns containing various customer information that can be summarized as customer’s demographic, account, and subscription information. The “churn” column which is the column we want to predict contains information on whether the customer churned or not.</li><li>Based on the statistics:</li></ul><p>7043 records are available for analysis</p><p>8684.800000 is the maximum Total Charge</p><p>18.800000 is the minimum Total Charge</p><p>118.750000 is the maximum Monthly charge</p><p>18.250000 is the minimum Monthly charge</p><p>Average tenure is 32 months</p><ul><li>There were no duplicates or missing values in the data.</li><li>The data was split into numerical &amp; categorical data</li></ul><pre># Split the columns into numerical and categorical data<br>df = Telco_churn.copy()<br>df.drop([&#39;customerID&#39;], axis=1, inplace=True)<br><br><br># split the data into features (X) and target variable (y)<br>X = df.drop(&#39;Churn&#39;, axis=1)<br>y = df[&#39;Churn&#39;]</pre><p>Based on the information provided in the dataset, there are some attributes that could potentially be combined to create new features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLpwgLmxwGQxJor_HwI7CQ.png" /><figcaption>New Features Creation</figcaption></figure><pre># Combine &quot;OnlineSecurity&quot; and &quot;DeviceProtection&quot; into a new feature called &quot;SecurityServices&quot;<br>X[&#39;SecurityServices&#39;] = X[&#39;OnlineSecurity&#39;] + X[&#39;DeviceProtection&#39;]<br><br># Replace values with new labels based on whether the customer has no, one, or both security services<br>X[&#39;SecurityServices&#39;] = X[&#39;SecurityServices&#39;].replace({&#39;NoNo&#39;: &#39;NoneSecurityServices&#39;,<br>                                                       &#39;YesNo&#39;: &#39;OnlyOnlineSecurity&#39;,<br>                                                       &#39;NoYes&#39;: &#39;OnlyDeviceProtection&#39;,<br>                                                       &#39;YesYes&#39;: &#39;BothSecurityServices&#39;})<br><br># Drop the original &quot;OnlineSecurity&quot; and &quot;DeviceProtection&quot; features<br>X = X.drop([&#39;OnlineSecurity&#39;, &#39;DeviceProtection&#39;], axis=1)<br><br>X[&#39;SecurityServices&#39;].head()</pre><p>The above code combines the “OnlineSecurity” and “DeviceProtection” features into a new feature called “SecurityServices” and replaces the values with new labels based on whether the customer has no, one, or both security services. It then drops the original “OnlineSecurity” and “DeviceProtection” features.</p><p>This is useful for combining related features into a single feature and creating new labels based on the combinations of the original feature values.</p><pre># Create a new feature called &quot;StreamingServices&quot;<br>X[&#39;StreamingServices&#39;] = X[&#39;StreamingTV&#39;] + X[&#39;StreamingMovies&#39;]<br><br># Replace values with new labels based on whether the customer has no, one, or both Streaming Services<br>X[&#39;StreamingServices&#39;] = X[&#39;StreamingServices&#39;].replace({&#39;NoNo&#39;: &#39;NoneStreamingServices&#39;, <br>                                                         &#39;YesNo&#39;: &#39;OnlyStreamingTV&#39;, <br>                                                         &#39;NoYes&#39;: &#39;OnlyStreamingMovies&#39;, <br>                                                         &#39;YesYes&#39;: &#39;BothStreamingServices&#39;})<br><br># Drop the original &quot;StreamingTV&quot; and &quot;StreamingMovies&quot; features<br>X = X.drop([&#39;StreamingTV&#39;, &#39;StreamingMovies&#39;], axis=1)<br><br>X[&#39;StreamingServices&#39;].head()</pre><p>A new feature called “StreamingServices” has been by concatenating the “StreamingTV” and “StreamingMovies” features. It then replaces the values in the new feature based on whether the customer has no, one, or both streaming services, using a dictionary to map the old values to the new labels. Finally, it drops the original “StreamingTV” and “StreamingMovies” features from the dataset.</p><pre># Combine PhoneService and MultipleLines into a single feature, PhoneServices<br>X[&#39;PhoneServices&#39;] = X.apply(lambda x: &#39;MultipleLines&#39; if x[&#39;MultipleLines&#39;] == &#39;Yes&#39; else &#39;SingleLine&#39;, axis=1)<br><br># Drop PhoneService and MultipleLines columns<br>X.drop([&#39;PhoneService&#39;, &#39;MultipleLines&#39;], axis=1, inplace=True)<br><br>X[&#39;PhoneServices&#39;].head(100)</pre><p>This code combines the “PhoneService” and “MultipleLines” features into a new feature called “PhoneServices” and drops the original “PhoneService” and “MultipleLines” features.</p><p>This is useful for combining related features into a single feature and simplifying the dataset by removing redundant features.</p><pre># Create a new feature called &quot;InternetServices&quot;<br>X[&#39;InternetServices&#39;] = X.apply(lambda row: &#39;DSL Only&#39; if row[&#39;InternetService&#39;] == &#39;DSL&#39; and row[&#39;OnlineBackup&#39;] == &#39;No&#39; else<br>                                          &#39;Fiber Optic Only&#39; if row[&#39;InternetService&#39;] == &#39;Fiber optic&#39; and row[&#39;OnlineBackup&#39;] == &#39;No&#39; else<br>                                          &#39;Internet and Backup&#39; if (row[&#39;InternetService&#39;] == &#39;DSL&#39; or row[&#39;InternetService&#39;] == &#39;Fiber optic&#39;) and row[&#39;OnlineBackup&#39;] == &#39;Yes&#39; else<br>                                          &#39;No Internet Service&#39;, axis=1)<br><br># Drop the original &quot;InternetService&quot; and &quot;OnlineBackup&quot; columns<br>X = X.drop([&#39;InternetService&#39;, &#39;OnlineBackup&#39;], axis=1)<br><br>X[&#39;InternetServices&#39;].head()</pre><p>A new feature called “InternetServices” is created by applying a lambda function to each row of the dataset. The lambda function checks the values of the “InternetService” and “OnlineBackup” features and assigns a label to the new feature based on those values. It then drops the original “InternetService” and “OnlineBackup” features from the dataset.</p><h3>Features encoding</h3><p>Machine learning algorithms require numerical data as inputs, so categorical features must be transformed before they can be used in these algorithms. There are several methods for encoding categorical features in Python however, One-Hot Encoding will be used in this case.</p><blockquote>One-Hot Encoding: This method creates a new binary column for each possible category in a categorical feature. Each column is assigned a value of 0 or 1, indicating whether or not the category is present in the original feature. This method is commonly used when there are a small number of categories and/or when the categories are not ordered.</blockquote><pre>for col in X.columns:<br>    print(f&quot;Column &#39;{col}&#39; categories: {X[col].unique()}&quot;)</pre><p>This code helps us understand the distribution of categorical data in a DataFrame, identifying any missing or unexpected categories, and selecting an appropriate feature encoding method based on the unique categories in each column.</p><h4>Output:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqKS91UaAlZmaacbVkNOtg.png" /></figure><pre># Import the necessary libraries<br>from sklearn.preprocessing import OneHotEncoder<br><br>columns_to_encode = [&#39;Partner&#39;, &#39;Dependents&#39;, &#39;PaperlessBilling&#39;, &#39;gender&#39;]<br><br><br># Create a OneHotEncoder object<br>ohe = OneHotEncoder()<br><br># Fit and transform the columns using the OneHotEncoder<br>encoded_columns = ohe.fit_transform(X[columns_to_encode])<br><br># Create a new DataFrame with the encoded columns<br>encoded_df = pd.DataFrame(encoded_columns.toarray(), columns=ohe.get_feature_names_out(columns_to_encode))<br><br># Drop the original columns from the original DataFrame<br>X.drop(columns_to_encode, axis=1, inplace=True)<br><br># Concatenate the original DataFrame with the new encoded DataFrame<br>X = pd.concat([X, encoded_df], axis=1)</pre><p>The code is performing one-hot encoding on the specified columns in the DataFrame ‘X’ using the scikit-learn OneHotEncoder. The end result is that the original categorical columns in ‘X’ have been replaced with a set of one-hot encoded columns, where each original category is represented by a binary indicator column.</p><pre>columns_to_encode = [&#39;TechSupport&#39;, &#39;Contract&#39;,&#39;PaymentMethod&#39;, &#39;PhoneServices&#39;,<br>                     &#39;SecurityServices&#39;,&#39;StreamingServices&#39;, <br>                     &#39;InternetServices&#39;]<br><br><br># Create a OneHotEncoder object<br>ohe = OneHotEncoder()<br><br># Fit and transform the columns using the OneHotEncoder<br>encoded_columns = ohe.fit_transform(X[columns_to_encode])<br><br># Create a new DataFrame with the encoded columns<br>encoded_df = pd.DataFrame(encoded_columns.toarray(), columns=ohe.get_feature_names_out(columns_to_encode))<br><br># Drop the original columns from the original DataFrame<br>X.drop(columns_to_encode, axis=1, inplace=True)<br><br># Concatenate the original DataFrame with the new encoded DataFrame<br>X = pd.concat([X, encoded_df], axis=1)</pre><p>The columns to be encoded are specified in the list columns_to_encode.</p><p>This process effectively transforms the original categorical features into binary features, with a 1 indicating that a particular category is present and a 0 indicating that it is not.</p><h4>Features Scaling</h4><p>Scaling is a common preprocessing step that helps to ensure all the features have the same range of values, which can help improve the performance of machine learning models.</p><pre>from sklearn.preprocessing import MinMaxScaler<br><br># Create an instance of MinMaxScaler<br>scaler = MinMaxScaler()<br><br># Fit and transform the MonthlyCharges and TotalCharges columns<br>X[[&#39;MonthlyCharges&#39;, &#39;TotalCharges&#39;, &#39;tenure&#39;]] = scaler.fit_transform(X[[&#39;MonthlyCharges&#39;, &#39;TotalCharges&#39;, &#39;tenure&#39;]])</pre><p>This will scale the MonthlyCharges, TotalCharges, and tenure columns using the MinMaxScaler.</p><h3>Machine Learning Modeling</h3><h4>Model #001</h4><h4>RandomForest Classifier over the imbalanced dataset</h4><p>For the first model, we train RandomForest Classifier over the imbalanced dataset. For tree-based algorithms such as Random Forest, Gradient Boosting, and Decision Trees, scaling is not required because they are not affected by the scale of the input features.</p><h4>Create the model</h4><pre>from sklearn.ensemble import RandomForestClassifier<br>from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_score, recall_score, f1_score<br>from imblearn.metrics import geometric_mean_score <br><br># Instantiate the Random Forest model<br>rf = RandomForestClassifier(random_state=42)</pre><p>After importing the necessary modules and instantiated the random forest classifier, you can proceed with fitting the model and evaluating its performance. Before that, however, the dataset needs to be split into training and testing sets.</p><h4>Train the model</h4><pre># Fit the model to the training data<br>rf.fit(X_train, y_train)<br><br># Use the model to make predictions on the test data<br>y_pred_rf = rf.predict(X_test)</pre><h4>Evaluate the model on the evaluation dataset</h4><pre># Print the classification report<br>print(classification_report(y_test, y_pred_rf))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gpSwsF20RNhIw5A_Lb27pQ.png" /></figure><p>This is a classification report for a model’s performance on predicting two classes — 0 and 1.</p><p>In general, a higher value is better as it indicates better overall performance of the model across all classes.</p><p>The precision for class 1 is 0.60, which means that out of all the instances the model predicted as class 1, 60% of them are actually positive.</p><p>The recall for class 1 is 0.48, which means that out of all the actual positive instances, the model correctly identified only 48% of them.</p><p>the F1-score for class 1 is 0.53, which is the weighted average of precision and recall for class 1.</p><h4>Model #002</h4><h4>Decision Tree over the imbalanced dataset</h4><p>For the 2nd model, we train Decision Tree algorithm.</p><p>This algorithm creates a tree-like model of decisions and their possible consequences. It is commonly used for classification and regression problems</p><p>Classification Report for the model after creating &amp; training</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvJTpe5gGWr3nEYXUo23qw.png" /></figure><p>In the second report, precision for class 0 is 0.81, and for class 1, it is 0.48.</p><p>The first classification report has better overall metrics compared to the second classification report.</p><p>In the first classification report, the accuracy is 0.78, while in the second classification report, it’s 0.73. This means that the first model is more accurate at predicting the correct class for new unseen data.</p><p>Similarly, the recall for class 1 in the first classification report is 0.48, while in the second classification report, it’s 0.46. This means that the first model has a better ability to correctly identify all the positive samples (i.e., churn customers) out of all the actual positive samples in the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FB3gnzz3iPKlDQsEBWhZQw.png" /></figure><h4>Model #003</h4><h4>Adaptive Boosting (AdaBoost) over the Imbalanced dataset</h4><p>For the 3rd model, we train an Adaptive Boosting (AdaBoost)algorithm.</p><p>This algorithm builds a series of decision trees, where each subsequent tree tries to correct the errors made by the previous tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBJrF4oFpn4UIWc7pdI8nw.png" /></figure><p>In the third classification report, the precision, recall, and F1-score for class 1 have improved significantly, indicating that the model is performing better in identifying the positive cases.</p><h4>Model #004</h4><h4>Naive_bayes over Balanced Train Data</h4><p>For the 4th model, we train Naive_bayes over Synthetic Minority Oversampling Technique (SMOTE).</p><pre>from imblearn.over_sampling import SMOTE<br><br># Create the SMOTE object<br>smote = SMOTE()<br><br># Apply SMOTE to the training data only<br>X_train_resampled, y_train_resampled = smote.fit_resample(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QepI049kmm-lpCwY7RUwaQ.png" /></figure><h4>Model #005</h4><h4>SVM Over Balanced Train Data</h4><p>For the 5th model, we train SVM. For other algorithms such as SVM and K-Nearest Neighbors, scaling may be necessary to ensure that all features are on a similar scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9nSghhkZ-du8XB3Smf6MQ.png" /></figure><h4>Model #006</h4><h4>K-Nearest Neighbors over balanced Train Data</h4><p>For the 6th model, we train K-Nearest Neighbors over balanced Train Data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjOjOsOraQrqpa_Ey7THlg.png" /></figure><h4>Model #007</h4><h4>Gradient Boosting Classifier over balanced Train Data</h4><p>For the 7th model, we train Gradient Boosting Classifier over balanced Train Data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UisrSmIlMSyeINO2eNGJBQ.png" /></figure><h4>Model #008</h4><h4>catboost over balanced Train Data</h4><p>For the 8th model, we train catboost over balanced Train Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xd48BQ9MV4x6m92I4PszdQ.png" /></figure><h4>Model #009</h4><h4>xgboost over balanced Train Data</h4><p>For the 9th model, we train xgboost over balanced Train Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CnrhReVKBM8YT2l9hXFEA.png" /></figure><h4>Model #010</h4><h4>Adaptive Boosting (AdaBoost) over the Balanced dataset</h4><p>For the 3rd model, we train an Adaptive Boosting (AdaBoost)algorithm.</p><p>This algorithm builds a series of decision trees, where each subsequent tree tries to correct the errors made by the previous tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJOXhpHFqKkOdkCJkZL3Zw.png" /></figure><h3>Comparing all the models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzXiNOUSstSdIDlDXiAuzQ.png" /></figure><p>In conclusion, based on the evaluation metrics, the AdaBoost model trained on the imbalanced dataset performed the best, with an accuracy of 0.795, precision of 0.637, recall of 0.535, and F1-score of 0.581.</p><p>The Naive Bayes model performed well in terms of recall (0.81), but had lower precision and F1-score. The Random Forest model also performed well in terms of accuracy (0.779) and had higher precision and F1-score than the Naive Bayes model.</p><p>Overall, it seems that the ensemble models (AdaBoost, Random Forest, Gradient Boosting, CatBoost, and XGBoost) performed better than the other models on this dataset.</p><p>To access the complete code, check out my git repository:</p><p><a href="https://github.com/AlbieCofie/Customer_Churn_Telco">https://github.com/AlbieCofie/Customer_Churn_Telco</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1a44428051" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Machine Learning Models in Forecasting Sales for Corporación Favorita]]></title>
            <link>https://medium.com/@albiecofie2000/using-machine-learning-models-in-forecasting-sales-for-corporaci%C3%B3n-favorita-4153ab8c255f?source=rss-429e195b95c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4153ab8c255f</guid>
            <category><![CDATA[machine-learning-models]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Alberta Cofie]]></dc:creator>
            <pubDate>Sun, 12 Feb 2023 18:05:47 GMT</pubDate>
            <atom:updated>2023-02-12T18:05:47.428Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wV0ZQqz_-rBw3ewFebFBtQ.jpeg" /></figure><p>Forecasting sales is always tricky but however necessary because, a key factor in a company’s retail performance is the ability to properly estimate sales and manage inventories. <br>The key problem in this case is predicting the sales and inventory requirements for each location to avoid overstocking and under-stocking, allowing the business to offer the greatest customer service while reducing losses and guaranteeing the store’s sustainability.</p><p>One of the best ways to forecast sales is by using Python Machine Learning methods. Taking a look at data gathered from a grocery shop in Ecuador: Corporación Favorita Grocery, we will need to utilize several time series forecasting methods to forecast store sales for the Ecuadorian grocery retailer Corporation Favorita. Dates, stores, product details, whether the item was on sale, and sales statistics are all included in the training data. Separate files are also provided with further information that could be helpful in developing the models.</p><h3>Hypothesis</h3><p><strong><em>Promotion positively impacts sales.</em></strong></p><p><strong>NULL: </strong>There is no significant increase in sales when product-family are on promotion.</p><p><strong>ALTERNATE:</strong> There is a significant increase in sales when products are on promotion.</p><p>All libraries necessary for data analysis and visualization are imported</p><pre># Data handling<br>import pandas as pd<br>import numpy as np<br><br>#display all columns and rows <br>pd.set_option(&#39;display.max_columns&#39;, None)<br><br># Vizualisation (Matplotlib, Plotly, Seaborn, etc. )<br>import matplotlib.pyplot as plt<br>import seaborn as sns <br><br># EDA (pandas-profiling, etc. )<br>from pandas_profiling import ProfileReport<br>from datetime import date</pre><p>Next Step: Load, clean and explore the data. This included: Dropping duplicates, finding and filling missing values with the values before the missing data.</p><pre>Train_df = pd.read_csv(&#39;train.csv&#39;)<br>stores_df = pd.read_csv(&#39;stores.csv&#39;)<br>Transaction_df = pd.read_csv(&#39;transactions.csv&#39;)<br>oil_df = pd.read_csv(&#39;oil.csv&#39;)<br>submission_df = pd.read_csv(&#39;sample_submission.csv&#39;)<br>test_df = pd.read_csv(&#39;test.csv&#39;)<br>Holiday_df = pd.read_csv(&#39;holidays_events.csv&#39;)</pre><p>The date column was split in day, month and year to be used for further analysis.</p><pre>Train_df[&quot;date&quot;] = pd.to_datetime(Train_df[&quot;date&quot;], format=&#39;%Y-%m-%d&#39;)<br>Transaction_df[&quot;date&quot;] = pd.to_datetime(Transaction_df[&quot;date&quot;], format=&#39;%Y-%m-%d&#39;)<br>oil_df[&quot;date&quot;] = pd.to_datetime(oil_df[&quot;date&quot;], format=&#39;%Y-%m-%d&#39;)<br>Holiday_df[&quot;date&quot;] = pd.to_datetime(Holiday_df[&quot;date&quot;], format=&#39;%Y-%m-%d&#39;)</pre><p>To have a 360 degree view of the data, the datasets are merged based on the relationships between them and the date column was set as index.</p><pre>merged_df = pd.merge(Train_df, stores_df, on=&#39;store_nbr&#39;, how=&#39;left&#39;)<br>merged_df = pd.merge(merged_df,Transaction_df, on=[&#39;store_nbr&#39;,&#39;date&#39;], how=&#39;left&#39;)<br>merged_df = pd.merge(merged_df,oil_df, on=[&#39;date&#39;], how=&#39;left&#39;)<br>merged_df = pd.merge(merged_df,Holiday_df, on=[&#39;date&#39;], how=&#39;left&#39;)</pre><p>Further data cleaning processes were done and the next step is to answer a couple of questions. Most of which help prove the Hypothesis stated above.</p><p><strong>Question 1: Is the train dataset complete?</strong></p><p>Using a heatmap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*KHxVcsQ7MZmeb0LVTHdjlQ.png" /><figcaption>Using heatmap to show if the data is complete</figcaption></figure><p>Checking for missing dates:</p><pre>expected_dates = pd.date_range(start=merged_df[&#39;day&#39;].min(), end=merged_df[&#39;day&#39;].max())<br>missing_dates = expected_dates.difference(merged_df[&#39;day&#39;])<br>missing_dates</pre><p><strong><em>Output:</em></strong></p><pre>DatetimeIndex([&#39;2013–12–25&#39;, &#39;2014–12–25&#39;, &#39;2015–12–25&#39;, &#39;2016–12–25&#39;], dtype=&#39;datetime64[ns]&#39;, freq=None</pre><p>From the result, the train dataset is mising 4 dates. These missing dates follow a sequence. All the years are missing dates of December 25th (12,25). This date is also a holiday in Ecuador. This analysis therefore assumes that no data was taken on this day every year as the shops may be closed on that date each year.</p><p><strong>Question 2: Which dates have the lowest and highest sales for each year?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*6tBM_1uJaPo_KkProdbV5Q.png" /><figcaption>A chart showing the total Sales by Year</figcaption></figure><p>The Company recorded the highest sales in 2016, followed by 2015 and then 2014. The lowest sales was recorded in 2013 followed by 2017. However, the data for 2017 was collected for only 8 months (2017/08/15) which may account for the ranking. So we focus on the highest (2016) and lowest (2013)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*zFZkW7RTAwcYtYT41SPMjw.png" /><figcaption>Using seaborn to create a bar plot, showing the maximum sales for each year</figcaption></figure><p><strong>Question 3: Did the Earthquake in April 2016 affect sales?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*3RSxpPNZum8a2O7YWz__Sg.png" /><figcaption>So although the earthquake happened on the 16th of April, the 17th saw a sharp increase in sales, so we can confidently say the event did not affect sales.</figcaption></figure><p><strong>Question 4: Are certain groups of stores selling more products? (Cluster, city, state, type)?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*e0uqntlFEN-YgzDYz1o98w.png" /></figure><p>Store number 43 has the highest sales</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J260BQBg6oBdq0BXJUSaKw.png" /></figure><p>Product family <strong>Grocery I </strong>had the most sales</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*Kx0izqWsges7eYekY_P3-Q.png" /></figure><p>The highest sales were made in the city of Quito</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*Bvo9cPb9Bsl7ST_X6xAVcA.png" /></figure><p>The State of Pichincha has the highest number of sales</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*5VBQbQB1fA_2aUKzroAimA.png" /></figure><p>Store type A recorded the highest number of sales.</p><p><strong>Question 5: Are sales affected by promotions, oil prices and holidays?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*lhdO4YQPfvx1Pii0TtUzQA.png" /><figcaption>A pie chart to show the distribution of the two labels</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*_SD8G9xlNNnrXImSfxUPTQ.png" /><figcaption>Determine the correlation between sales and onpromotion</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*3o17RkeGkMMbNinRrpobDQ.png" /></figure><p>The bar chart above visualises the average sales for each year, separated by promotion status.</p><p>Finding that sweet spot in terms of the number of products on promtion that can maximize sales. As can be observed below, having about 250 products on sale can optimise and improve average sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*FSniGUUqnwDepdzcKyFoGg.png" /></figure><h3>Using Traditional Machine Learning methods</h3><p>Importing libraries:</p><pre>from sklearn import preprocessing<br>from sklearn.ensemble import RandomForestClassifier,RandomForestRegressor,GradientBoostingRegressor<br>from sklearn.tree import DecisionTreeRegressor<br>from sklearn.metrics import mean_squared_error,mean_absolute_error,mean_squared_log_error</pre><p><strong>Using the Linear Regression Model</strong></p><pre># Import the linear regression model<br>from sklearn.linear_model import LinearRegression<br><br># Initialize the linear regression model<br>reg = LinearRegression()<br><br># Fit the linear regression model to the training data<br>reg.fit(X_train, y_train)<br><br># Predict on the validation test data<br>y_pred_lg = reg.predict(X_validation_test)<br><br># Calculate the RMSLE<br>rmsle_lg = np.sqrt(mean_squared_log_error(y_validation_test, y_pred))<br>#print(&quot;RMSLE: &quot;, rmsle)<br><br>print(&#39;Mean Absolute Error for LinearRegression:&#39;, mean_absolute_error(y_validation_test, y_pred_lg))<br>print(&#39;Mean Squared Log Error for LinearRegression:&#39;, mean_squared_log_error(y_validation_test, y_pred_lg))<br>print(&#39;Mean Squared Error for LinearRegression:&#39;, mean_squared_error(y_validation_test, y_pred_lg))<br>print(&#39;Root Mean Squared Error for LinearRegression:&#39;, np.sqrt(mean_squared_error(y_validation_test, y_pred_lg)))<br>print(&#39;Root Mean Squared Log Error for LinearRegression:&#39;, np.sqrt(mean_squared_log_error(y_validation_test, y_pred_lg)))<br><br></pre><p>This code is fitting a linear regression model from scikit-learn’s LinearRegression class to training data, and then using the fitted model to make predictions on validation test data.</p><p>It then calculates various evaluation metrics such as mean absolute error, mean squared error, mean squared log error, root mean squared error, and root mean squared log error to evaluate the performance of the model on the validation test data.</p><p>These evaluation metrics are calculated using the mean_absolute_error, mean_squared_error, mean_squared_log_error, and np.sqrt functions from scikit-learn&#39;s metrics module.</p><p>Output:</p><pre>Mean Absolute Error for LinearRegression: 0.5478638617146765<br>Mean Squared Log Error for LinearRegression: 0.11376193571249157<br>Mean Squared Error for LinearRegression: 0.4442382787974733<br>Root Mean Squared Error for LinearRegression: 0.6665120244957875<br>Root Mean Squared Log Error for LinearRegression: 0.33728613329410917</pre><p><strong>Using A Random Forest Regression Model</strong></p><pre>#RandomForestClassifier()<br>#from sklearn.ensemble import RandomForestClassifier,RandomForestRegressor,GradientBoostingRegressor<br>rfm =RandomForestRegressor(n_estimators=100,max_depth=6,n_jobs=3, random_state=10)<br>rfm.fit(X_train, y_train)<br><br># RandomForestRegressor Prediction<br>y_pred_Rf= rfm.predict(X_validation_test)<br><br># Calculate the RMSLE<br>rmsle_RF = np.sqrt(mean_squared_log_error(y_validation_test, y_pred_Rf))<br><br>print(&#39;Mean Absolute Error for RandomForestRegressor:&#39;, mean_absolute_error(y_validation_test, y_pred_Rf))<br>print(&#39;Mean Squared Log Error for RandomForestRegressor:&#39;, mean_squared_log_error(y_validation_test, y_pred_Rf))<br>print(&#39;Mean Squared Error for RandomForestRegressor:&#39;, mean_squared_error(y_validation_test, y_pred_Rf))<br>print(&#39;Root Mean Squared Error for RandomForestRegressor:&#39;, np.sqrt(mean_squared_error(y_validation_test, y_pred_Rf)))<br>print(&#39;Root Mean Squared Log Error for RandomForestRegressor:&#39;, np.sqrt(mean_squared_log_error(y_validation_test, y_pred_Rf)))<br></pre><p>We are training a random forest regression model from scikit-learn’s RandomForestRegressor class on the training data. The RandomForestRegressor is being initialized with the following parameters:</p><ul><li>n_estimators: The number of trees in the forest. Here, it is set to 100.</li><li>max_depth: The maximum depth of the tree. Here, it is set to 6.</li><li>n_jobs: The number of parallel jobs to run. Here, it is set to 3.</li><li>random_state: The seed of the random number generator used when shuffling the data. Here, it is set to 10.</li></ul><p>Once the model is initialized, it is trained on the training data using the fit method.</p><p>The code goes on to make predictions on the validation test data using the trained random forest regression model. It then calculates various evaluation metrics such as mean absolute error, mean squared error, mean squared log error, root mean squared error, and root mean squared log error to evaluate the performance of the model on the validation test data. These evaluation metrics are calculated using the mean_absolute_error, mean_squared_error, mean_squared_log_error, and np.sqrt functions from scikit-learn&#39;s metrics module.</p><p>Output:</p><pre>Mean Absolute Error for RandomForestRegressor: 0.5181034077206986<br>Mean Squared Log Error for RandomForestRegressor: 0.0990607743260502<br>Mean Squared Error for RandomForestRegressor: 0.3962637344533816<br>Root Mean Squared Error for RandomForestRegressor: 0.6294948248026997<br>Root Mean Squared Log Error for RandomForestRegressor: 0.31473921637770247</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4153ab8c255f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Indian Startup Ecosystem — Which Industry is more likely to get Funding?]]></title>
            <link>https://medium.com/@albiecofie2000/indian-startup-ecosystem-which-industry-is-more-likely-to-get-funding-d00222ee47ff?source=rss-429e195b95c6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d00222ee47ff</guid>
            <category><![CDATA[funding]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[technology-strategy]]></category>
            <category><![CDATA[indian-companies]]></category>
            <dc:creator><![CDATA[Alberta Cofie]]></dc:creator>
            <pubDate>Sun, 15 Jan 2023 22:34:01 GMT</pubDate>
            <atom:updated>2023-01-15T22:34:01.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Indian Startup Ecosystem — Which Industry is more likely to get Funding?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeFoMKC6pvD4C9UgMdLWGA.jpeg" /><figcaption>The Indian StartUp Ecosystem</figcaption></figure><p>In the last couple of months, I researched on the Indian startup ecosystem — not just for fun but because I wanted to understand how it works, especially which industry is more likely to get the most funding. As a data scientist, I did what I do best — use the data I came across by analyzing it and visualizing it to facilitate in making a more informed decision.</p><blockquote>India has one of the world’s fastest expanding economies. A huge number of unicorn startups have emerged in the Indian startup ecosystem over the last decade, with a global influence. Startups may be small businesses, but they can have a huge impact on economic growth. They generate more jobs, which leads to increased employment, and increased employment leads to a healthier economy. Not only that, but startups can also contribute to economic vitality by encouraging innovation and injecting competition.</blockquote><p>In this article, I will be taking you through the relevant processes and steps I went through to understand the Indian startup ecosystem using P<strong>ython</strong>. Note that I used data gathered on startups in India that got funding from 2018–2021. I analysed the data per year and one thing was for sure — the data cleaning process was not straightforward since there were several inconsistencies in the dataset for each year. But that was not the main takeaway. It became rather clear at the end of my analysis that Technological companies are more likely to get funded.</p><p>Before the data cleaning and analysing, there is a need to import all necessary libraries.</p><pre>#Import packages (numpy, pandas and nltk) for preprocessing </pre><pre>import numpy as np </pre><pre>import pandas as pd </pre><pre>import nltk</pre><pre>import matplotlib.pyplot as plt </pre><pre>%matplotlib inline </pre><pre>import seaborn as sns </pre><pre>sns.set_style(&#39;whitegrid&#39;)</pre><pre>plt.style.use(&quot;fivethirtyeight&quot;)</pre><pre>#display all columns and rows </pre><pre>pd.set_option(&#39;display.max_columns&#39;, None)</pre><pre>pd.set_option(&#39;display.max_rows&#39;, None)</pre><p>Click on the links below for more information on the libraries that were imported,</p><ul><li>Numpy: <a href="https://numpy.org/doc/stable/user/absolute_beginners.html">https://numpy.org/doc/stable/user/absolute_beginners.html</a>.</li><li>Pandas: <a href="https://www.educative.io/answers/what-is-pandas-in-python">https://www.educative.io/answers/what-is-pandas-in-python</a>.</li><li>NLTK: <a href="https://www.nltk.org/">https://www.nltk.org</a>.</li><li>Matplotlib.pyplot: <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwirkpG7sMj8AhVsU6QEHU7ICWsQFnoECAkQAw&amp;url=https%3A%2F%2Fwww.scaler.com%2Ftopics%2Fmatplotlib%2Finstall-matplotlib%2F&amp;usg=AOvVaw2evQBK9v-P4zBsIw86wA07">How to Install Matplotlib in Python? — Scaler Topicshttps://www.scaler.com › topics › install-matplotlib</a></li></ul><p>2. Data Loading</p><pre>startup_funding_2018 = pd.read_csv(&#39;startup_funding2018.csv&#39;, <br>    usecols = [&#39;Company Name&#39;,&#39;Industry&#39;,&#39;Round/Series&#39;,&#39;Amount&#39;,&#39;Location&#39;])</pre><pre>startup_funding_2018.rename(columns = {&#39;Industry&#39;:&#39;Sector&#39;}, inplace = True)</pre><pre>startup_funding_2018.rename(columns = {&#39;Round/Series&#39;:&#39;Stage&#39;}, inplace = True)</pre><pre>startup_funding_2018[&#39;Funding Year&#39;] = &quot;2018&quot;</pre><pre>startup_funding_2018[&#39;Funding Year&#39;] = startup_funding_2018[&#39;Funding Year&#39;].astype(int)</pre><ul><li>Taking a look at the datasets across the years, certain columns were common in all the datasets and were deemed relevant in the analysis. So in importing the datasets, specific columns were imported. These included: <strong><em>Company Name, Industry, Round/Series, Amount &amp; Location.</em></strong></li><li>To ensure consistency, some columns were renamed to match the columns in the dataset of subsequent years. Industry was renamed ‘Sector’ and Round/Series was renamed ‘Stage’.</li><li>A new column named ‘Funding Year’ was also added to each dataset and all rows were assigned the value ‘2018’ ‘2019’ ‘2020’ or ‘2021’ depending on the dataset.</li><li>Majority of the datasets (2019–2021) had all amount currency in dollars however, in the 2018 dataset, a few of the amounts were in Rupees and the rest in dollars. The rupees were converted to dollars using the average exchange rate in 2018 found online.</li><li>With the exception of 2018, all the other datasets had other relevant columns such as the year the startup was founded as well as the investor that provided funding. These columns were imported because there was a need to understand if the number of years that a startup had been</li><li>The datasets were analysed for NULL &amp; duplicate values. The rows with NUL values were kept to be analysed later but the duplicate values were dropped.</li></ul><p>After the data cleaning process, all datasets were concatenated and merged into 1 dataframe with 2873 rows and 8 columns in total.</p><p>Displaying the top 5 &amp; last 5 columns of the dataframe.</p><p>Top 5 columns</p><pre>startup_funding_Full.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ppqN9tkmYv1-GfLSCJ3HtQ.png" /></figure><p>Last 5 columns</p><pre>startup_funding_Full.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rg_3fCzeOkXsTrCM6_OUUQ.png" /></figure><p>In order to come to a clear conclusion about which industry/sector is more likely to get the most funding. The following question needed to be answered.</p><p>Does the type of industry affect the success of getting funded?</p><pre>sector_analysis = startup_funding_Full[&#39;Sector&#39;].apply(lambda x: str(x).replace(&#39;,&#39;, &#39;&#39;))<br>sector_analysis = sector_analysis.apply(lambda x: str(x).replace(&#39;&amp;&#39;, &#39;&#39;))<br>sector_analysis = sector_analysis.apply(lambda x: str(x).replace(&#39;startup&#39;, &#39;&#39;))<br>sector_analysis = sector_analysis.apply(lambda x: str(x).replace(&#39;technology&#39;, &#39;&#39;))</pre><pre># Concatenate all the words in the sector_analysis series into a single string<br>txt = sector_analysis.str.lower().str.cat(sep=&#39; &#39;)</pre><pre>words = txt.split()</pre><pre># Create a dictionary to store the word counts<br>word_counts = {}</pre><pre># Loop through the list of words and update the count for each word<br>for word in words:<br>    if word in word_counts:<br>        word_counts[word] += 1<br>    else:<br>        word_counts[word] = 1<br>        <br># Sort the dictionary by the count and get the top 10 words<br>top_10 = dict(sorted(word_counts.items(), key=lambda x: x[1], reverse=True)[:10])</pre><pre>#print(top_10)</pre><p>The code above is trying to analyze the “Sector” column of a DataFrame named “startup_funding_Full” and extract the most common words from it.</p><p>It does this by:</p><p>1- Replacing all ‘,’ and ‘&amp;’ with an empty string in the ‘Sector’ column, this is done to avoid having these characters mixed with the words in the sector column</p><p>2- Replacing all instances of the word ‘startup’ and ‘technology’ with an empty string in the sector column, this is done to not consider these words when getting the top 10 most common words</p><p>3- Concatenating all the words in the “sector_analysis” into a single string and make all the characters lower case</p><p>4- creating a variable words that contains the list of all words from the concatenated string obtained in step 3</p><p>5- creating a dictionary named word_counts that will store the count of each word from the list obtained in step 4</p><p>6- iterating over the words list and updating the count for each word in the dictionary</p><p>7- sorting the dictionary by the count of each word in descending order</p><p>8- getting the top 10 words that have the highest counts and this dictionary should contain the top 10 most common words in the ‘Sector’ column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*X40pDWXsXp1h62Hjv3P05A.png" /></figure><pre>startup_funding_Full.Sector = startup_funding_Full.Sector.astype(str)</pre><pre>keywords = [&quot;fintech&quot;, &quot;edtech&quot;,&quot;services&quot;, &quot;food&quot;,&quot;financial&quot;,&quot;e-commerce&quot;, &quot;health&quot;]</pre><pre>keyword_totals = {}</pre><pre>for keyword in keywords:<br>    <br>    keyword_totals[keyword] = startup_funding_Full[startup_funding_Full[&#39;Sector&#39;].apply(lambda x: keyword in x)].Amount.sum()<br>    <br># keyword_totals is a dictionary that store the sum of amounts <br>#for a corresponding keyword</pre><p>This code is trying to analyze the “Sector” column of a DataFrame named “startup_funding_Full” and extract the sum of the “Amount” column for all rows where a keyword from a predefined list appears in the “Sector” column.</p><p>It does this by:</p><p>1- Changing the datatype of the “Sector” column to a string, this allows the use of string methods on the column</p><p>2- Defining a list of keywords [“fintech”, “edtech”, “services”, “food”, “financial”, “e-commerce”, “health”] that will be used to search in the “Sector” column</p><p>3- Creating an empty dictionary keyword_totals that will store the sum of “Amount” for each keyword.</p><p>4- Iterating over the keywords list, for each keyword</p><p>it filters the rows from the DataFrame that have the current keyword in the “Sector” column,then it sums the Amount of the filtered dataframe, this will give the sum of the “Amount” for all rows that contain the current keyword in the “Sector” column it then adds this sum of the amount as the value and the current keyword as the key to the keyword_totals dictionary</p><p>At the end of this process, the keyword_totals dictionary should contain the sum of the “Amount” for each keyword in the keywords list that appears in the “Sector” column.</p><pre>keyword_totals</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-_xxncAsHmx2aJ_aSfwgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*u2KvbW5ZVvve2ODndpEIXA.png" /></figure><p>To further answer the question about which industry is more likely to receive funding, a list which contains keywords associated with technology like Fintech, edtech, robotics etc was created. This was generated manually by skimming through the sector attribute of the full datatset.</p><pre>keywords = [&quot;fintech&quot;, &quot;edtech&quot;, &quot;e-commerce&quot;,&quot;robotics&quot;, &quot;cryptocurrency&quot;, &quot;esports&quot;,<br>            &quot;automotive &quot;, &quot;engineering &quot;,&quot;telecommunications&quot;, &quot;electricity&quot;, <br>            &quot;agritech&quot;, &quot;healthtech&quot;, &quot;technology&quot;, &quot;e-marketplace&quot;, &quot;social&quot;, <br>            &quot;tech&quot;, &quot;gaming&quot;, &quot;computer&quot;, &quot;femtech&quot;, &quot;solar&quot;, &quot;embedded &quot;, <br>            &quot;software &quot;, &quot;saas &quot;, &quot;e-commerce&quot;, &quot;analytics&quot;, &quot;ar&quot;, &quot;vr&quot;, &quot;crm&quot;, &quot;nft&quot;, <br>            &quot;e-learning&quot;, &quot;iot&quot;, &quot;e-commerce&quot;, &quot;e-mobility&quot;, &quot;api &quot;, <br>            &quot;ecommerce&quot;, &quot;media&quot;, &quot;ai&quot;,&quot;sportstech&quot;, &quot;traveltech&quot;, &quot;online&quot;, <br>            &quot;information&quot;, &quot;automobile&quot;, &quot;e-commerce&quot;, &quot;biotechnology&quot;, &quot;applications&quot;,  <br>            &quot;it&quot;, &quot;edtech&quot;, &quot;energy&quot;, &quot;computer&quot;, &quot;agritech&quot;, &quot;online &quot;, &quot;virtual &quot;, <br>            &quot;fintech&quot;, &quot;internet&quot;, &quot;automation&quot;, &quot;cloud&quot;, &quot;apps&quot;, &quot;chatbot&quot;, <br>            &quot;digital&quot;, &quot;cleantech&quot;, &quot;ev&quot;, &quot;manufacturing&quot;,&quot;networking&quot;, &quot;mobile &quot;, <br>            &quot;electronics&quot;, &quot;logitech&quot;, &quot;solar&quot;, &quot;insurtech&quot;,&quot;finance&quot;, &quot;electric&quot;, <br>            &quot;fmcg&quot;, &quot;intelligence&quot;, &quot;blockchain&quot;,&quot;crypto&quot;, &quot;foodtech &quot;, &quot;audio &quot;, <br>            &quot;nanotechnology&quot;, &quot;biometrics&quot;, &quot;auto-tech&quot;, &quot;biotech&quot;, &quot;data &quot;,  &quot;autonomous &quot;, <br>            &quot;AI&quot;, &quot;machine learning&quot;, &quot;e-market&quot;, &quot;proptech&quot;, &quot;machine learning &quot;]</pre><pre>def check_keywords(string, keywords):<br>    for keyword in keywords:<br>        if keyword in string:<br>            return &quot;technology&quot;<br>    return &quot;non-technology&quot;</pre><p>This code defines a function named check_keywords that takes two inputs, string and keywords.</p><p>The function goes through each keyword in the list of keywords and check if it is in the input string, if it finds any match it returns “technology”, otherwise it returns “non-technology”</p><p>So overall this function takes a string and a list of keywords as inputs, then checks if the string contains any of the keywords, if it contains any it returns the technology, otherwise it returns non-technology.</p><pre># Select only the rows with non-null values in the Sector column<br>startup_funding_Full = startup_funding_Full[startup_funding_Full[&quot;Sector&quot;].notnull()]</pre><pre># Convert the Sector column to a Pandas Series<br>sector_series = pd.Series(startup_funding_Full[&quot;Sector&quot;])</pre><pre>#startup_funding_Full[&quot;Sector&quot;].str.apply(check_keywords, keywords=keywords)</pre><pre># Apply the check_keywords function to the Series<br>sector_series = sector_series.apply(check_keywords, keywords=keywords)</pre><pre># Convert the resulting Series back to a column in the startup_funding_Full DataFrame<br>startup_funding_Full[&quot;label&quot;] = sector_series</pre><p>This code is trying to add a new column ‘label’ to the DataFrame “startup_funding_Full” that categorizes the sectors of the startups into either “technology” or “non-technology” based on whether they contain certain keywords or not.</p><p>It does this by:</p><p>1- Selecting only the rows of the “startup_funding_Full” DataFrame that have non-null values in the “Sector” column</p><p>2- Creating a new Pandas Series ‘sector_series’ which contains all the values in the “Sector” column of the “startup_funding_Full” DataFrame</p><p>3- applying the function check_keywords to the ‘sector_series’ using the keyword list that is passed as an argument, and assigns the result of each function call to the same element in the sector_series</p><p>4- creating a new column in the “startup_funding_Full” DataFrame named “label” which contains the values of the ‘sector_series’</p><p>In summary, this code first selects the non-null Sector rows, then creates a new series from the Sector column of the dataframe, then applies the check_keywords function to the series, and finally, it creates a new column in the dataframe which contains the result of the function applied to the series.</p><pre># Select only the rows with non-null values in the Sector column<br>startup_funding_Full = startup_funding_Full[startup_funding_Full[&quot;Sector&quot;].notnull()]</pre><pre># Convert the Sector column to a Pandas Series<br>sector_series = pd.Series(startup_funding_Full[&quot;Sector&quot;])</pre><pre>#startup_funding_Full[&quot;Sector&quot;].str.apply(check_keywords, keywords=keywords)</pre><pre># Apply the check_keywords function to the Series<br>sector_series = sector_series.apply(check_keywords, keywords=keywords)</pre><pre># Convert the resulting Series back to a column in the startup_funding_Full DataFrame<br>startup_funding_Full[&quot;label&quot;] = sector_series</pre><p>The first line of the code selects only the rows from the ‘startup_funding_Full’ DataFrame where the ‘Sector’ column is not null. This means that any rows in the DataFrame where the ‘Sector’ column is empty or null will be removed.</p><p>The second line of the code converts the ‘Sector’ column of the ‘startup_funding_Full’ DataFrame to a Pandas Series object. A Series is a one-dimensional labeled array capable of holding any data type.</p><p>The third line of the code applies a function called ‘check_keywords’ to the ‘sector_series’ Series. The function is passed a list of keywords as a parameter, it checks the keyword in the series, if it is present then it returns the keyword otherwise returns ‘Other’.</p><p>The fourth line of the code converts the resulting Series back to a column in the ‘startup_funding_Full’ DataFrame and adds it to the dataframe as ‘label’ column.</p><pre>startup_funding_Full[&quot;label&quot;].value_counts(normalize=True)*100</pre><p>This code is counting the number of occurrences of each unique value in the ‘label’ column of the ‘startup_funding_Full’ DataFrame, and then normalizing the counts by dividing by the total number of values in the ‘label’ column.</p><p>The value_counts() function returns the frequency of each unique value in the &#39;label&#39; column in descending order. By default, it returns the count of each value, but when the normalize parameter is set to True, it returns the relative frequency of each value, that is, the count of each value divided by the total number of values in the &#39;label&#39; column.</p><p>The output is a new DataFrame which lists unique values in the column as index and their corresponding percentage as values.</p><p>The final step is multiplying the value by 100, to get the percentage of each unique value in the ‘label’ column.</p><p>The output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*qR1yhvcHcUHWsus1OYow3w.png" /></figure><p>Now, the above data is visualized below to show the distribution on the two labels</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*jA97288rHiuj5wcq61BtQw.png" /></figure><p>Set the float format to a custom function that formats the number as a string without the exponential notation</p><pre>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;{:.0f}&#39;.format(x))</pre><pre>group_obj = startup_funding_Full[&quot;Amount&quot;].groupby(startup_funding_Full[&quot;label&quot;]).agg([&#39;max&#39;,&#39;mean&#39;, &#39;sum&#39;])</pre><pre>group_obj</pre><p>The output;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*9vt3icN0Q2ZwI1bBRZbj8A.png" /></figure><p>In conclusion, Technological industries have a higher success rate of being funded because based on the above analysis, they have received the most funding over the period of 4 years (i.e 2018–2021). Another major takeaway is that Fintech and edtech are two of the most active sectors in the Indian startup ecosystem. So if you are looking to startup a business in India, with the hope of getting funding at some stage, it is advisable to startup a company that is in the Technological Industry.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d00222ee47ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>