ML & Data Science

Bank Term-Deposit Prediction

Classification · MLOps

MSc Data Science · Machine Learning coursework · Coventry University

Predicts which bank clients will subscribe to a term deposit, so marketing teams call the right people and stop spamming everyone else.

Role
ML Engineer
Year
2025
Focus
Classification
Stack
11 technologies
  • LightGBM
  • XGBoost
  • CatBoost
  • scikit-learn
  • PyTorch
  • SMOTE
  • MLflow
  • SHAP
  • LIME
  • FastAPI
  • Gradio
  • 0.94

    ROC-AUC (LightGBM, tuned)

  • 78%

    Precision: fewer wasted calls

  • 67%

    Recall: 2 in 3 subscribers found

  • 86,399

    Records after merging

  • 6

    Models tracked in MLflow

  • 24

    Features after engineering

Telemarketing campaigns waste most of their calls. Only about 12% of clients subscribe, an 88:12 (7.3:1) class imbalance that pushes naive models to predict 'no' for everyone. The strongest signal, call duration, is only known after the call ends, so it can't be used to decide who to call.

The UCI Bank Marketing data comes in two versions: bank-full (45,211 rows with client and campaign data) and bank-additional-full (41,188 rows that add five macroeconomic indicators). I combined them with an outer-join union into 86,399 records, removed duplicates, aligned column names, and cast categoricals to save memory. The trade-off is that about 52% of rows have no economic data, which is handled openly rather than hidden.

Missing economic values are filled with the median and flagged with a has_economic_data indicator, so the model can learn different patterns for rows with and without that context. Outliers were treated case by case with IQR: balance capped at the 99th percentile, campaign contacts at the 95th ('customer fatigue'), age kept in full. SMOTE balances the training split only, after the train/test split, so the test set still reflects the real 88:12 world.

Six algorithms were trained on 24 engineered features, each in its own MLflow run with parameters, metrics, training time, and model artifacts. LightGBM and XGBoost led on ROC-AUC (0.942 and 0.941). The best model was tuned with GridSearchCV, its decision threshold set for the business goal, and deployed to Hugging Face Spaces as a Gradio form and a FastAPI REST API.

Pipeline

  1. 01

    Merge

    outer join

    bank-full (45,211) and bank-additional-full (41,188) unioned into one 86,399-row schema.

  2. 02

    Clean

    Deduplicate, align column names, cast categoricals, median-impute the five economic indicators and add a has_economic_data flag.

  3. 03

    Explore

    Class balance, distributions, subscription rates by segment, and correlation with the target.

  4. 04

    Treat outliers

    IQR

    Cap balance at P99 and campaign at P95; keep age; keep duration for analysis only.

  5. 05

    Engineer

    contact_frequency, previous_campaign_success, age_group, duration_category, has_economic_data.

  6. 06

    Balance

    SMOTE

    Synthetic minority samples on the training split only, plus class weights.

  7. 07

    Train & track

    MLflow

    Logistic Regression, Random Forest, XGBoost, LightGBM, CatBoost, and a 128-64-32-1 neural network.

  8. 08

    Tune & explain

    GridSearchCV · SHAP

    Hyperparameter search, threshold optimisation, then SHAP, LIME, permutation importance, and PDPs.

  9. 09

    Serve

    Gradio · FastAPI

    Interactive web form plus single and batch prediction endpoints on Hugging Face Spaces.

