This project uses the K-Nearest Neighbors (KNN) algorithm to classify customers into segments based on their demographics and spending behavior. We go through building a base model, performing hyperparameter tuning, and analyzing the results with a focus on model performance and generalization.
We aim to predict a customerβs spending behavior category (Low, Medium, High) based on:
- Gender
- Age
- Annual Income
We transformed this into a classification problem by segmenting the Spending Score into 3 categories:
0: Low spender1: Medium spender2: High spender
Mall Customer Segmentation Data
π Download from Kaggle: Click here
Features:
Gender(converted to 0/1)AgeAnnual Income (k$)Spending Score (1β100)β Used to create target class:Segment
-
Data Cleaning & Preprocessing
- Encoded categorical variables
- Normalized features using
StandardScaler - Created a
Segmenttarget variable by binningSpending Score
-
Base KNN Model
- Used default
k=5 - Achieved high test accuracy: 82.5%
- However, this could be overfitting to the current train-test split
- Used default
-
Hyperparameter Tuning (GridSearchCV)
- Tuned
n_neighbors,weights, anddistance metric - Best parameters: e.g.,
k=4,weights='uniform',metric='euclidean' - Final test accuracy: 77.5%
- Accuracy slightly dropped but model generalizes better on unseen data
- Tuned
-
Elbow Method Visualization
- Confirmed
k=4is near the optimal elbow point
- Confirmed
| Model | Accuracy | Comment |
|---|---|---|
| Base KNN | 82.5% | High accuracy but overfitting |
| Tuned KNN (CV-based) | 77.5% | More stable, better generalization |
- The base model may have overfitted the test data (especially due to small dataset size).
- The tuned model, despite lower accuracy, is less biased by specific train-test splits and performs more reliably when predicting new or unseen data.
pandas,numpymatplotlib,seabornscikit-learn
- Always validate model performance using cross-validation, not just one train-test split.
- Higher accuracy β better model-generalization matters more.
- KNN is sensitive to scaling and the choice of
k, so visualization (like Elbow Method) is helpful.