<?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 KHADIJA NID SAID on Medium]]></title>
        <description><![CDATA[Stories by KHADIJA NID SAID on Medium]]></description>
        <link>https://medium.com/@khadijaagadir2018?source=rss-d6601d526e20------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OIV-wxFhbSH94eydBVaCcA.png</url>
            <title>Stories by KHADIJA NID SAID on Medium</title>
            <link>https://medium.com/@khadijaagadir2018?source=rss-d6601d526e20------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:15:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khadijaagadir2018/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[Credit Risk Prediction with Python: A Practical Multiclass Classification Assessment]]></title>
            <link>https://medium.com/@khadijaagadir2018/credit-risk-prediction-with-python-a-practical-multiclass-classification-assessment-4fe06bce5b4a?source=rss-d6601d526e20------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fe06bce5b4a</guid>
            <category><![CDATA[data-science-projects]]></category>
            <category><![CDATA[predictive-analytics]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[multiclass-classification]]></category>
            <category><![CDATA[credit-risk-modeling]]></category>
            <dc:creator><![CDATA[KHADIJA NID SAID]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 16:32:43 GMT</pubDate>
            <atom:updated>2026-12-01T16:32:43.138Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From applicant data to risk classification: a hands-on exercise covering data cleaning, data querying, exploratory analysis, multiclass classification and model evaluation.</em></p><p><strong>Part 2 of the Sharing Is Caring series | Machine Learning Assessment Preparation</strong></p><h3>Introduction</h3><p>In the first article of this series, I worked on a Customer Churn Prediction problem, where the objective was to predict one of two possible outcomes: whether a customer would leave or stay.</p><p>This time, I wanted to explore another fundamental Machine Learning task: <strong>Multiclass Classification</strong>.</p><p>Unlike binary classification, multiclass classification involves predicting one class among three or more possible categories.</p><p>For this project, I chose a Credit Risk Prediction problem.</p><p>Imagine a bank receiving loan applications and wanting to classify applicants according to their estimated level of credit risk. This is the problem we will try to solve.</p><p>As in the previous project, I structured the exercise around four main areas:</p><p><strong>Data Cleaning &amp; Preprocessing</strong></p><p><strong>Data Querying &amp; Manipulation</strong></p><p><strong>Exploratory Data Analysis (EDA) &amp; Visualization</strong></p><p><strong>Machine Learning &amp; Predictive Modeling</strong></p><p>The goal is not simply to train a model and obtain a score. It is to understand the complete workflow, make appropriate decisions at each stage, and interpret the results.</p><p>Let’s get started!</p><h3>Understanding the Business Problem</h3><p>Imagine working with a bank that receives loan applications every day.</p><p>Credit officers need to assess the risk associated with each applicant before making a lending decision.</p><p>To support their work, the bank wants to classify applicants into three categories.</p><p><strong>Low Risk:</strong> Applicants with a relatively lower estimated risk.</p><p><strong>Medium Risk:</strong> Applicants with an intermediate estimated risk.</p><p><strong>High Risk:</strong> Applicants with a relatively higher estimated risk.</p><p>Our target variable is risk_level.</p><p>This is a supervised learning problem because the dataset contains historical applicants with an existing risk label. The model learns patterns from these examples and predicts a risk category for new applicants.</p><p><strong>Business objective:</strong> Support credit officers by identifying applications that may require additional review.</p><p>An important distinction: a model’s predicted risk category is not a final lending decision. Real credit decisions require appropriate policies, human oversight, fairness assessments and regulatory compliance.</p><h3>Understanding the Dataset</h3><p>For this exercise, I used a synthetic dataset containing approximately 3,000 loan applications. Each row represents one applicant.</p><p>The dataset contains 18 columns, covering several types of information.</p><p><strong>Personal information:</strong> Age, gender, marital status and education.</p><p><strong>Professional information:</strong> Employment type and years employed.</p><p><strong>Financial information:</strong> Annual income, loan amount, loan term and debt-to-income ratio.</p><p><strong>Credit history:</strong> Credit history years, number of late payments and existing loans.</p><p><strong>Other information:</strong> Application date, home ownership and city.</p><p><strong>Target variable:</strong> risk_level, with three possible values: Low, Medium and High.</p><p>The dataset also contains deliberately introduced data-quality problems, including duplicates, missing values, numeric values stored as text, inconsistent categorical formats, mixed date formats and impossible values.</p><p>These issues make the exercise useful for practising data preparation before modelling.</p><h3>Task 1: Data Cleaning &amp; Preprocessing</h3><p>Before building a Machine Learning model, we need to understand the dataset and correct its inconsistencies.</p><h3>Inspecting the dataset</h3><p>The first step is to load the data using Pandas and inspect its structure.</p><pre>import pandas as pd<br>import numpy as np</pre><pre>df = pd.read_csv(&quot;../data/credit_risk.csv&quot;)</pre><pre>print(df.shape)<br>print(df.dtypes)<br>print((df.isna().mean() * 100).round(2))<br>print(&quot;Duplicates:&quot;, df.duplicated().sum())</pre><p>The initial dataset contains 3,040 rows and 18 columns.</p><p>During the inspection, we identify missing values in several columns, including education, annual income, credit history years and debt-to-income ratio.</p><p>We also find 40 duplicated rows.</p><h3>Removing duplicate applicants</h3><p>Each applicant should appear only once in the dataset.</p><p>We remove duplicates using the applicant identifier:</p><pre>df = df.drop_duplicates(<br>    subset=&quot;applicant_id&quot;<br>).reset_index(drop=True)</pre><p>This removes 40 duplicated records.</p><p>Why is this important?</p><p>Imagine calculating the percentage of High-risk applicants while some applicants appear more than once. Those records would be counted multiple times and could distort our statistics.</p><p><strong>Lesson:</strong> Always check duplicates using the appropriate business identifier, not only exact duplicate rows.</p><h3>Converting annual income into numeric values</h3><p>One interesting issue in this dataset is that some annual income values are stored as text.</p><p>For example, we may encounter values such as $45,000 instead of 45000.</p><p>Before performing calculations, we need to convert these values into numeric data.</p><pre>df[&quot;annual_income&quot;] = (<br>    df[&quot;annual_income&quot;]<br>    .astype(str)<br>    .str.replace(r&quot;[$€,]&quot;, &quot;&quot;, regex=True)<br>    .str.strip()<br>)</pre><pre>df[&quot;annual_income&quot;] = pd.to_numeric(<br>    df[&quot;annual_income&quot;],<br>    errors=&quot;coerce&quot;<br>)</pre><p>We also consider values less than or equal to zero, and values above 5,000,000, invalid. These are converted into missing values before imputation.</p><p>This is an important reminder: a column may look numeric but still have an object or string data type.</p><h3>Standardizing categorical variables</h3><p>Categorical columns can contain inconsistent values.</p><p>For example, &quot; male &quot;, &quot;MALE&quot; and &quot;Male&quot; should represent the same category.</p><p>We standardize the relevant text columns by removing unnecessary spaces and applying consistent capitalization.</p><pre>df[&quot;gender&quot;] = (<br>    df[&quot;gender&quot;]<br>    .str.strip()<br>    .str.title()<br>)</pre><p>We apply similar cleaning to employment type, city and the target variable.</p><p>For the target, we make sure the classes are consistently represented as Low, Medium and High.</p><h3>Handling dates and invalid values</h3><p>The application dates use mixed formats, so we convert them carefully into actual date values.</p><p>We also inspect the age column and replace impossible values with missing values. For this exercise, only ages between 18 and 100 are considered valid.</p><h3>Handling missing values</h3><p>Different columns require different strategies.</p><p><strong>Annual income:</strong> Median income within the same employment type.</p><p><strong>Age:</strong> Overall median.</p><p><strong>Credit history years:</strong> Overall median.</p><p><strong>Education:</strong> The category &quot;Unknown&quot;.</p><p><strong>Debt-to-income ratio:</strong> Recomputed using the available financial information.</p><p>The debt-to-income ratio is calculated as follows:</p><pre>df[&quot;debt_to_income&quot;] = df[&quot;debt_to_income&quot;].fillna(<br>    (<br>        df[&quot;loan_amount&quot;] / df[&quot;loan_term_months&quot;] * 12<br>    ) / df[&quot;annual_income&quot;]<br>)</pre><p>Finally, we cap extreme values in loan_amount and annual_income using the IQR rule.</p><p>After cleaning and imputation, the dataset contains no remaining missing values.</p><p><strong>What should you remember?</strong></p><p>Data cleaning is not just about removing missing values. It is about understanding what each column represents and choosing a strategy that makes sense for the data.</p><h3>Task 2: Data Querying &amp; Manipulation with Pandas</h3><p>After cleaning the data, we move to the second part of the assessment: extracting useful information.</p><p>This task focuses on Pandas operations such as groupby(), agg(), value_counts(), crosstab(), filtering, sorting, ranking and merging.</p><h3>Distribution of applicants by risk level</h3><p>First, we calculate the number and percentage of applicants in each risk category.</p><pre>counts = df[&quot;risk_level&quot;].value_counts()</pre><pre>percentages = (<br>    df[&quot;risk_level&quot;]<br>    .value_counts(normalize=True) * 100<br>)</pre><pre>print(pd.concat(<br>    [counts, percentages],<br>    axis=1,<br>    keys=[&quot;Count&quot;, &quot;Percentage&quot;]<br>))</pre><p>The results show that Low-risk applicants represent 45% of the dataset, corresponding to 1,350 applicants.</p><p>Medium-risk applicants represent 35%, corresponding to 1,050 applicants.</p><p>High-risk applicants represent 20%, corresponding to 600 applicants.</p><p>This gives us an overview of the target distribution.</p><p>The classes are not equally represented, which is something we need to consider later when evaluating our models.</p><h3>Comparing financial characteristics</h3><p>We can also calculate the average loan amount, annual income and number of late payments for each risk category.</p><pre>df.groupby(&quot;risk_level&quot;)[<br>    [<br>        &quot;loan_amount&quot;,<br>        &quot;annual_income&quot;,<br>        &quot;num_late_payments&quot;<br>    ]<br>].mean().round(2)</pre><p>The results show that High-risk applicants have an average loan amount of approximately 81,832.</p><p>Their average annual income is approximately 44,502, and they have an average of 1.4 late payments.</p><p>For comparison, Low-risk applicants have an average loan amount of approximately 58,009 and an average annual income of approximately 53,471.</p><p>These comparisons help us understand how financial characteristics vary across risk categories.</p><h3>Identifying cities with a higher share of High-risk applicants</h3><p>Another useful question is: Which cities have the highest percentage of High-risk applicants?</p><p>We first create a binary indicator.</p><pre>df[&quot;is_high&quot;] = (<br>    df[&quot;risk_level&quot;] == &quot;High&quot;<br>).astype(int)</pre><p>Then we group applicants by city and calculate the share of High-risk cases.</p><p>We also require at least 100 applicants per city to avoid drawing conclusions from very small groups.</p><pre>city_stats = (<br>    df.groupby(&quot;city&quot;)<br>    .agg(<br>        n=(&quot;applicant_id&quot;, &quot;count&quot;),<br>        high_share=(&quot;is_high&quot;, &quot;mean&quot;)<br>    )<br>)</pre><pre>city_stats = city_stats[<br>    city_stats[&quot;n&quot;] &gt;= 100<br>]</pre><pre>print(<br>    city_stats<br>    .sort_values(&quot;high_share&quot;, ascending=False)<br>    .head(5)<br>)</pre><p>In this synthetic dataset, the five cities with the highest High-risk shares among those meeting the minimum sample-size requirement are Agadir at approximately 22.0%, Fes at approximately 21.0%, Casablanca at approximately 20.9%, Tangier at approximately 20.1% and Marrakech at approximately 18.9%.</p><p>This is a descriptive result, not evidence that location causes credit risk.</p><h3>Exploring employment type and risk level</h3><p>We can use pd.crosstab() to examine the distribution of risk levels across employment categories.</p><pre>pd.crosstab(<br>    df[&quot;employment_type&quot;],<br>    df[&quot;risk_level&quot;],<br>    normalize=&quot;index&quot;<br>) * 100</pre><p>Using normalize=&quot;index&quot; means that each employment category is expressed as a percentage of its own row.</p><p>This makes it easier to compare the proportions of Low, Medium and High-risk applicants across employment types.</p><h3>Creating useful financial features</h3><p>We can create a new feature called loan_to_income.</p><pre>df[&quot;loan_to_income&quot;] = (<br>    df[&quot;loan_amount&quot;] / df[&quot;annual_income&quot;]<br>)</pre><p>This represents the requested loan amount relative to the applicant’s annual income.</p><p>We can then investigate applicants who have a loan-to-income ratio greater than 1.5 and at least two late payments.</p><pre>risky = df[<br>    (df[&quot;loan_to_income&quot;] &gt; 1.5) &amp;<br>    (df[&quot;num_late_payments&quot;] &gt;= 2)<br>]</pre><p>In our exercise, 385 applicants match these conditions, and approximately 48.3% of them belong to the High-risk category.</p><p>This is an example of combining multiple conditions to answer a business question.</p><h3>Other querying exercises</h3><p>The assessment also includes calculating the number of applications per month, computing month-over-month percentage changes, finding the applicant with the largest loan in each city, comparing each applicant’s income with their city’s average, and ranking applicants within each city by loan amount.</p><p>These exercises help practise Pandas operations that are frequently useful in Data Science assessments.</p><h3>Task 3: Exploratory Data Analysis &amp; Visualization</h3><p>Now that the dataset is cleaned and we have extracted useful information, we move to Exploratory Data Analysis.</p><p>The objective is to understand how the features vary across the different risk categories.</p><h3>Comparing numerical features by risk level</h3><p>We calculate descriptive statistics for numerical variables, grouped by risk level.</p><pre>df.groupby(&quot;risk_level&quot;)[<br>    [<br>        &quot;age&quot;,<br>        &quot;annual_income&quot;,<br>        &quot;loan_amount&quot;,<br>        &quot;credit_history_years&quot;,<br>        &quot;num_late_payments&quot;,<br>        &quot;existing_loans&quot;,<br>        &quot;debt_to_income&quot;<br>    ]<br>].agg([&quot;mean&quot;, &quot;median&quot;])</pre><p>This helps us compare applicants with different risk labels.</p><p>Some observations from the results are that High-risk applicants have a higher average loan amount, their average annual income is lower than that of Low-risk applicants, their average credit history is shorter, and their average debt-to-income ratio is considerably higher.</p><p>These patterns are useful for understanding the dataset, but they do not establish causal relationships.</p><h3>Visualizing income by risk level</h3><p>A boxplot allows us to compare the distribution of annual income across the three risk categories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*04xHsmvheYYFPcQ-klUSwA.png" /></figure><p>It helps us identify differences in medians, variability and potential outliers.</p><h3>Risk distribution by employment type</h3><p>A bar chart can help visualize the proportions of Low, Medium and High-risk applicants within each employment category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*hF5-vrovMLs2WxvI74JjUQ.png" /></figure><p>This makes comparisons easier than reading a table alone.</p><h3>Exploring correlations</h3><p>We also explore correlations between numerical features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*8XL5olW6OGK3gKeNNiAbYw.png" /></figure><p>For the correlation heatmap, we encode the risk categories as numerical values: Low = 0, Medium = 1 and High = 2.</p><p>This allows us to include the target in the numerical correlation analysis.</p><p>However, the resulting correlation with the encoded target should be interpreted carefully. Encoding categories as numbers introduces an order, and correlation does not capture every relationship in a multiclass problem.</p><h3>Understanding the loan amount distribution</h3><p>The histogram of loan amounts shows a right-skewed distribution, with a skewness of approximately 0.92.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*9RwcABW5WvOUhBQ6KV6aBw.png" /></figure><p>This suggests that a relatively small number of applicants request larger loans.</p><p>A log transformation may be worth exploring for some algorithms, although tree-based models do not generally require normally distributed features.</p><h3>What can we learn from the EDA?</h3><p>The analysis helps us identify patterns worth investigating.</p><p>High-risk applicants tend to have higher debt-to-income ratios. Applicants with shorter credit histories tend to appear more frequently in the High-risk category. Applicants with multiple late payments may also require closer examination.</p><p>These are observations from the synthetic dataset, not universal financial rules.</p><h3>Task 4: Machine Learning : Multiclass Classification</h3><p>Now we move to the main Machine Learning task.</p><p>Our objective is to predict the risk category of an applicant using the available features.</p><h3>Selecting features and target</h3><p>Our target variable is:</p><pre>y = df[&quot;risk_level&quot;]</pre><p>The target contains three classes: Low, Medium and High.</p><p>We select the relevant columns as predictive features.</p><p>We exclude applicant_id because it is an identifier without meaningful predictive information.</p><p>We also exclude application_date from this particular modelling setup because we are not using it as a defined temporal feature.</p><p>We need to check that engineered features are calculated only from information available at the moment the prediction would be made.</p><p>This is an important question to ask in every predictive modelling task:</p><p><strong>Would I actually have access to this information when making the prediction?</strong></p><h3>Splitting the dataset</h3><p>We use an 80/20 train/test split.</p><p>Because this is a multiclass classification problem, we use stratification to preserve approximately the same class proportions in both sets.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    stratify=y,<br>    random_state=42<br>)</pre><p>The training data is used to train and compare models.</p><p>The test set is reserved for final evaluation.</p><h3>Building the preprocessing pipeline</h3><p>Our dataset contains numerical and categorical features.</p><p>We therefore need different preprocessing operations for each type.</p><p><strong>For numerical variables:</strong> Missing values are imputed using the median, and features are standardized using StandardScaler.</p><p><strong>For categorical variables:</strong> Missing values are imputed using the most frequent category, and categories are transformed using OneHotEncoder.</p><p>We combine these operations using ColumnTransformer and Pipeline.</p><p>Using a pipeline is important because preprocessing is fitted within each training fold during cross-validation. This helps prevent information from validation or test data from leaking into the training process.</p><h3>Comparing Machine Learning algorithms</h3><p>We compare four models.</p><p><strong>Dummy Classifier:</strong> A simple baseline that always predicts the majority class.</p><p><strong>Logistic Regression:</strong> A classification algorithm that estimates the probability of belonging to each class.</p><p><strong>Random Forest:</strong> An ensemble of decision trees that can capture nonlinear relationships.</p><p><strong>Gradient Boosting:</strong> An ensemble method that builds trees sequentially to improve predictions.</p><p>We evaluate the models using five-fold stratified cross-validation.</p><p>For this exercise, we focus on <strong>Macro F1-score</strong>.</p><p>Why Macro F1?</p><p>Because it calculates the F1-score separately for each class and then gives every class equal weight.</p><p>This is useful when the classes are not equally represented.</p><p>Our cross-validation results show that the Dummy Classifier achieves a Macro F1-score of 0.207.</p><p>Logistic Regression achieves 0.778, Random Forest achieves 0.731, and Gradient Boosting achieves 0.763.</p><p>Logistic Regression achieves the highest Macro F1-score in this initial comparison.</p><p>This is an interesting result: a simpler model can perform better than more complex models when the patterns in the dataset are sufficiently well represented by its assumptions.</p><h3>Hyperparameter tuning</h3><p>We also practise hyperparameter tuning using GridSearchCV.</p><p>For this part, we demonstrate the process with Random Forest.</p><p>We test different combinations of the number of trees, maximum tree depth and minimum number of samples per leaf.</p><p>The grid search uses cross-validation on the training data to identify a suitable configuration.</p><p>The best configuration found in the notebook uses 400 trees, no maximum depth restriction and a minimum of one sample per leaf.</p><p>Its best cross-validation Macro F1-score is approximately 0.735.</p><p>One important methodological note: Random Forest is tuned here as an exercise in using GridSearchCV; it did not have the highest Macro F1 among all four models in the initial comparison. In a strict model-selection workflow, we should also tune and evaluate the leading Logistic Regression model before choosing a final candidate.</p><h3>Evaluating the model</h3><p>The tuned Random Forest model is evaluated on the held-out test set.</p><p>The results are:</p><p><strong>Accuracy:</strong> 0.695.</p><p><strong>Macro F1:</strong> 0.684.</p><p><strong>ROC-AUC (One-vs-Rest):</strong> 0.868.</p><p>We also examine the classification report.</p><p><strong>Low-risk applicants</strong></p><p>Precision is 0.78. Recall is 0.81. F1-score is 0.79.</p><p><strong>Medium-risk applicants</strong></p><p>Precision is 0.57. Recall is 0.55. F1-score is 0.56.</p><p><strong>High-risk applicants</strong></p><p>Precision is 0.71. Recall is 0.68. F1-score is 0.69.</p><p>The Medium-risk category is the most difficult class for this model to predict.</p><p>This makes sense as an assessment question: intermediate categories can be harder to distinguish because they sit between the two extremes.</p><h3>Understanding the confusion matrix</h3><p>A confusion matrix helps us understand which classes are correctly identified and which are confused with one another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*1yJutLOGol3NwCGq_13z3w.png" /></figure><p>For a three-class problem, it compares the actual and predicted labels across Low, Medium and High.</p><p>It gives us more information than accuracy alone.</p><p>For example, we can investigate whether Medium-risk applicants are frequently classified as Low or High risk.</p><p>This helps us understand where the model makes mistakes.</p><h3>Understanding feature importance</h3><p>We can also inspect the Random Forest feature importances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*hG1Ic-SsJNNszIeP8iJJkw.png" /></figure><p>The eight most important features in this experiment are:</p><p><strong>Debt-to-income ratio:</strong> 0.230.</p><p><strong>Credit history years:</strong> 0.114.</p><p><strong>Loan-to-income ratio:</strong> 0.104.</p><p><strong>Loan term:</strong> 0.084.</p><p><strong>Annual income:</strong> 0.065.</p><p><strong>Loan amount:</strong> 0.064.</p><p><strong>Number of late payments:</strong> 0.049.</p><p><strong>Years employed:</strong> 0.044.</p><p>The debt-to-income ratio has the highest importance in this model.</p><p>Feature importance helps us understand which variables the model relies on most, but it does not prove that these variables cause credit risk.</p><h3>Predicting a new applicant</h3><p>Finally, we use the trained pipeline to predict the risk category of a new applicant.</p><p>For the example included in the notebook, the model returns the following probabilities.</p><p><strong>Low:</strong> 0.08.</p><p><strong>Medium:</strong> 0.36.</p><p><strong>High:</strong> 0.56.</p><p>The predicted class is <strong>High Risk</strong>.</p><p>These probabilities represent the model’s estimates based on the patterns it learned from the synthetic training data. They should not be interpreted as calibrated real-world probabilities or used to make actual lending decisions.</p><h3>What I Learned from This Assessment</h3><p>Working through this project helped me practise several important concepts.</p><p>I learned how to clean numeric values stored as text, handle missing values using different strategies, standardize categorical variables, and use Pandas to group, filter, rank and aggregate data.</p><p>I also practised the difference between binary and multiclass classification, stratified splitting, cross-validation, and the importance of Macro F1 when evaluating multiple classes.</p><p>On the modelling side, I compared simple and ensemble models, applied hyperparameter tuning with GridSearchCV, and interpreted classification reports, confusion matrices and feature importance.</p><p>One important takeaway is that model evaluation should consider each class, not just the overall accuracy.</p><h3>A Note About This Project</h3><p>The main objective of this exercise is learning and practice, not achieving the highest possible predictive performance.</p><p>The dataset is synthetic and was created for educational purposes. The results should therefore be interpreted as part of a learning exercise, not as evidence of real-world credit-risk performance.</p><p>Credit scoring is a sensitive application of Machine Learning. A real system would require representative data, careful validation, fairness and bias assessments, explainability, regulatory review and human oversight.</p><h3>Prepare Yourself: Questions to Practice</h3><p>After completing this assessment, try answering these questions without looking at the article or notebook.</p><p><strong>What is the difference between binary and multiclass classification?</strong></p><p><strong>What is the difference between macro, micro and weighted F1-score?</strong></p><p><strong>Why can accuracy be misleading when classes are imbalanced?</strong></p><p><strong>Why do we use stratified train/test splitting?</strong></p><p><strong>What is the purpose of OneHotEncoder?</strong></p><p><strong>What is the difference between standardization and normalization?</strong></p><p><strong>Why should preprocessing be included in a Pipeline?</strong></p><p><strong>What is cross-validation, and why do we use it?</strong></p><p><strong>What is the purpose of GridSearchCV?</strong></p><p><strong>What does a confusion matrix tell us?</strong></p><p><strong>What is the difference between feature importance and causation?</strong></p><p><strong>Why might Logistic Regression outperform Random Forest?</strong></p><p><strong>What is the One-vs-Rest strategy for multiclass ROC-AUC?</strong></p><p><strong>Why should a credit-risk model not make lending decisions without human oversight?</strong></p><p>Being able to explain your decisions is just as important as knowing how to implement them.</p><h3>Try the Assessment Yourself</h3><p>I created this project as a practical exercise, so I encourage you to attempt it before looking at the solution.</p><p>The GitHub repository contains the original assessment questions, a starter notebook with exercises to complete, a fully commented solution notebook, the synthetic dataset and supporting learning resources.</p><p><strong>GitHub repository:</strong> <a href="https://github.com/dijanidsaid/sharing-is-caring-ds-assessment-prep">Sharing Is Caring — Data Science Assessment Preparation</a></p><p>Navigate to the 02_credit_risk_multiclass folder to access the project.</p><p>My recommendation: start with the questions, try to complete the starter notebook within the suggested 90 minutes, and only then compare your work with the solution.</p><p><strong>Next in the series:</strong> House Price Prediction: preparing for a Regression assessment.</p><p><em>Sharing is caring.</em></p><p>I hope these resources make your preparation a little easier. If you know someone preparing for a Data Science internship, technical assessment or their first job, feel free to share this article with them.</p><p>Because knowledge becomes more valuable when we share it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fe06bce5b4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Churn Prediction with Python: A Practical Binary Classification Assessment]]></title>
            <link>https://medium.com/@khadijaagadir2018/customer-churn-prediction-with-python-a-practical-binary-classification-assessment-e09b4c5c8470?source=rss-d6601d526e20------2</link>
            <guid isPermaLink="false">https://medium.com/p/e09b4c5c8470</guid>
            <category><![CDATA[technical-assessment]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[assessment-preparation]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[KHADIJA NID SAID]]></dc:creator>
            <pubDate>Tue, 01 Dec 2026 01:40:32 GMT</pubDate>
            <atom:updated>2026-12-01T01:40:32.388Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From messy data to predictive modeling: a hands-on exercise covering data cleaning, querying, exploratory analysis, classification algorithms and business-oriented evaluation.</em></p><p><strong>Part 1 of the Sharing Is Caring series | Machine Learning Assessment Preparation</strong></p><h3>Introduction</h3><p>When I started preparing for technical assessments for Data Science and Machine Learning opportunities, I realized that knowing the theory wasn’t enough. I also needed to practice applying it to real-world problems.</p><p>I wanted to understand how to approach an assessment from beginning to end: how to inspect a dataset, clean it, extract useful information, explore patterns, select an appropriate model and evaluate its performance.</p><p>That’s why I decided to prepare four practical projects, each covering a different Machine Learning problem:</p><ul><li>Binary Classification</li><li>Multiclass Classification</li><li>Regression</li><li>Clustering</li></ul><p>This first project focuses on <strong>Binary Classification</strong>, using a Telecom Customer Churn Prediction problem.</p><p>I structured it like a technical assessment, with four main tasks:</p><ol><li>Data Cleaning &amp; Preprocessing</li><li>Data Querying &amp; Retrieval</li><li>Exploratory Data Analysis (EDA) &amp; Visualization</li><li>Machine Learning &amp; Predictive Modeling</li></ol><p>The dataset is synthetic, and I deliberately introduced missing values, duplicates, inconsistent formats and impossible values to make the exercise closer to the kind of data challenges we encounter in practice.</p><p>My goal with this article is to explain the approach, the decisions I made and the concepts worth understanding when preparing for a similar assessment.</p><p>Let’s get started!</p><h3>1: Understanding the Business Problem</h3><p>Imagine working for a telecommunications company.</p><p>The company has noticed that some customers are leaving and wants to identify those who are likely to cancel their subscriptions.</p><p>The retention team wants to contact these customers before they leave, potentially offering better plans or personalized services.</p><p>This is a <strong>Customer Churn Prediction</strong> problem.</p><p>Churn refers to customers who stop using a company’s services.</p><p>Our objective is to predict whether a customer will leave or stay.</p><h3>Why is this a Binary Classification problem?</h3><p>Because we have only two possible outcomes:</p><ul><li>1: The customer churned.</li><li>0: The customer stayed.</li></ul><p>Our target variable is therefore:</p><p>churned</p><p>This is an example of supervised learning because we have historical observations with known outcomes that the model can learn from.</p><p><strong>Business objective:</strong> Identify customers who are more likely to churn so the retention team can prioritize its actions.</p><h3>Understanding the dataset</h3><p>Our exercise uses three related tables:</p><p>Table | Description</p><p><strong>churn_customers|</strong> Customer information, including age, region, plan, monthly price and churn status.</p><p><strong>churn_transactions|</strong> Monthly billing information, data usage and call minutes.</p><p><strong>churn_tickets|</strong> Customer support tickets, their categories and resolution times.</p><p>The original customer table contains 4,045 rows, including duplicate customer records.</p><p>After removing duplicates, we have 4,000 unique customers.</p><p>The dataset contains approximately 27% churned customers, meaning the target classes are imbalanced.</p><p>This is important because a model can achieve apparently good accuracy simply by predicting the majority class.</p><p>We’ll come back to this when evaluating our models.</p><h3>2. Task 1 : Data Cleaning &amp; Preprocessing</h3><p>Before building any Machine Learning model, we need to understand and prepare our data.</p><p>In a technical assessment, this step is important because the quality of the input data directly affects the reliability of the results.</p><h3>2.1 Inspecting the datasets</h3><p>First, we load the three tables using Pandas.</p><pre>import pandas as pd<br>import numpy as np</pre><pre>cust = pd.read_csv(&quot;../data/churn_customers.csv&quot;)<br>tx = pd.read_csv(&quot;../data/churn_transactions.csv&quot;)<br>tk = pd.read_csv(&quot;../data/churn_tickets.csv&quot;)</pre><pre>print(cust.shape, tx.shape, tk.shape)</pre><pre>print(cust.isna().mean() * 100)</pre><pre>print(&quot;Duplicates:&quot;, cust.duplicated().sum())</pre><p>We inspect:</p><ul><li>The dimensions of each dataset.</li><li>The percentage of missing values.</li><li>The number of duplicated records.</li></ul><p>The customer table contains 45 duplicated rows.</p><h3>2.2 Removing duplicates</h3><p>Each customer should appear only once in the customer table.</p><pre>cust = cust.drop_duplicates(subset=&quot;customer_id&quot;)</pre><p>Why is this important?</p><p>Imagine calculating the churn rate by region while some customers appear twice.</p><p>Those customers would be counted twice, potentially distorting our statistics.</p><p><strong>Lesson:</strong> Remove duplicates before calculating customer-level statistics.</p><h3>2.3 Standardizing categorical variables</h3><p>Some values have inconsistent formats:</p><ul><li>&quot; Standard &quot;</li><li>&quot;PREMIUM&quot;</li><li>&quot;north&quot;</li><li>&quot;north&quot;</li><li>Missing regions.</li></ul><p>We standardize the text:</p><pre>cust[&quot;plan&quot;] = cust[&quot;plan&quot;].str.strip().str.title()</pre><pre>cust[&quot;region&quot;] = (<br>    cust[&quot;region&quot;]<br>    .str.strip()<br>    .str.title()<br>    .fillna(&quot;Unknown&quot;)<br>)</pre><p>This ensures that equivalent categories are represented consistently.</p><h3>2.4 Handling dates with different formats</h3><p>One interesting challenge was that the signup dates used two different formats:</p><ul><li>YYYY-MM-DD</li><li>DD/MM/YYYY</li></ul><p>My first attempt used:</p><pre>pd.to_datetime(<br>    cust[&quot;signup_date&quot;],<br>    format=&quot;mixed&quot;,<br>    dayfirst=True<br>)</pre><p>It executed without an error, but it could interpret dates in the ISO format incorrectly by swapping the day and month.</p><p>I discovered this by manually checking a few dates.</p><p>A safer approach is to parse each format separately:</p><pre>d_iso = pd.to_datetime(<br>    cust[&quot;signup_date&quot;],<br>    format=&quot;%Y-%m-%d&quot;,<br>    errors=&quot;coerce&quot;<br>)</pre><pre>d_dmy = pd.to_datetime(<br>    cust[&quot;signup_date&quot;],<br>    format=&quot;%d/%m/%Y&quot;,<br>    errors=&quot;coerce&quot;<br>)</pre><pre>cust[&quot;signup_date&quot;] = d_iso.fillna(d_dmy)</pre><p><strong>Something worth remembering:</strong> Code that runs without errors isn’t necessarily code that produces correct results. Always validate your transformations.</p><h3>2.5 Handling impossible ages</h3><p>The age column contains unrealistic values, including values outside the 18–100 range.</p><p>We replace those values with missing values and then use the median to fill them.</p><pre>cust[&quot;age&quot;] = pd.to_numeric(<br>    cust[&quot;age&quot;],<br>    errors=&quot;coerce&quot;<br>)</pre><pre>cust.loc[<br>    ~cust[&quot;age&quot;].between(18, 100),<br>    &quot;age&quot;<br>] = np.nan</pre><pre>cust[&quot;age&quot;] = cust[&quot;age&quot;].fillna(<br>    cust[&quot;age&quot;].median()<br>)</pre><p>Why the median?</p><p>Unlike the mean, the median is less affected by extreme values.</p><h3>2.6 : Filling missing prices</h3><p>Customers have different subscription plans, so using one global median could introduce unnecessary differences between plans.</p><p>Instead, we calculate the median monthly price for each plan.</p><pre>cust[&quot;monthly_price&quot;] = cust[&quot;monthly_price&quot;].fillna(<br>    cust.groupby(&quot;plan&quot;)[&quot;monthly_price&quot;]<br>    .transform(&quot;median&quot;)<br>)</pre><p>This is an example of group-based imputation.</p><h3>2.7 What about missing transaction amounts?</h3><p>The transaction table also contains missing values in amount_billed.</p><p>Pandas aggregation functions such as mean() skip missing values by default.</p><p>For example:</p><pre>tx.groupby(&quot;customer_id&quot;)[&quot;amount_billed&quot;].mean()</pre><p>We can leave those values missing when calculating averages rather than inventing billing amounts.</p><p>However, it’s important to understand that this means the average is calculated from available observations, not necessarily every billing month.</p><h3>3. Task 2 : Data Querying &amp; Retrieval with Pandas</h3><p>Cleaning the data is only part of the assessment.</p><p>We also need to extract useful information from multiple tables.</p><p>This is where Pandas grouping, aggregation, filtering, sorting and merging become particularly important.</p><h3>3.1 : Calculating churn rates by region</h3><p>We want to identify which regions have the highest churn rates.</p><pre>region_summary = (<br>    cust.groupby(&quot;region&quot;)<br>    .agg(<br>        n=(&quot;customer_id&quot;, &quot;count&quot;),<br>        churn_rate=(&quot;churned&quot;, &quot;mean&quot;)<br>    )<br>    .assign(<br>        churn_rate=lambda x: x[&quot;churn_rate&quot;] * 100<br>    )<br>    .sort_values(&quot;churn_rate&quot;, ascending=False)<br>)</pre><p>Because our target is encoded as 0 and 1, its mean represents the proportion of customers who churned.</p><p>The results show:</p><p><strong>Regional Churn Analysis</strong></p><p><strong>North </strong>| 762 customers | 30.4% churn rate</p><p><strong>East</strong> | 785 customers | 27.6% churn rate</p><p><strong>Centre</strong> | 571 customers | 27.0% churn rate</p><p><strong>South</strong> | 975 customers | 26.8% churn rate</p><p><strong>West </strong>| 787 customers | 24.7% churn rate</p><p><strong>Unknown</strong> | 120 customers | 19.2% churn rate</p><p>This helps the company identify regions that may require further investigation.</p><h3>3.2 : Other useful querying exercises</h3><p>The assessment also includes:</p><ul><li>Finding the top 10 customers by total billed amount in 2024.</li><li>Calculating average support resolution time by ticket category.</li><li>Computing monthly revenue and month-over-month percentage changes.</li><li>Finding each customer’s most frequent support ticket category.</li><li>Building one customer-level table by combining customer, transaction and ticket information.</li></ul><p>These exercises help practice operations that frequently appear in Data Science assessments.</p><h3>3.3 : Why do we need to merge the tables?</h3><p>The customer table contains customer information, but it doesn’t contain all the information we need.</p><p>We need to aggregate transactions and support tickets before joining them to the customer table.</p><p>For example:</p><pre>n_tickets = (<br>    tk.groupby(&quot;customer_id&quot;)<br>    .size()<br>    .rename(&quot;n_tickets&quot;)<br>)</pre><pre>billing = tx.groupby(&quot;customer_id&quot;).agg(<br>    avg_bill=(&quot;amount_billed&quot;, &quot;mean&quot;),<br>    avg_data=(&quot;data_gb&quot;, &quot;mean&quot;),<br>    avg_calls=(&quot;call_minutes&quot;, &quot;mean&quot;),<br>    n_months=(&quot;billing_month&quot;, &quot;nunique&quot;)<br>)</pre><pre>df = (<br>    cust.merge(n_tickets, on=&quot;customer_id&quot;, how=&quot;left&quot;)<br>        .merge(billing, on=&quot;customer_id&quot;, how=&quot;left&quot;)<br>)</pre><pre>df[&quot;n_tickets&quot;] = df[&quot;n_tickets&quot;].fillna(0)</pre><p>We use a left join to preserve all customers, including those without support tickets.</p><p>One important habit: <strong>always check the number of rows after merging.</strong></p><p>Our final customer-level table contains 4,000 rows, matching the number of unique customers.</p><h3>3.4 : SQL bonus</h3><p>The assessment also includes a small SQL exercise.</p><p>We reproduce the regional churn calculation using SQLite:</p><pre>SELECT<br>    region,<br>    COUNT(*) AS n,<br>    ROUND(AVG(churned) * 100, 1) AS churn_rate<br>FROM customers<br>GROUP BY region<br>ORDER BY churn_rate DESC;</pre><p>This is useful practice because technical assessments may test the same data manipulation concepts using either Pandas or SQL.</p><h3>4. Task 3: Exploratory Data Analysis &amp; Visualization</h3><p>Now that our data is prepared, we want to understand the relationships between customer characteristics and churn.</p><p>EDA helps us discover patterns, formulate hypotheses and communicate useful insights.</p><h3>4.1 : Churn rate by subscription plan</h3><p>One of the first things we investigate is whether churn differs between subscription plans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*9TotC9AVAPOvUuilRjeFmA.png" /></figure><p>The results show:</p><ul><li>Basic: approximately 37%.</li><li>Standard: approximately 23%.</li><li>Premium: approximately 12%.</li></ul><p>This suggests that Basic-plan customers are more likely to leave than Premium-plan customers.</p><p>However, this is an association, not proof that the subscription plan itself causes churn.</p><h3>4.2 : Churn rate by number of support tickets</h3><p>We also investigate the relationship between support activity and churn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*LMm1UQbDq34oT83C-19ueg.png" /></figure><p>We observe that churn increases with the number of support tickets.</p><p>But notice that the 5+ group contains only 40 customers.</p><p>This is why it’s important to display both the percentage and the number of observations. A high percentage based on a small group should be interpreted carefully.</p><h3>4.3 : Additional visualizations</h3><p>The assessment also includes:</p><p><strong>Boxplots:</strong></p><ul><li>Customer tenure split by churn status.</li><li>Average data usage split by churn status.</li></ul><p><strong>Correlation heatmap:</strong></p><p>We calculate correlations between numerical variables to explore possible relationships.</p><p>These visualizations help us understand the dataset before building a predictive model.</p><h3>4.4 : Business insights</h3><p>Based on the exploratory analysis, we can propose three initial observations:</p><ol><li>Basic-plan customers have a higher churn rate than Standard and Premium customers.</li><li>Customers with more support tickets show higher churn rates.</li><li>Newer customers appear more likely to churn than longer-tenured customers.</li></ol><p>These observations can help the retention team identify areas worth investigating.</p><p>Remember that EDA reveals patterns, but it doesn’t establish causation.</p><h3>5. Task 4 : Machine Learning : Binary Classification</h3><p>Now comes the main Machine Learning task.</p><p>Our objective is to build a model that predicts whether a customer will churn.</p><h3>5.1 Selecting features and target</h3><p>Our target is:</p><pre>y = df[&quot;churned&quot;]</pre><p>We select numerical and categorical features.</p><p><strong>Numerical features:</strong></p><ul><li>Age</li><li>Monthly price</li><li>Number of tickets</li><li>Customer tenure</li><li>Average bill</li><li>Average data usage</li><li>Average call minutes</li></ul><p><strong>Categorical features:</strong></p><ul><li>Region</li><li>Subscription plan</li><li>Acquisition channel</li></ul><p>We exclude:</p><ul><li>customer_id: an identifier, not a meaningful predictive feature.</li><li>signup_date: we use derived tenure instead.</li><li>n_months: the number of billed months in 2024.</li></ul><p>Why exclude n_months?</p><p>Because a customer who leaves during 2024 may stop generating billed months. This feature can therefore reveal information about the outcome.</p><p>This is an example of <strong>data leakage</strong>.</p><p>A useful question to ask when selecting features is:</p><p><em>Would I actually have access to this information at the moment I need to make the prediction?</em></p><p>An additional temporal check is important here: our transaction and ticket aggregates also come from 2024. Before using them for a real prediction, we must define a prediction date and ensure that all aggregated information was available before that date. Otherwise, features such as average billing, usage and ticket counts may introduce temporal leakage or exposure bias.</p><h3>5.2 : Splitting the data</h3><p>We use an 80/20 train/test split.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(<br>    X,<br>    y,<br>    test_size=0.2,<br>    stratify=y,<br>    random_state=42<br>)</pre><p>Why stratify=y?</p><p>Because our classes are imbalanced.</p><p>Stratification helps preserve approximately the same proportion of churned and non-churned customers in both datasets.</p><p>The training set is used to learn the model, while the test set is reserved for final evaluation.</p><h3>5.3 : Building the preprocessing pipeline</h3><p>Our dataset contains both numerical and categorical features.</p><p>They require different preprocessing operations.</p><p>For numerical features:</p><ul><li>Missing values are replaced using the median.</li><li>Features are standardized using StandardScaler.</li></ul><p>For categorical features:</p><ul><li>Missing values are replaced using the most frequent category.</li><li>OneHotEncoder converts categories into numerical columns.</li></ul><p>We use ColumnTransformer and Pipeline:</p><pre>from sklearn.compose import ColumnTransformer<br>from sklearn.pipeline import Pipeline<br>from sklearn.impute import SimpleImputer<br>from sklearn.preprocessing import StandardScaler, OneHotEncoder</pre><pre>prep = ColumnTransformer([<br>    (<br>        &quot;num&quot;,<br>        Pipeline([<br>            (&quot;imp&quot;, SimpleImputer(strategy=&quot;median&quot;)),<br>            (&quot;sc&quot;, StandardScaler())<br>        ]),<br>        num_cols<br>    ),<br>    (<br>        &quot;cat&quot;,<br>        Pipeline([<br>            (&quot;imp&quot;, SimpleImputer(strategy=&quot;most_frequent&quot;)),<br>            (&quot;oh&quot;, OneHotEncoder(handle_unknown=&quot;ignore&quot;))<br>        ]),<br>        cat_cols<br>    )<br>])</pre><p>Why use a pipeline?</p><p>Because preprocessing is learned from the training data within each cross-validation fold.</p><p>This prevents information from validation or test data from influencing the transformations.</p><h3>5.4 : Choosing Machine Learning algorithms</h3><p>Since this is a binary classification problem, we compare three classifiers.</p><p><strong>1. Dummy Classifier</strong></p><p>This is our baseline.</p><p>It always predicts the majority class, meaning that it predicts customers will stay.</p><p>Why do we need it?</p><p>Because we want to know whether our actual models perform better than a simple prediction strategy.</p><p><strong>2. Logistic Regression</strong></p><p>A commonly used classification algorithm that estimates the probability of belonging to a particular class.</p><p>It is a useful starting point because it is relatively interpretable and provides probabilities.</p><p><strong>3. Random Forest</strong></p><p>An ensemble learning algorithm that combines multiple decision trees.</p><p>It can capture more complex relationships and interactions between features.</p><h3>5.5 : Evaluating models using cross-validation</h3><p>We use StratifiedKFold with five folds.</p><p>Each model is evaluated using:</p><ul><li>F1-score</li><li>ROC-AUC</li></ul><p>Our results:</p><p>Dummy (baseline) F1 = 0.000 | ROC-AUC = 0.500</p><p>Logistic Regression F1 = 0.475 | ROC-AUC = 0.683</p><p>Random Forest F1 = 0.442 | ROC-AUC = 0.663</p><p>Best model : Logistic Regression</p><p>Logistic Regression achieves the highest F1-score and ROC-AUC among the three models.</p><p>We therefore select Logistic Regression as our best-performing model in this experiment.</p><p>Notice that we don’t simply choose the most complex algorithm. The goal is to compare models and select the one that performs best according to our evaluation criteria.</p><p><strong>A Note About This Project</strong></p><p>The goal of this exercise is learning, not chasing a high score. The dataset is synthetic and was created specifically for educational practice.</p><p>The results are intended to help you understand the machine learning workflow, compare different approaches, select appropriate evaluation metrics, and interpret model performance. They should not be considered real-world performance benchmarks or evidence of production-ready models.</p><h3>6. Understanding Classification Evaluation Metrics</h3><p>This is one of the most important parts of preparing for classification assessments.</p><p>Different metrics answer different questions.</p><h3>6.1 : Confusion Matrix</h3><p>A confusion matrix compares actual labels with predicted labels.</p><p>It contains four possible outcomes:</p><p><strong>1. Actual churn — Predicted churn: True Positive (TP)</strong></p><p>The customer actually left, and the model correctly predicted churn.</p><p><strong>2. Actual churn — Predicted stay: False Negative (FN)</strong></p><p>The customer left, but the model incorrectly predicted that they would stay.</p><p><strong>3. Actual stay — Predicted churn: False Positive (FP)</strong></p><p>The customer stayed, but the model incorrectly predicted that they would leave.</p><p><strong>4. Actual stay — Predicted stay: True Negative (TN)</strong></p><p>The customer stayed, and the model correctly predicted that they would stay.</p><p>For our test set, at the default threshold of 0.5:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*4BB_-mwwuwvh1Newr4BqAA.png" /></figure><p>This means:</p><ul><li>354 customers who stayed were correctly identified.</li><li>230 customers who stayed were incorrectly flagged as churners.</li><li>80 actual churners were missed.</li><li>136 actual churners were correctly identified.</li></ul><h3>6.2 : Accuracy</h3><p>Accuracy measures the proportion of correct predictions.</p><p>It is not always a reliable metric when the classes are imbalanced.</p><p>Our dataset contains approximately 73% non-churners.</p><p>A model that always predicts “stay” would achieve approximately 73% accuracy while detecting no churners at all.</p><p>That’s why we need additional metrics.</p><h3>6.3 : Precision</h3><p>Precision answers:</p><p><em>Among all the customers predicted to churn, how many actually churned?</em></p><p>It matters when contacting customers has a cost.</p><h3>6.4 : Recall</h3><p>Recall answers:</p><p><em>Among all the customers who actually churned, how many did our model identify?</em></p><p>It matters when the company wants to avoid missing potential churners.</p><h3>6.5 : F1-score</h3><p>F1-score combines precision and recall using their harmonic mean.</p><p>It is useful when we want to balance the two.</p><h3>6.6 : ROC-AUC</h3><p>ROC-AUC measures how well a model ranks positive cases above negative cases across different classification thresholds.</p><p>A score of 0.5 corresponds to random ranking, while higher values indicate better discrimination.</p><h3>6.7 : PR-AUC</h3><p>Precision-Recall AUC summarizes the precision-recall relationship across thresholds.</p><p>It is particularly useful when the positive class is relatively rare.</p><p><strong>A useful interview tip:</strong> Don’t memorize metric definitions without understanding the business situation in which each metric matters.</p><p>For example, in churn prediction, a company may prefer higher recall because missing a customer who is about to leave could mean losing an opportunity to retain them.</p><h3>7. Choosing a Business-Oriented Decision Threshold</h3><p>One of the most interesting parts of this project is threshold selection.</p><p>A classification model can output probabilities rather than immediately assigning a class.</p><p>For example:</p><p>Customer Predicted churn probability</p><p><strong>Customer A:</strong> 0.82</p><p><strong>Customer B:</strong> 0.61</p><p><strong>Customer C:</strong> 0.38</p><p><strong>Customer D:</strong> 0.21</p><p>By default, we classify a customer as a churner when the predicted probability is at least 0.5.</p><p>But why should we always use 0.5?</p><p>Imagine the retention team tells us:</p><p><em>“We want to identify at least 70% of the customers who will leave.”</em></p><p>This introduces a business requirement.</p><p>We need to choose a threshold that prioritizes recall while maintaining as much precision as possible.</p><h3>How did I choose the threshold?</h3><p>Instead of using the test set to select it, I used cross-validated predictions on the training set.</p><pre>oof = cross_val_predict(<br>    best,<br>    X_train,<br>    y_train,<br>    cv=cv,<br>    method=&quot;predict_proba&quot;<br>)[:, 1]</pre><pre>prec, rec, thr = precision_recall_curve(<br>    y_train,<br>    oof<br>)</pre><pre>ok = np.where(rec[:-1] &gt;= 0.70)[0]</pre><pre>threshold = thr[ok[-1]]</pre><p>These are out-of-fold predictions: each training observation receives a prediction from a model that did not train on that observation.</p><p>We select the highest threshold that still achieves at least 70% recall on these training predictions.</p><p><strong>Selected threshold was : 0.474</strong></p><p>When applied to the untouched test set, we obtained the following results:</p><p><strong>Using the default threshold (0.5)</strong></p><p>Precision: 0.372</p><p>Recall: 0.630</p><p>F1-score: 0.467</p><p><strong>Using the selected threshold (0.474)</strong></p><p>Precision: 0.370</p><p>Recall: 0.681</p><p>F1-score: 0.480</p><p>Recall increased from 63.0% to 68.1%. Although the model did not reach the 70% target on the test set, it identified more customers who actually churned.</p><p>The threshold also changes the balance between false positives and false negatives.</p><p>This is why threshold selection should reflect the business objective rather than automatically using 0.5.</p><h3>8. Understanding Feature Importance</h3><p>After training the Logistic Regression model, we inspect its coefficients to understand which features are associated with the predictions.</p><p>Some of the largest coefficients by absolute value were:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*q3SEEv4m50o8sqmkV-4o0w.png" /></figure><p>For Logistic Regression:</p><ul><li>Positive coefficients increase the predicted log-odds of churn.</li><li>Negative coefficients decrease the predicted log-odds of churn.</li></ul><p>For example, the negative coefficient associated with the Premium plan indicates a lower predicted tendency to churn relative to the reference category, holding the other features constant.</p><p>These coefficients describe associations learned by the model, not causal effects.</p><p>Also, numerical features were standardized, and categorical features were one-hot encoded. Coefficient magnitude should therefore be interpreted with care, particularly when features are correlated.</p><h3>9. Business Recommendations and Model Limitations</h3><p>A Machine Learning assessment shouldn’t stop at model evaluation.</p><p>We should also explain what the results mean for the business.</p><h3>9.1 : Possible recommendations</h3><p>Based on our exploratory analysis and model predictions:</p><ol><li>Investigate retention strategies for Basic-plan customers, especially those with several support tickets.</li><li>Prioritize customers with higher predicted churn probabilities for retention outreach, while considering the team’s available resources.</li></ol><h3>9.2 : Model limitations</h3><p>There are several limitations to acknowledge.</p><p><strong>1. Synthetic data</strong></p><p>The dataset is artificial and doesn’t necessarily represent the complexity of real telecom customer behavior.</p><p><strong>2. Predictive performance</strong></p><p>The ROC-AUC of 0.677 indicates moderate discrimination. The model is better than random ranking, but its predictions are far from perfect.</p><p><strong>3. Correlation is not causation</strong></p><p>The model identifies patterns associated with churn. It doesn’t establish why customers leave.</p><p><strong>4. Temporal validation</strong></p><p>Before using the model operationally, we would need a clearly defined prediction date, historical features available before that date, and validation on a later time period.</p><p>This would help detect temporal leakage and measure how well the model generalizes to future customers.</p><h3>10. What I Learned from This Assessment</h3><p>Working through this project helped me practice more than just binary classification.</p><p>Some of the most important lessons were:</p><ol><li>Always inspect your data before starting any analysis.</li><li>Remove duplicates before calculating customer-level statistics.</li><li>Validate date transformations instead of assuming they are correct.</li><li>Check row counts after merging tables.</li><li>Understand the difference between numerical and categorical preprocessing.</li><li>Build a baseline before comparing more complex models.</li><li>Understand why accuracy alone is insufficient for imbalanced classification.</li><li>Select evaluation metrics according to the problem and business objective.</li><li>Check for data leakage before training.</li><li>Remember that the best threshold depends on the business requirement.</li></ol><h3>11. Prepare Yourself: Questions to Practice</h3><p>After completing this assessment, you should be comfortable answering questions such as:</p><ol><li>What is the difference between binary and multiclass classification?</li><li>Why is Logistic Regression used for classification despite its name?</li><li>What is the difference between precision and recall?</li><li>Why can accuracy be misleading with imbalanced classes?</li><li>What is the purpose of stratified sampling?</li><li>What is data leakage, and how can you prevent it?</li><li>Why do we use a preprocessing pipeline?</li><li>What is the difference between ROC-AUC and PR-AUC?</li><li>Why might we change the default classification threshold?</li><li>When would you prefer Random Forest over Logistic Regression?</li></ol><p>Try answering these questions without looking at the article or notebook. Being able to explain your decisions is just as important as knowing how to implement them.</p><h3>12. Try the Assessment Yourself</h3><p>I created this project as a practical exercise, so I encourage you to attempt it before looking at the solution.</p><p>The GitHub repository contain:</p><ul><li>The original assessment questions.</li><li>A starter notebook with exercises to complete.</li><li>A fully commented solution notebook.</li><li>The synthetic datasets.</li><li>Supporting visualizations and learning resources.</li></ul><p><strong>GitHub repository:</strong> <a href="https://github.com/dijanidsaid/sharing-is-caring-ds-assessment-prep/tree/main">Sharing Is Caring — Data Science Assessment Preparation</a></p><p>Navigate to the 01_churn_binary folder to access the project.</p><p>My recommendation: start with the questions, complete the starter notebook within the suggested 90 minutes, and only then compare your work with the solution.</p><p><em>Next in the series: Credit Risk Classification : preparing for a Multiclass Classification assessment.</em></p><p><strong>Sharing Is Caring.</strong></p><p>I hope these resources make your preparation a little easier. If you know someone preparing for a Data Science internship, technical assessment or their first job, feel free to share this article with them.</p><p>Because knowledge becomes more valuable when we share it.</p><h3>About the initiative</h3><p>Sharing Is Caring is a small learning initiative built around a simple idea: sharing what we learn can make someone else’s starting point easier.</p><p>Created by Khadija Nid Said.</p><ul><li>GitHub: <a href="https://github.com/dijanidsaid">@dijanidsaid</a></li><li>LinkedIn: <a href="https://www.linkedin.com/in/khadija-nid-said-88a640240/">Khadija Nid Said</a></li></ul><p>If you find the material useful, consider starring the repository or sharing it with someone preparing for an internship, PFE, or technical assessment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e09b4c5c8470" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From Tweets to Feelings: How I Built a Sentiment Analysis Model with PySpark ✨]]></title>
            <link>https://medium.com/@khadijaagadir2018/from-tweets-to-feelings-how-i-built-a-sentiment-analysis-model-with-pyspark-dafa1089f487?source=rss-d6601d526e20------2</link>
            <guid isPermaLink="false">https://medium.com/p/dafa1089f487</guid>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[tweet]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[KHADIJA NID SAID]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 22:54:23 GMT</pubDate>
            <atom:updated>2025-11-03T22:57:30.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how computers can tell whether a tweet is positive or negative? Well, in this project, I built a sentiment analysis model using PySpark and a portion of the famous Sentiment140 dataset. In this post, I’ll walk you through how I taught Spark to read emotions from tweets from cleaning text and transforming words into numbers, to training a logistic regression model that predicts positivity or negativity. Fun, simple, and powered by Spark! ⚡</p><h3>💡 Why I built this project</h3><p>I’ve always been fascinated by how machines interpret human language especially emotions hidden inside text. So, I decided to try building a model that could detect the sentiment of tweets, from happy to grumpy, using <strong>PySpark </strong>it’s<strong> </strong>a powerful engine for big data processing.</p><p>I used a portion of the <strong>Sentiment140 dataset</strong>, which originaly contains 1.6 million tweets labeled as positive or negative. It’s one of the most popular datasets for learning and experimenting with sentiment analysis.</p><h3>🚀 Step 1: Setting up the Spark magic</h3><p>Everything starts with a Spark session — basically Spark’s way of saying <em>“Hey, I’m ready to crunch data!”</em></p><pre>from pyspark.sql import SparkSession<br>spark = SparkSession.builder \<br>    .appName(&quot;Sentiment Analysis in Spark&quot;) \<br>    .config(&quot;spark.some.config.option&quot;, &quot;some-value&quot;) \<br>    .getOrCreate()</pre><p>Spark can scale across machines, but even on a laptop, it’s super fast for large text data.</p><h3>🧾 Step 2: Reading the tweets</h3><p>Next, I loaded the dataset a CSV file containing tweets and their sentiment labels.</p><pre>tweets_csv = spark.read.csv(&#39;tweets.csv&#39;, inferSchema=True, header=True)<br>tweets_csv.show(truncate=False, n=3)</pre><p>The Sentiment140 dataset includes two main columns: <strong>SentimentText</strong> (the tweet itself) and <strong>Sentiment</strong> (0 for negative, 1 for positive). A quick .show() helps visualize a few examples.</p><h3>✂️ Step 3: Keeping only what matters</h3><p>The dataset had lots of metadata, but we only needed the text and sentiment.</p><pre>from pyspark.sql.functions import col<br>data = tweets_csv.select(&quot;SentimentText&quot;, col(&quot;Sentiment&quot;).cast(&quot;Int&quot;).alias(&quot;label&quot;))</pre><p>We rename the sentiment column to label that’s the standard format Spark ML expects.</p><h3>🔀 Step 4: Train-test split — giving the model a fair test</h3><p>To check how well our model learns, we split the data into training (70%) and testing (30%).</p><pre>dividedData = data.randomSplit([0.7, 0.3])<br>trainingData = dividedData[0]<br>testingData = dividedData[1]</pre><p>This ensures we can evaluate the model on unseen tweets.</p><h3>🧠 Step 5: Teaching Spark to understand text</h3><p>Computers can’t understand words directly, so we need to turn tweets into numerical features.</p><p>We use three main tools:</p><ol><li><strong>Tokenizer</strong> → splits sentences into words.</li><li><strong>StopWordsRemover</strong> → removes common words like “the”, “is”, and “at”.</li><li><strong>HashingTF</strong> → turns each tweet into a numeric vector based on word frequency.</li></ol><pre>from pyspark.ml.feature import Tokenizer, StopWordsRemover, HashingTF<br>tokenizer = Tokenizer(inputCol=&quot;SentimentText&quot;, outputCol=&quot;words&quot;)<br>remover = StopWordsRemover(inputCol=&quot;words&quot;, outputCol=&quot;filtered&quot;)<br>hashingTF = HashingTF(inputCol=&quot;filtered&quot;, outputCol=&quot;features&quot;)</pre><h3>⚙️ Step 6: Building and training the model</h3><p>Now it’s time to train the classifier! I chose <strong>Logistic Regression</strong>, a classic model for binary sentiment classification.</p><pre>from pyspark.ml.classification import LogisticRegression<br>from pyspark.ml import Pipeline<br>lr = LogisticRegression(maxIter=10, regParam=0.01)<br>pipeline = Pipeline(stages=[tokenizer, remover, hashingTF, lr])<br>model = pipeline.fit(trainingData)</pre><p>This single pipeline handles text cleaning, feature extraction, and model training in one go very Spark-style.</p><h3>📊 Step 7: Testing &amp; evaluation</h3><p>Now we test it on unseen data:</p><pre>predictions = model.transform(testingData)<br>predictions.select(&quot;SentimentText&quot;, &quot;label&quot;, &quot;prediction&quot;).show(5)</pre><p>We can also compute accuracy or F1-score to evaluate how well the model generalizes. Even a basic setup like this often achieves surprisingly strong results.</p><h3>💡 Step 8: What I learned</h3><p>✨ Data cleaning and preprocessing take most of the time.<br> ✨ PySpark Pipelines simplify the whole ML workflow beautifully.<br> ✨ Logistic Regression remains a great, interpretable model for text classification.</p><h3>✨ Final thoughts</h3><p>This project was a fun mix of big data and emotion detection <br> If you’ve ever wanted to play with large datasets or natural language processing, PySpark is a fantastic place to start.</p><p>If you enjoyed this post, leave a clap 👏 or share it with a data-loving friend. More fun AI adventures coming soon!</p><p>🔗 <strong>Full code + dataset on GitHub</strong>: <a href="https://github.com/dijanidsaid/SentimentSpark-Real-Time-Sentiment-Analysis">GitHub Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dafa1089f487" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Detective: Building a Vision Transformer for Gender and Emotion Detection]]></title>
            <link>https://medium.com/@khadijaagadir2018/face-detective-building-a-vision-transformer-for-gender-and-emotion-detection-36d68df7d601?source=rss-d6601d526e20------2</link>
            <guid isPermaLink="false">https://medium.com/p/36d68df7d601</guid>
            <dc:creator><![CDATA[KHADIJA NID SAID]]></dc:creator>
            <pubDate>Wed, 29 Oct 2025 17:00:20 GMT</pubDate>
            <atom:updated>2025-11-03T22:59:08.457Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve always been a <strong>Convolutional Neural Network (CNN)</strong> fan for image tasks, those layers are like magic for spotting patterns in pixels. But recently, I’ve become a huge fan of <strong>Transformers</strong>, the superstars of NLP, and I wanted to see if they could shine on images too. Enter the <strong>Vision Transformer (ViT)</strong>, a game-changer that treats images like sentences, breaking them into patches and using attention to focus on what matters. Curious how it stacks up against CNNs, I built a ViT to detect <strong>gender (male/female)</strong> and <strong>emotions (anger, happy, etc.)</strong> using Kaggle datasets, hitting <strong>98% accuracy for gender</strong> and <strong>85% for emotions</strong>. Here’s the step-by-step journey, with code, explanations.</p><h3>1. The Arsenal: Loading the Tools</h3><p>Just like gearing up for a face-reading adventure, we start with the essentials.</p><pre>import os<br>import numpy as np<br>import cv2<br>from tensorflow.keras.utils import to_categorical  # For one-hot encoding labels<br>import tensorflow as tf<br>from tensorflow.keras import layers, Model<br>from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay</pre><ul><li><strong>os, numpy, cv2</strong>: For file handling, arrays, and image processing (grayscale, resizing).</li><li><strong>TensorFlow/Keras</strong>: Builds the ViT model with custom layers like Patches and PatchEncoder.</li><li><strong>Matplotlib, sklearn</strong>: Plots results, splits data, and shows confusion matrices.</li><li><strong>Callbacks</strong>: EarlyStopping stops training if no improvement; ReduceLROnPlateau adjusts learning rate dynamically.</li></ul><p>Why this matters: These libraries handle everything from loading images to training complex transformers, keeping our code efficient and focused.</p><h3>2. The Data: Faces Galore from Kaggle</h3><p>For <strong>gender detection</strong>, we use the “Male and Female Faces” dataset from Kaggle, plit into male and female folders.</p><pre>men_dir = &quot;content/male_faces&quot;<br>women_dir = &quot;content/female_faces&quot;<br>print(f&quot;Nombre d&#39;images hommes: {len(os.listdir(men_dir))}&quot;)<br>print(f&quot;Nombre d&#39;images femmes: {len(os.listdir(women_dir))}&quot;)</pre><ul><li><strong>Total faces</strong>: Around 5,400 (2,721 male, 2,699 female), but we limited to 2,000 per class for balance .</li><li><strong>Labels</strong>: 1 for male, 0 for female.</li></ul><p>For <strong>emotion detection</strong>, we switch to the CK+ dataset with folders for 7 emotions: anger, contempt, disgust, fear, happy, sadness, surprise.</p><p>Why this matters: Real-world datasets like these teach the model diverse faces. CK+ is great for emotions as it includes sequences, but we focus on static images.</p><h3>3. Preprocessing: Turning Faces into Model-Ready Data</h3><p>Faces come in all shapes so we standardize them.</p><pre>image_size = 48  # Resize all to 48x48 pixels<br>def load_and_preprocess_images(men_dir, women_dir, max_images=None):<br>    X = []  # Images<br>    y = []  # Labels<br>    <br>    # Load male images<br>    male_files = [f for f in os.listdir(men_dir) if f.endswith((&#39;.jpg&#39;, &#39;.jpeg&#39;, &#39;.png&#39;))]<br>    if max_images:<br>        male_files = male_files[:max_images]<br>    for file in male_files:<br>        img_path = os.path.join(men_dir, file)<br>        img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)  # Grayscale<br>        if img is None:<br>            continue<br>        img = cv2.resize(img, (image_size, image_size))  # Resize<br>        X.append(img)<br>        y.append(1)  # Male<br>    <br>    # Load female images (similarly)<br>    # ...<br>    <br>    X = np.array(X).reshape(-1, image_size, image_size, 1) / 255.0  # Normalize [0,1], add channel dim<br>    y = to_categorical(np.array(y), num_classes=2)  # One-hot: [1,0] for male, [0,1] for female<br>    <br>    return X, y<br>X, y = load_and_preprocess_images(men_dir, women_dir, max_images=2000)<br>print(f&quot;Dataset loaded: {X.shape}, Labels: {y.shape}&quot;)</pre><ul><li><strong>Grayscale</strong>: Simplifies input (1 channel instead of 3 RGB), focuses on shapes over colors.</li><li><strong>Resize to 48x48</strong>: Matches ViT’s patch size (6x6 patches from 48x48 image = 64 patches).</li><li><strong>Normalize /255.0</strong>: Scales pixel values to [0,1] for stable training.</li><li><strong>One-hot encoding</strong>: Turns labels into vectors for binary/multi-class classification.</li></ul><p>For emotions, we use a similar function but with 7 classes and the CK+ folders.</p><p>Why this matters: Clean data prevents model confusion. Limiting images speeds up prototyping without losing key patterns.</p><p>We split into train/test:</p><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y)</pre><ul><li><strong>stratify=y</strong>: Keeps class balance in splits.</li></ul><h3>4. Building the ViT Model: The Transformer Magic</h3><p>ViT treats images like text : splitting into patches, embedding them, and using transformers for attention.</p><pre>class Patches(layers.Layer):<br>    def __init__(self, patch_size):<br>        super().__init__()<br>        self.patch_size = patch_size<br>    <br>    def call(self, images):<br>        patches = tf.image.extract_patches(<br>            images=images,<br>            sizes=[1, self.patch_size, self.patch_size, 1],<br>            strides=[1, self.patch_size, self.patch_size, 1],<br>            rates=[1, 1, 1, 1],<br>            padding=&quot;VALID&quot;,<br>        )<br>        return tf.reshape(patches, [tf.shape(images)[0], -1, patches.shape[-1]])<br>    class PatchEncoder(layers.Layer):<br>        def __init__(self, num_patches, projection_dim):<br>            super().__init__()<br>            self.num_patches = num_patches<br>            self.projection = layers.Dense(units=projection_dim)<br>            self.position_embedding = layers.Embedding(input_dim=num_patches, output_dim=projection_dim)<br>        <br>        def call(self, patch):<br>            positions = tf.range(start=0, limit=self.num_patches, delta=1)<br>            encoded = self.projection(patch) + self.position_embedding(positions)<br>            return encoded</pre><p>Full model:</p><pre>def create_vit_classifier(input_shape, patch_size, num_patches, projection_dim, num_heads, transformer_layers, mlp_head_units, num_classes):<br>    inputs = layers.Input(shape=input_shape)<br>    patches = Patches(patch_size)(inputs)<br>    encoded_patches = PatchEncoder(num_patches, projection_dim)(patches)<br>    <br>    for _ in range(transformer_layers):<br>        x1 = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)<br>        attention_output = layers.MultiHeadAttention(num_heads=num_heads, key_dim=projection_dim, dropout=0.1)(x1, x1)<br>        x2 = layers.Add()([attention_output, encoded_patches])<br>        x3 = layers.LayerNormalization(epsilon=1e-6)(x2)<br>        x3 = mlp(x3, hidden_units=mlp_head_units, dropout_rate=0.1)<br>        encoded_patches = layers.Add()([x3, x2])<br>    <br>    representation = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)<br>    representation = layers.Flatten()(representation)<br>    representation = layers.Dropout(0.5)(representation)<br>    features = mlp(representation, hidden_units=mlp_head_units, dropout_rate=0.5)<br>    logits = layers.Dense(num_classes)(features)<br>    <br>    model = Model(inputs=inputs, outputs=logits)<br>    return model<br>    # For gender: 2 classes<br>    model_gender = create_vit_classifier((48,48,1), 6, 64, 64, 8, 2, [128,64], 2)<br>    model_gender.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><ul><li><strong>Patches</strong>: Splits image into 6x6 chunks (64 patches from 48x48).</li><li><strong>PatchEncoder</strong>: Projects patches to embeddings + adds position info.</li><li><strong>Transformer Layers</strong>: Multi-head attention learns relationships between patches; MLP adds non-linearity.</li><li><strong>MLP Head</strong>: Flattens and classifies (softmax for probabilities).</li></ul><p>For emotions: Same but with 7 classes and categorical_crossentropy loss.</p><p>Why this matters: ViT’s attention captures global face features (like eyes for emotions) better than CNNs alone.</p><h3>5. Training: Teaching the Model to Read Faces</h3><pre>early_stopping = EarlyStopping(monitor=&#39;val_loss&#39;, patience=5, restore_best_weights=True)<br>reduce_lr = ReduceLROnPlateau(monitor=&#39;val_loss&#39;, factor=0.2, patience=3, min_lr=1e-6)<br>history = model_gender.fit(X_train, y_train, epochs=50, batch_size=32, validation_data=(X_test, y_test), callbacks=[early_stopping, reduce_lr])</pre><ul><li><strong>Epochs=50, batch=32</strong>: Trains in chunks, stops early if no improvement.</li><li><strong>Callbacks</strong>: Prevent overfitting by adjusting LR or stopping.</li></ul><p>For emotions: Similar, but monitor categorical accuracy.</p><p>Why this matters: Training balances learning and generalization — callbacks save time and improve results.</p><h3>6. Evaluation: How Good Is It?</h3><p><strong>Gender Results</strong>: ~98% accuracy.</p><p><strong>Emotion Results</strong>: ~85% on CK+ (challenging due to fewer samples).</p><h3>7. Live Test: Detect Gender or Emotion on a New Face</h3><pre>def detect_and_align_face(image_path):<br>    # Use OpenCV Haar Cascade for face detection and alignment<br>    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + &#39;haarcascade_frontalface_default.xml&#39;)<br>    img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)<br>    faces = face_cascade.detectMultiScale(img, scaleFactor=1.1, minNeighbors=5)<br>    if len(faces) &gt; 0:<br>        (x, y, w, h) = faces[0]<br>        face = img[y:y+h, x:x+w]<br>        # Align if needed (e.g., using landmarks)<br>        return cv2.resize(face, (48,48))<br>    return None<br>def test_image(model, image_path, is_gender=True):<br>    face = detect_and_align_face(image_path)<br>    if face is None:<br>        return &quot;No face detected&quot;<br>    face = face.reshape(1, 48, 48, 1) / 255.0<br>    pred = model.predict(face)<br>    if is_gender:<br>        return &quot;Male&quot; if np.argmax(pred) == 1 else &quot;Female&quot;<br>    else:<br>        emotions = [&quot;anger&quot;, &quot;contempt&quot;, &quot;disgust&quot;, &quot;fear&quot;, &quot;happy&quot;, &quot;sadness&quot;, &quot;surprise&quot;]<br>        return emotions[np.argmax(pred)]<br>print(test_image(model_gender, &quot;test_face.jpg&quot;))  # Male/Female<br>print(test_image(model_emotion, &quot;happy_face.png&quot;, is_gender=False))  # happy</pre><p>Why this matters: Real-time testing shows practical use, like in apps for sentiment analysis.</p><h3>8. Save the Hero Model</h3><pre>model_gender.save(&quot;vit_gender_model.h5&quot;)<br>model_emotion.save(&quot;vit_emotion_model.h5&quot;)</pre><p>Why this matters: Saved models can be loaded for apps, APIs, or further fine-tuning.</p><p>🔗 <strong>Full code on GitHub</strong>: <a href="https://github.com/dijanidsaid/Identity-and-Emotion-Detection-with-Vision-Transformer-ViT-">GitHub Link</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36d68df7d601" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spam Slayer: A Machine Learning Battle Against Junk Mail]]></title>
            <link>https://medium.com/@khadijaagadir2018/spam-slayer-a-machine-learning-battle-against-junk-mail-f0885f99fb10?source=rss-d6601d526e20------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0885f99fb10</guid>
            <dc:creator><![CDATA[KHADIJA NID SAID]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 15:12:30 GMT</pubDate>
            <atom:updated>2025-10-25T16:11:21.224Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Congratulations! You’ve won $1,000,000!”</em> Yeah, right. We’ve all seen it. The inbox is a battlefield, and spam emails are the enemy. So I said: ENOUGH.</p><p>I grabbed my Python sword, two spam-filled datasets, and went full Spam Slayer Mode. Let’s break down how I trained <strong>five ML models</strong> to detect spam in a way that’s fun, simple, and <em>actually</em> makes sense.</p><p>using <strong>scikit-learn</strong>, <strong>CountVectorizer</strong>, and turned 11,300 messy emails into a 99.1% accurate spam-killing machine.</p><p>There are some general code steps below, but you’ll find the <strong>full code and datasets</strong> on my 🔗 <a href="https://github.com/dijanidsaid/SpamDetector-ML">GitHub</a></p><h3>1. The Arsenal: Importing the Tools</h3><p>Every good project needs the right tools. Think of this as packing your toolbox for a spam-fighting mission.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import warnings<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><ul><li><strong>NumPy</strong>: Handles numerical operations, like arrays for calculations.</li><li><strong>Pandas</strong>: Organizes data into tables (DataFrames) for easy manipulation.</li><li><strong>Matplotlib</strong>: Creates charts to visualize our model performance.</li><li><strong>Warnings</strong>: Silences annoying, non-critical messages to keep our output clean.</li></ul><p>Next, we bring in the ML superheroes:</p><pre>from sklearn.naive_bayes import MultinomialNB<br>from sklearn.svm import SVC<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.ensemble import RandomForestClassifier</pre><p>And the support crew for preprocessing and evaluation:</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.feature_extraction.text import CountVectorizer<br>from sklearn.pipeline import Pipeline<br>from sklearn.metrics import accuracy_score, classification_report<br>import pickle</pre><ul><li><strong>train_test_split</strong>: Splits data into training and testing sets.</li><li><strong>CountVectorizer</strong>: Turns text into numbers (more on this later).</li><li><strong>Pipeline</strong>: Combines preprocessing and modeling into one step.</li><li><strong>accuracy_score, classification_report</strong>: Measures how well our models perform.</li><li><strong>pickle</strong>: Saves our trained model for later use.</li></ul><h3>2. The Data: 11,300 Emails, 2 Armies</h3><p>We used two datasets to build our spam-fighting army:</p><ul><li><strong>Dataset 1</strong>: A collection of SMS messages (adapted to mimic emails) from a Kaggle dataset.</li><li><strong>Dataset 2</strong>: Real-world emails from sources like Enron and SpamAssassin, labeled as spam or ham (legit).</li></ul><p>Here’s how we load and clean them:</p><pre>df1 = pd.read_csv(&quot;mail_spam_dataset_1.csv&quot;, names=[&#39;v1&#39;,&#39;v2&#39;,2,3,4], header=0)<br>df2 = pd.read_csv(&quot;mail_spam_dataset_2.csv&quot;, names=[&#39;mail&#39;,&#39;spam&#39;], header=0)<br><br># Clean up Dataset 1 (it’s messy!)<br>df1.drop(columns=[2,3,4], inplace=True)  # Remove unnamed, useless columns<br>df1 = df1[[&#39;v2&#39;,&#39;v1&#39;]].copy()  # Reorder columns: text first, label second<br>df1.columns = [&#39;mail&#39;,&#39;spam&#39;]   # Rename for consistency<br>df1[&#39;spam&#39;] = df1[&#39;spam&#39;].map({&#39;ham&#39;:0, &#39;spam&#39;:1})  # Convert labels to 0 (ham) and 1 (spam)<br><br># Merge into one big dataset<br>df = pd.concat([df2, df1], ignore_index=True)</pre><p>Why this matters:</p><ul><li><strong>Dropping columns</strong>: Dataset 1 had extra, empty columns (2, 3, 4) that added no value, so we removed them to keep things tidy.</li><li><strong>Renaming</strong>: Consistent column names (mail, spam) make merging easier.</li><li><strong>Label conversion</strong>: Machine learning models need numbers, so we mapped ham to 0 and spam to 1.</li><li><strong>Merging</strong>: Combining datasets gives us more data (11,300 emails), which helps models learn better patterns.</li></ul><p><strong>Quick stats</strong>:</p><pre>print(df[&#39;spam&#39;].value_counts())</pre><ul><li><strong>Total emails</strong>: 11,300</li><li><strong>Spam</strong>: 2,115 (18.7%)</li><li><strong>Ham</strong>: 9,185 (81.3%)</li></ul><p>The dataset is imbalanced (more ham than spam), but it’s enough to get started.</p><h3>3. Text to Numbers: The CountVectorizer Trick</h3><p>Emails are words, but models only understand numbers. <em>CountVectorizer</em> transforms text into a matrix of word counts, where each email becomes a row, and each unique word in the dataset gets a column. The value in each cell is how many times that word appears in that email.</p><p>Example :</p><pre>&quot;win free money&quot; → {&#39;win&#39;:1, &#39;free&#39;:1, &#39;money&#39;:1}<br>&quot;free lunch lunch today&quot; → {&#39;free&#39;:1, &#39;lunch&#39;:2, &#39;today&#39;:1}</pre><p>We split the data into features (X: email text) and labels (y: spam or ham), then create training and testing sets:</p><pre>X = df[&#39;mail&#39;]<br>y = df[&#39;spam&#39;]<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)</pre><ul><li><strong>test_size = 0.2</strong>: 20% of data (2,260 emails) for testing, 80% (9,040) for training.</li><li><strong>stratify = y</strong>: Ensures the train/test split keeps the same spam-to-ham ratio as the full dataset.</li><li><strong>random_state = 42</strong>: Fixes the random split for reproducibility.</li></ul><p>Why this matters: Splitting data lets us train models on one part and test on another to simulate real-world performance. Stratification prevents skewed splits, especially with imbalanced data.</p><h3>4. The Great Model Showdown</h3><p>We trained five models using a <strong>Pipeline</strong>, which combines <em>CountVectorizer</em> with a <em>classifier</em>, ensuring text is processed and fed to the model seamlessly.</p><pre>models = {<br>    &#39;Naive Bayes&#39;: MultinomialNB(),<br>    &#39;SVM&#39;: SVC(C=1000, gamma=0.001),<br>    &#39;KNN&#39;: KNeighborsClassifier(n_neighbors=3),<br>    &#39;Decision Tree&#39;: DecisionTreeClassifier(),<br>    &#39;Random Forest&#39;: RandomForestClassifier()<br>}<br>for name, model in models.items():<br>    model.fit(X_train, y_train)<br>    y_pred = model.predict(X_test)<br>    print(name, &quot;Accuracy:&quot;, accuracy_score(y_test, y_pred))</pre><p>For each model, we:</p><ol><li>Create a pipeline: Pipeline([(‘vect’, CountVectorizer()), (‘clf’, model)])</li><li>Fit it on X_train, y_train</li><li>Predict on X_test and compute metrics like accuracy and precision.</li></ol><p><strong>What each model does</strong>:</p><ul><li><strong>Naive Bayes</strong>: A probabilistic model that calculates the likelihood of an email being spam based on word frequencies, assuming words are independent. Fast and great for text.</li><li><strong>SVM</strong>: Support Vector Classifier finds the best boundary to separate spam from ham in high-dimensional space, using an RBF kernel for non-linear patterns. The C=1000 controls strictness, and gamma=0.001 fine-tunes the decision boundary.</li><li><strong>KNN</strong>: Labels an email based on its similarity to the nearest n_neighbors=3 emails in the training set. Simple but sensitive to noisy data.</li><li><strong>Decision Tree</strong>: Builds a tree of yes/no questions (e.g., “Does it contain ‘free’?”) to classify emails. Clear but prone to overfitting.</li><li><strong>Random Forest </strong>: Combines multiple decision trees (an ensemble) to vote on the label, reducing overfitting and boosting accuracy.</li></ul><p><strong>Results</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8bmtyPFqM6MNw5ME3dXcw.png" /><figcaption><strong>Comparing of Algorithms</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*X4Sv173iXQHnRQOzCV6hFA.png" /></figure><p><strong>Why SVM won</strong>: Its ability to handle high-dimensional, sparse text data with fine-tuned parameters (C, gamma) made it the most precise and reliable.</p><h3>5. Live Test: Spam or Not?</h3><p>We built a function to test any email:</p><pre>def predict(model, text):<br>    return &quot;SPAM&quot; if model.predict([text])[0] == 1 else &quot;HAM&quot;<br><br># Train the champ (SVM)<br>svm = Pipeline([(&#39;vect&#39;, CountVectorizer()), (&#39;clf&#39;, SVC(C=1000, gamma=0.001))])<br>svm.fit(X_train, y_train)<br><br># Test it!<br>print(predict(svm, &quot;URGENT: Claim your prize now!&quot;))  # SPAM<br>print(predict(svm, &quot;Hey, lunch tomorrow?&quot;))           # HAM</pre><p>Why this matters: This function lets us instantly classify new emails, mimicking a real-world spam filter. The pipeline ensures the text is vectorized the same way as during training.</p><h3>6. Save the Hero Model</h3><p>To use our model later (e.g., in an app), we save it with <strong>pickle</strong>:</p><pre>with open(&quot;spam_slayer_svm.pkl&quot;, &quot;wb&quot;) as f:<br>    pickle.dump(svm, f)</pre><p>Why this matters: Pickling serializes the trained model to a file, so you can load it without retraining — perfect for deployment in web apps or email clients.</p><p>🔗 <em>Full notebook on GitHub : </em><a href="https://github.com/dijanidsaid/SpamDetector-ML">GitHub Link</a></p><h3>Your Turn!</h3><ol><li><strong>Fork the notebook</strong>: <a href="https://github.com/dijanidsaid/SpamDetector-ML">GitHub Link</a></li><li><strong>Test your spammiest email</strong></li><li><strong>Beat 99.1%</strong>: Tweak the model and share your score!</li></ol><blockquote><strong><em>Spam doesn’t stand a chance against ML.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0885f99fb10" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>