Every chart below comes from the project notebooks in the GitHub repo. Tap any figure to zoom.

  1. Fig. 01 · EDA

    An 88:12 class imbalance

    Only about 12% of clients subscribed. A model that always says 'no' would be 88% accurate and useless, so accuracy alone can't be the yardstick.

    • ROC-AUC is the primary metric, with precision, recall, and F1 alongside it.
    • SMOTE is applied to the training split only, never the test set.
  2. Fig. 02 · Data quality

    The cost of merging two datasets

    The union merge keeps every row but leaves about 52% of records without the five economic indicators (and the two older-only columns missing for the rest).

    • Median imputation keeps the central tendency stable against outliers.
    • A has_economic_data flag tells the model which values were real and which were filled.
  3. Fig. 03 · Outliers · IQR

    Numeric features by outcome

    Balance and duration are heavily right-skewed, and campaign has a long tail of clients called dozens of times. Subscribers clearly had longer calls.

    • Balance capped at the 99th percentile so a few very wealthy clients don't dominate.
    • Campaign capped at the 95th percentile, reflecting customer fatigue.
    • Age outliers kept: every age is a valid customer group.
  4. Fig. 04 · Segment analysis

    Who actually subscribes

    Students, retired clients, and university graduates subscribe more often. Mobile contacts beat landlines, and March, September, October, and December stand out.

    • A previous campaign 'success' is the strongest categorical signal.
    • Seasonality and contact channel matter as much as demographics.
  5. Fig. 05 · Bivariate

    Correlation with the target

    Duration correlates most strongly (≈0.40) but is a post-call metric. The economic indicators (nr.employed, euribor3m, emp.var.rate) are strongly negative and highly correlated with each other.

  6. Fig. 06 · Evaluation

    ROC curves after tuning

    The gradient-boosted models (LightGBM, XGBoost, CatBoost) hug the top-left corner. Logistic Regression trails clearly, confirming the relationships aren't linear.

  7. Fig. 07 · Evaluation

    Precision-recall curves

    On imbalanced data the PR curve shows the real trade-off: how many extra subscribers you find for each extra wasted call. This is where the decision threshold was chosen.

  8. Fig. 08 · Error analysis

    LightGBM's confidence

    Most predictions sit near 0 or 1, with few false positives or negatives in the uncertain middle. That separation is what makes threshold tuning effective.

  9. Fig. 09 · Interpretability

    Feature importance across four models

    The tree models agree on a core set (duration, contact, previous success, economic indicators) but rank them differently, which is why model-agnostic methods were used next.

  10. Fig. 10 · Explainability

    SHAP: global explanation

    Each dot is one client. Long calls (red, high duration) push predictions strongly towards 'yes'; contact type, campaign count, day, and month follow.

  11. Fig. 11 · Local explanation

    SHAP: one client, step by step

    For this correctly predicted subscriber, a first contact, a previous campaign success, and age 53 add the most. A relatively short call is the only thing pulling the score down.

  12. Fig. 12 · Local explanation

    LIME: a second opinion

    LIME fits a simple local model around one prediction. It agrees with SHAP that short calls hurt and that having no default and no loan helps.

  13. Fig. 13 · Model-agnostic

    Permutation importance

    Shuffling duration costs the most ROC-AUC by far. Campaign and contact_frequency come next, so the engineered fatigue feature carries real signal.

  14. Fig. 14 · Feature effects

    Partial dependence

    Probability rises steadily with call duration, while campaign shows diminishing returns: past a few contacts, extra calls stop helping.

  • Logistic Regression

    baseline

    Interpretable linear floor with class_weight='balanced'. Tests whether subscribers are linearly separable.

  • Random Forest

    bagging

    Robust non-linear model, resistant to overfitting, with reliable native feature importance.

  • XGBoost

    boosting

    Regularised gradient boosting with scale_pos_weight for imbalance.

  • LightGBM

    selected

    Fastest and most memory-efficient on 86K rows. Highest ROC-AUC (0.942) and the model chosen for deployment.

  • CatBoost

    boosting

    Native categorical handling with auto_class_weights='Balanced', reducing leakage from encoding.

  • Neural network

    PyTorch

    128-64-32-1 with ReLU, dropout 0.3/0.3/0.2, Adam at lr 0.001. Benchmarks deep learning on tabular data.

ROC-AUC on the held-out test set

Top three models from the comparison run

  • LightGBM (selected)0.942
  • XGBoost0.941
  • Random Forest0.928

Accuracy after retraining and tuning

All six models, balanced evaluation set

  • LightGBM94.5%
  • XGBoost94.4%
  • CatBoost94.3%
  • Random Forest93.5%
  • Neural Network92.3%
  • Logistic Regression85.4%
  • Call duration is the single strongest predictor, but it's only known after the call. Using it for pre-call targeting is data leakage, so it's treated as an engagement signal, not a targeting input.
  • A 'success' in a previous campaign is one of the most powerful positive signals: customers behave consistently.
  • Macroeconomic indicators (euribor3m, emp.var.rate, nr.employed) act in regimes. Clients subscribe more when rates are low and the economy is uncertain, when term deposits look like a safe haven.
  • Campaign intensity shows diminishing returns. Too many contacts and long gaps since the last contact (stale leads) both lower the chance of a 'yes'.
  • Mobile beats landline, and March, September, October, and December are consistently better months.
  • One run per model with random_state, imbalance strategy (class_weight, scale_pos_weight, auto_class_weights), and algorithm-specific hyperparameters such as n_estimators=100, max_depth 6/10, learning_rate 0.1, subsample, and colsample_bytree.
  • Metrics logged for every run: ROC-AUC (primary), accuracy, precision, recall, F1, and training time.
  • Artifacts logged: the pickled model, confusion matrices, and feature-importance charts, giving a versioned model registry that can be reloaded exactly as trained.
  • The tuned production model and its preprocessing (label encoders and scaler) are saved separately for deployment.
  • Hosted on Hugging Face Spaces with no servers to manage: upload the model, preprocessing artifacts, and requirements, and the platform builds and launches it.
  • A Gradio web form lets non-technical users, such as bank managers, enter a client's details and get an instant prediction.
  • A FastAPI REST API (/predict, /predict/batch, /health, /model/info) lets CRM or mobile banking systems score leads automatically.
  • CI/CD workflows in GitHub Actions test the project and redeploy the Space.
  • The data comes from one Portuguese bank between 2008 and 2010, so it may not generalise to other countries, products, or economic conditions without retraining.
  • Models trained on age and job can reproduce historical bias, for example favouring 'management' over 'blue-collar' clients. Pre-deployment fairness audits (e.g. fairlearn) and a model card are recommended.
  • Targeting only 'likely' subscribers creates a feedback loop that hides new customer segments.
  • Balance and loan data are personal financial information, so use must follow GDPR and similar regulation.
  • Uplift modelling to find clients who subscribe because of the call, not those who would anyway.
  • Richer data: real-time economic APIs, broader demographics, and sentiment from call transcripts.
  • Tabular deep learning (TabTransformer, SAINT) and a stacked ensemble of LightGBM, XGBoost, and CatBoost.
  • A continuous-learning pipeline that retrains on new campaign data.