Task 6.1P¶

Part 2 - Logistic Regression and KNN on the Bank Marketing Dataset¶

Introduction¶

In this notebook, I complete the Week 6 problem-solving task using the bank-additional-full.csv dataset. I keep the analysis practical and concise: for each question, I show the model output, report the key metrics, and then give a short interpretation focused on business use.

The business goal is to predict whether a client will subscribe to a term deposit (y). Because the dataset is imbalanced (only about 11% positive), I use metrics beyond accuracy (ROC-AUC, recall, precision, F1, and specificity) and I test threshold tuning to support better campaign decisions. I also remove duration to avoid leakage and recode pdays=999 into a separate contact-history signal so the preprocessing matches the business meaning of the data.

In [25]:
from pathlib import Path
import time
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.base import clone
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
    accuracy_score,
    average_precision_score,
    confusion_matrix,
    ConfusionMatrixDisplay,
    f1_score,
    precision_recall_curve,
    precision_score,
    recall_score,
    roc_auc_score,
    roc_curve,
)
from sklearn.model_selection import (
    cross_validate,
    cross_val_predict,
    GridSearchCV,
    StratifiedKFold,
    train_test_split,
)
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

sns.set_theme(style="whitegrid")
ROOT = Path.cwd()
DATA_PATH = ROOT / "bank+marketing" / "bank-additional" / "bank-additional-full.csv"


def evaluate_model(y_true, y_pred, y_proba):
    """Return a dictionary of classification metrics including specificity."""
    tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
    return {
        'accuracy':      accuracy_score(y_true, y_pred),
        'precision':     precision_score(y_true, y_pred, zero_division=0),
        'recall':        recall_score(y_true, y_pred, zero_division=0),
        'f1':            f1_score(y_true, y_pred, zero_division=0),
        'specificity':   tn / (tn + fp),
        'roc_auc':       roc_auc_score(y_true, y_proba),
        'avg_precision': average_precision_score(y_true, y_proba),
        'tn': int(tn), 'fp': int(fp), 'fn': int(fn), 'tp': int(tp),
    }


def time_single_fit(estimator, X_fit, y_fit):
    t0 = time.time()
    clone(estimator).fit(X_fit, y_fit)
    return time.time() - t0

Dataset loading and exploratory analysis¶

Before modelling, I check data quality and distribution so the modelling choices are justified. I focus on three things:

  • Target imbalance (so I can choose suitable metrics).
  • Basic feature behaviour (numeric and categorical patterns).
  • Potential leakage risk (duration, which is known only after a call ends).

I remove duration before modelling to keep the solution realistic for real-world prediction, and I separate the special pdays=999 code into its own contact-history flag so that later scaling does not treat it like an ordinary numeric distance.

In [26]:
df = pd.read_csv(DATA_PATH, sep=';')
print(f"Dataset shape: {df.shape[0]:,} rows  x  {df.shape[1]} columns\n")

print("Data types and non-null counts:")
df.info(show_counts=True)

print("\nNumeric summary:")
display(df.describe().round(2))

df_model = df.drop(columns=['duration']).copy()
df_model['y_num'] = (df_model['y'] == 'yes').astype(int)
df_model['was_contacted_before'] = (df_model['pdays'] != 999).astype(int)
df_model['pdays'] = df_model['pdays'].replace(999, np.nan)

print("Target distribution:")
print(df_model['y'].value_counts().to_string())
print(f"Positive-class rate: {df_model['y_num'].mean():.2%}")
print("\nI recoded `pdays=999` into `was_contacted_before` and left `pdays` as missing")
print("for those never-contacted clients so the later scaler does not treat 999 as a")
print("real elapsed-day value.")

fig, ax = plt.subplots(figsize=(5, 3.5))
sns.countplot(data=df_model, x='y', hue='y', palette='muted', legend=False, ax=ax)
ax.set_title("Class distribution of target variable (y)")
ax.set_xlabel("Subscribed to term deposit")
ax.set_ylabel("Count")
for p in ax.patches:
    ax.annotate(f'{int(p.get_height()):,}',
                (p.get_x() + p.get_width() / 2., p.get_height()),
                ha='center', va='bottom', fontsize=10)
plt.tight_layout()
plt.show()

numeric_cols_plot = ['age', 'campaign', 'pdays', 'previous',
                     'emp.var.rate', 'cons.price.idx', 'cons.conf.idx',
                     'euribor3m', 'nr.employed']
fig, axes = plt.subplots(3, 3, figsize=(13, 9))
for ax, col in zip(axes.flatten(), numeric_cols_plot):
    sns.histplot(data=df_model, x=col, hue='y', bins=30, ax=ax,
                 multiple='stack', palette='Set2', legend=(col == 'age'))
    ax.set_title(col)
fig.suptitle("Numeric feature distributions (stacked by target)", y=1.00, fontsize=13)
plt.tight_layout()
plt.show()

corr_cols = numeric_cols_plot + ['was_contacted_before', 'y_num']
fig, ax = plt.subplots(figsize=(9, 7))
sns.heatmap(df_model[corr_cols].corr().round(2),
            annot=True, cmap='coolwarm', center=0, fmt='.2f', ax=ax)
ax.set_title("Correlation matrix of numeric features (with y_num)")
plt.tight_layout()
plt.show()

fig, axes = plt.subplots(2, 2, figsize=(13, 9))
for ax, col in zip(axes.flatten(), ['job', 'education', 'contact', 'poutcome']):
    rates = df_model.groupby(col)['y_num'].mean().sort_values()
    sns.barplot(x=rates.values, y=rates.index, hue=rates.index,
                dodge=False, legend=False, palette='viridis', ax=ax)
    ax.axvline(df_model['y_num'].mean(), color='red', linestyle='--',
               linewidth=1, label='overall rate')
    ax.set_title(f"Subscription rate by {col}")
    ax.set_xlabel("Rate")
    ax.legend(loc='lower right')
plt.tight_layout()
plt.show()
Dataset shape: 41,188 rows  x  21 columns

Data types and non-null counts:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 41188 entries, 0 to 41187
Data columns (total 21 columns):
 #   Column          Non-Null Count  Dtype  
---  ------          --------------  -----  
 0   age             41188 non-null  int64  
 1   job             41188 non-null  object 
 2   marital         41188 non-null  object 
 3   education       41188 non-null  object 
 4   default         41188 non-null  object 
 5   housing         41188 non-null  object 
 6   loan            41188 non-null  object 
 7   contact         41188 non-null  object 
 8   month           41188 non-null  object 
 9   day_of_week     41188 non-null  object 
 10  duration        41188 non-null  int64  
 11  campaign        41188 non-null  int64  
 12  pdays           41188 non-null  int64  
 13  previous        41188 non-null  int64  
 14  poutcome        41188 non-null  object 
 15  emp.var.rate    41188 non-null  float64
 16  cons.price.idx  41188 non-null  float64
 17  cons.conf.idx   41188 non-null  float64
 18  euribor3m       41188 non-null  float64
 19  nr.employed     41188 non-null  float64
 20  y               41188 non-null  object 
dtypes: float64(5), int64(5), object(11)
memory usage: 6.6+ MB

Numeric summary:
age duration campaign pdays previous emp.var.rate cons.price.idx cons.conf.idx euribor3m nr.employed
count 41188.00 41188.00 41188.00 41188.00 41188.00 41188.00 41188.00 41188.00 41188.00 41188.00
mean 40.02 258.29 2.57 962.48 0.17 0.08 93.58 -40.50 3.62 5167.04
std 10.42 259.28 2.77 186.91 0.49 1.57 0.58 4.63 1.73 72.25
min 17.00 0.00 1.00 0.00 0.00 -3.40 92.20 -50.80 0.63 4963.60
25% 32.00 102.00 1.00 999.00 0.00 -1.80 93.08 -42.70 1.34 5099.10
50% 38.00 180.00 2.00 999.00 0.00 1.10 93.75 -41.80 4.86 5191.00
75% 47.00 319.00 3.00 999.00 0.00 1.40 93.99 -36.40 4.96 5228.10
max 98.00 4918.00 56.00 999.00 7.00 1.40 94.77 -26.90 5.04 5228.10
Target distribution:
y
no     36548
yes     4640
Positive-class rate: 11.27%

I recoded `pdays=999` into `was_contacted_before` and left `pdays` as missing
for those never-contacted clients so the later scaler does not treat 999 as a
real elapsed-day value.
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image

What the EDA tells me¶

The dataset has 41,188 rows and is strongly imbalanced (~11.3% subscribers). This confirms that accuracy alone is not enough.

The macro-economic variables (emp.var.rate, euribor3m, nr.employed) show strong shared signal and high correlation, so regularisation is useful later to stabilise coefficients.

The pdays variable also needed cleaning: the code 999 means "not previously contacted", so I separated that into was_contacted_before and left pdays to represent only genuine elapsed-day information.

From categorical summaries, stronger conversion appears in groups such as poutcome='success', contact='cellular', and selected job/month segments. I keep these patterns in mind for Question 7.

Modelling setup¶

Before fitting any model, I keep the preprocessing and evaluation protocol in one place so the comparisons stay consistent.

  • I use a stratified 80/20 train/test split.
  • I keep a shared stratified 5-fold cross-validation object for Q1, Q2, Q3, Q6, and the out-of-fold Q7 scoring.
  • Numeric features use median imputation plus standardisation, while categorical features use most-frequent imputation plus one-hot encoding inside a single pipeline.
In [27]:
X = df_model.drop(columns=['y', 'y_num'])
y = df_model['y_num']

numeric_features = X.select_dtypes(include=['int64', 'float64']).columns.tolist()
categorical_features = [c for c in X.columns if c not in numeric_features]

print(f"Numeric features ({len(numeric_features)}): {numeric_features}")
print(f"Categorical features ({len(categorical_features)}): {categorical_features}")

numeric_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler()),
])
categorical_transformer = Pipeline([
    ('imputer', SimpleImputer(strategy='most_frequent')),
    ('onehot', OneHotEncoder(handle_unknown='ignore')),
])

preprocessor = ColumnTransformer([
    ('num', numeric_transformer, numeric_features),
    ('cat', categorical_transformer, categorical_features),
])

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y,
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)

print(f"\nStratified split → train: {X_train.shape[0]:,}   test: {X_test.shape[0]:,}")
print(f"Positive-class rate — train: {y_train.mean():.2%}   test: {y_test.mean():.2%}")
Numeric features (10): ['age', 'campaign', 'pdays', 'previous', 'emp.var.rate', 'cons.price.idx', 'cons.conf.idx', 'euribor3m', 'nr.employed', 'was_contacted_before']
Categorical features (10): ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']

Stratified split → train: 32,950   test: 8,238
Positive-class rate — train: 11.27%   test: 11.26%

Question 1 - Baseline logistic regression¶

For Question 1, I treat logistic regression as a clean baseline model. I fit it without explicit regularisation so later improvements from tuning and regularisation are easy to interpret.

To make the evaluation stronger than a single split, I first estimate baseline ROC-AUC and F1 with stratified 5-fold cross-validation on the training data, then I fit the same pipeline once on the full training split and report the held-out test metrics. This gives me both a resampled baseline and an out-of-sample result.

In [28]:
baseline_model = Pipeline([
    ('prep', preprocessor),
    ('model', LogisticRegression(max_iter=3000, penalty=None, solver='lbfgs')),
])

baseline_cv = cross_validate(
    baseline_model,
    X_train,
    y_train,
    cv=cv,
    scoring={'roc_auc': 'roc_auc', 'f1': 'f1'},
    n_jobs=-1,
)

baseline_cv_summary = pd.DataFrame([{
    'cv_roc_auc_mean': baseline_cv['test_roc_auc'].mean(),
    'cv_roc_auc_std': baseline_cv['test_roc_auc'].std(),
    'cv_f1_mean': baseline_cv['test_f1'].mean(),
    'cv_f1_std': baseline_cv['test_f1'].std(),
}]).round(4)

print("--- Baseline Logistic Regression: 5-fold CV on training set ---")
display(baseline_cv_summary)

t0 = time.time()
baseline_model.fit(X_train, y_train)
baseline_single_fit_time = time.time() - t0

baseline_proba = baseline_model.predict_proba(X_test)[:, 1]
baseline_pred = (baseline_proba >= 0.5).astype(int)

baseline_metrics = evaluate_model(y_test, baseline_pred, baseline_proba)
baseline_metrics['single_fit_time_sec'] = round(baseline_single_fit_time, 4)

print("\n--- Baseline Logistic Regression: Hold-out Test Performance ---")
baseline_display = pd.DataFrame([{k: round(v, 4) if isinstance(v, float) else v
                                  for k, v in baseline_metrics.items()}])
display(baseline_display)

fig, ax = plt.subplots(figsize=(4.5, 3.5))
ConfusionMatrixDisplay.from_predictions(
    y_test, baseline_pred, display_labels=['No', 'Yes'], cmap='Blues', ax=ax,
)
ax.set_title("Baseline logistic regression — confusion matrix")
plt.tight_layout()
plt.show()
--- Baseline Logistic Regression: 5-fold CV on training set ---
cv_roc_auc_mean cv_roc_auc_std cv_f1_mean cv_f1_std
0 0.7888 0.0066 0.3381 0.012
--- Baseline Logistic Regression: Hold-out Test Performance ---
accuracy precision recall f1 specificity roc_auc avg_precision tn fp fn tp single_fit_time_sec
0 0.9008 0.6881 0.2188 0.332 0.9874 0.8008 0.4659 7218 92 725 203 2.0452
No description has been provided for this image

Explanations¶

At the default 0.5 threshold the baseline achieves high accuracy and very high specificity, but recall is modest. In other words it rejects non-subscribers well yet misses a large share of actual subscribers — a typical conservative behaviour on imbalanced data. Questions 2, 3 and 5 explore how tuning, regularisation and threshold adjustment can improve this.

Question 2 - Hyperparameter tuning and optimisation¶

I did not use hyperparameter tuning in Question 1 because I wanted the first model to serve as a transparent, untuned baseline. In this section I run a broader logistic-regression tuning sweep with GridSearchCV and stratified 5-fold cross-validation, then compare the best configuration directly against the Q1 baseline.

My search space covers:

Hyperparameter Values
Penalty L1, L2
C (inverse regularisation strength) 0.01, 0.1, 1, 10
Class weight None, balanced
Scoring metric ROC-AUC

I chose ROC-AUC as the tuning objective because it is threshold-independent and more reliable than accuracy for imbalanced data. In this notebook the best overall Q2 configuration later reappears as the best L1 setting in Q3, so I use Q2 mainly to show the optimisation path from the untuned baseline to the strongest logistic operating point.

In [29]:
q2_pipeline = Pipeline([
    ('prep', preprocessor),
    ('model', LogisticRegression(max_iter=5000, solver='liblinear')),
])

q2_grid = {
    'model__penalty': ['l1', 'l2'],
    'model__C': [0.01, 0.1, 1, 10],
    'model__class_weight': [None, 'balanced'],
}

t0 = time.time()
q2_search = GridSearchCV(
    q2_pipeline, q2_grid, scoring='roc_auc',
    cv=cv, n_jobs=-1, return_train_score=True,
)
q2_search.fit(X_train, y_train)
q2_grid_search_time = time.time() - t0
q2_single_fit_time = time_single_fit(q2_search.best_estimator_, X_train, y_train)

print("Top 10 GridSearchCV configurations (ranked by CV ROC-AUC):\n")
q2_results = pd.DataFrame(q2_search.cv_results_)[[
    'param_model__penalty', 'param_model__C', 'param_model__class_weight',
    'mean_test_score', 'rank_test_score',
]].sort_values('rank_test_score').head(10).reset_index(drop=True)
display(q2_results)

print(f"\nBest parameters: {q2_search.best_params_}")
print(f"Best CV ROC-AUC:  {q2_search.best_score_:.4f}")
if q2_search.best_params_['model__penalty'] == 'l1':
    print("This best overall Q2 configuration is the same regularisation family that I")
    print("analyse separately as the L1 model in Q3, so Q2 functions as the tuning story")
    print("and Q3 provides the cleaner family-by-family comparison.")

traj = pd.DataFrame(q2_search.cv_results_).copy()
traj['penalty'] = traj['param_model__penalty'].astype(str)
traj['cw'] = traj['param_model__class_weight'].astype(str)
traj['C'] = traj['param_model__C'].astype(float)

fig, ax = plt.subplots(figsize=(8, 4.5))
for (pen, cw), grp in traj.groupby(['penalty', 'cw']):
    grp = grp.sort_values('C')
    ax.plot(grp['C'], grp['mean_test_score'],
            marker='o', label=f'{pen} | cw={cw}')
best_C = q2_search.best_params_['model__C']
best_score = q2_search.best_score_
ax.scatter([best_C], [best_score], color='red', s=120, zorder=5,
           label=f'best (C={best_C}, AUC={best_score:.4f})')
ax.set_xscale('log')
ax.set_xlabel("Inverse regularisation strength C (log scale)")
ax.set_ylabel("Mean CV ROC-AUC")
ax.set_title("Q2 — Optimisation trajectory: CV ROC-AUC vs C")
ax.legend(bbox_to_anchor=(1.02, 1), loc='upper left', fontsize=8)
plt.tight_layout()
plt.show()

pivot_data = pd.DataFrame(q2_search.cv_results_).copy()
pivot_data['setting'] = (pivot_data['param_model__penalty'].astype(str) + ' | C=' +
                         pivot_data['param_model__C'].astype(str))
pivot_table = pivot_data.pivot_table(
    values='mean_test_score', index='setting',
    columns='param_model__class_weight', aggfunc='mean',
)

fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(pivot_table, annot=True, fmt='.4f', cmap='YlOrRd', ax=ax)
ax.set_title("Q2 GridSearchCV — Mean ROC-AUC by Setting")
ax.set_xlabel("Class Weight")
ax.set_ylabel("Penalty | C")
plt.tight_layout()
plt.show()

q2_proba = q2_search.predict_proba(X_test)[:, 1]
q2_pred = (q2_proba >= 0.5).astype(int)
q2_metrics = evaluate_model(y_test, q2_pred, q2_proba)
q2_metrics['grid_search_time_sec'] = round(q2_grid_search_time, 4)
q2_metrics['single_fit_time_sec'] = round(q2_single_fit_time, 4)

print("\n--- Q1 vs Q2 Comparison ---")
skip = {'tn', 'fp', 'fn', 'tp'}
q1_vs_q2 = pd.DataFrame([
    {'model': 'Q1 — Baseline (no regularisation)',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in baseline_metrics.items() if k not in skip}},
    {'model': 'Q2 — Optimised broad sweep',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in q2_metrics.items() if k not in skip and not k.endswith('_sec')}},
])
display(q1_vs_q2)

print("\nCompared with the baseline, the tuned model improves recall and F1")
print("but gives up some accuracy. That is an expected accuracy-recall trade-off")
print("when class weighting makes the model more willing to flag potential subscribers.")
Top 10 GridSearchCV configurations (ranked by CV ROC-AUC):

param_model__penalty param_model__C param_model__class_weight mean_test_score rank_test_score
0 l1 0.1 balanced 0.789821 1
1 l2 0.1 balanced 0.789633 2
2 l2 1.0 balanced 0.789604 3
3 l1 0.1 None 0.789598 4
4 l1 1.0 balanced 0.789583 5
5 l2 10.0 balanced 0.789581 6
6 l1 10.0 balanced 0.789578 7
7 l2 0.1 None 0.789110 8
8 l1 1.0 None 0.789018 9
9 l2 1.0 None 0.788950 10
Best parameters: {'model__C': 0.1, 'model__class_weight': 'balanced', 'model__penalty': 'l1'}
Best CV ROC-AUC:  0.7898
This best overall Q2 configuration is the same regularisation family that I
analyse separately as the L1 model in Q3, so Q2 functions as the tuning story
and Q3 provides the cleaner family-by-family comparison.
No description has been provided for this image
No description has been provided for this image
--- Q1 vs Q2 Comparison ---
model accuracy precision recall f1 specificity roc_auc avg_precision single_fit_time_sec
0 Q1 — Baseline (no regularisation) 0.9008 0.6881 0.2188 0.332 0.9874 0.8008 0.4659 2.0452
1 Q2 — Optimised broad sweep 0.8343 0.3662 0.6444 0.467 0.8584 0.8012 0.4619 NaN
Compared with the baseline, the tuned model improves recall and F1
but gives up some accuracy. That is an expected accuracy-recall trade-off
when class weighting makes the model more willing to flag potential subscribers.

What the Q2 optimisation tells me¶

The broad sweep shows that balanced class weighting matters more than aggressive complexity changes. Compared with Q1, recall and F1 improve, while accuracy drops because the model now accepts more false positives in order to catch more true subscribers.

In this run, the best overall Q2 configuration is an L1 model with balanced class weighting. That is why the same setting shows up again in Q3. I therefore use Q2 as the tuning narrative and Q3 as the cleaner comparison between the named L1 and L2 regularisation families.

Overall, Q2 shows that tuning can move logistic regression to a more campaign-useful operating point without materially hurting its ranking quality.

Question 3 - Two regularised logistic regression models¶

For this question I built two separate regularised logistic regression models and evaluated them using the same stratified train/test split from Q1:

  1. L1 regularisation (LASSO) - this penalty can shrink some coefficients exactly to zero, effectively performing embedded feature selection. I find this valuable when I suspect that not every feature contributes meaningfully to the prediction. If L1 zeroes out a feature’s coefficient, it tells me that feature was not adding predictive value once the other features were accounted for.

  2. L2 regularisation (Ridge) - this penalty shrinks all coefficients smoothly towards zero without eliminating any entirely. It tends to produce more stable predictions when features are correlated, because it distributes the weight among correlated predictors rather than arbitrarily picking one.

I tuned the regularisation strength C and the class-weight setting for both models using the same stratified 5-fold cross-validation scheme and ROC-AUC scoring that I used in Q2, so that every comparison in this notebook uses a consistent evaluation framework.

In [30]:
# --- L1 (LASSO) ---
l1_pipeline = Pipeline([
    ('prep', preprocessor),
    ('model', LogisticRegression(max_iter=5000, solver='liblinear', penalty='l1')),
])
l1_grid = {'model__C': [0.01, 0.1, 1, 10], 'model__class_weight': [None, 'balanced']}

t0 = time.time()
l1_search = GridSearchCV(l1_pipeline, l1_grid, scoring='roc_auc', cv=cv, n_jobs=-1)
l1_search.fit(X_train, y_train)
l1_grid_search_time = time.time() - t0
l1_single_fit_time = time_single_fit(l1_search.best_estimator_, X_train, y_train)

# --- L2 (Ridge) ---
l2_pipeline = Pipeline([
    ('prep', preprocessor),
    ('model', LogisticRegression(max_iter=5000, solver='liblinear', penalty='l2')),
])
l2_grid = {'model__C': [0.01, 0.1, 1, 10], 'model__class_weight': [None, 'balanced']}

t0 = time.time()
l2_search = GridSearchCV(l2_pipeline, l2_grid, scoring='roc_auc', cv=cv, n_jobs=-1)
l2_search.fit(X_train, y_train)
l2_grid_search_time = time.time() - t0
l2_single_fit_time = time_single_fit(l2_search.best_estimator_, X_train, y_train)

print("Best L1 parameters:", l1_search.best_params_)
print("Best L2 parameters:", l2_search.best_params_)

l1_proba = l1_search.predict_proba(X_test)[:, 1]
l1_pred = (l1_proba >= 0.5).astype(int)
l1_metrics = evaluate_model(y_test, l1_pred, l1_proba)
l1_metrics['grid_search_time_sec'] = round(l1_grid_search_time, 4)
l1_metrics['single_fit_time_sec'] = round(l1_single_fit_time, 4)

l2_proba = l2_search.predict_proba(X_test)[:, 1]
l2_pred = (l2_proba >= 0.5).astype(int)
l2_metrics = evaluate_model(y_test, l2_pred, l2_proba)
l2_metrics['grid_search_time_sec'] = round(l2_grid_search_time, 4)
l2_metrics['single_fit_time_sec'] = round(l2_single_fit_time, 4)

skip = {'tn', 'fp', 'fn', 'tp'}
print("\n--- L1 (LASSO) Performance on Test Set ---")
display(pd.DataFrame([{k: round(v, 4) if isinstance(v, float) else v
                       for k, v in l1_metrics.items()
                       if k not in skip and not k.endswith('_sec')}]))

print("\n--- L2 (Ridge) Performance on Test Set ---")
display(pd.DataFrame([{k: round(v, 4) if isinstance(v, float) else v
                       for k, v in l2_metrics.items()
                       if k not in skip and not k.endswith('_sec')}]))

fig, axes = plt.subplots(1, 2, figsize=(10, 4))
for ax, pred, title in zip(axes,
                           [l1_pred, l2_pred],
                           ['L1 (LASSO)', 'L2 (Ridge)']):
    ConfusionMatrixDisplay.from_predictions(
        y_test, pred, display_labels=['No', 'Yes'], cmap='Blues', ax=ax)
    ax.set_title(f"Q3 — {title}")
plt.tight_layout()
plt.show()

print("\nBoth regularised models show higher recall and F1 than the baseline,")
print("which indicates regularisation helped the model generalise better on the minority class.")
Best L1 parameters: {'model__C': 0.1, 'model__class_weight': 'balanced'}
Best L2 parameters: {'model__C': 0.1, 'model__class_weight': 'balanced'}

--- L1 (LASSO) Performance on Test Set ---
accuracy precision recall f1 specificity roc_auc avg_precision
0 0.8343 0.3662 0.6444 0.467 0.8584 0.8012 0.4618
--- L2 (Ridge) Performance on Test Set ---
accuracy precision recall f1 specificity roc_auc avg_precision
0 0.8337 0.3657 0.6487 0.4678 0.8572 0.8009 0.4609
No description has been provided for this image
Both regularised models show higher recall and F1 than the baseline,
which indicates regularisation helped the model generalise better on the minority class.

What the Q3 regularised models tell me¶

Both L1 and L2 regularised models outperform the untuned baseline on minority-class detection and give similar overall ranking quality.

The practical difference is interpretability vs stability:

  • L1 can zero out some coefficients (simpler feature attribution).
  • L2 keeps all features with smoother shrinkage (often more stable with correlated inputs).

Since both are close in score, model choice can be based on deployment preference and interpretation needs.

Question 4 - Compare the three main logistic models¶

The task asks me to compare the three models from Q1 and Q3:

  1. Baseline logistic regression (Q1) - no regularisation
  2. L1-regularised logistic regression (Q3) - LASSO
  3. L2-regularised logistic regression (Q3) - Ridge

I assembled their test-set metrics into a single comparison table and plotted the key metrics side by side. I also plotted the ROC curves for all three models so that I could visually assess their ranking performance across every possible threshold.

My interpretation takes into account the nature of the problem: this is an imbalanced marketing dataset where the positive class (term-deposit subscribers) makes up only about 11 % of the sample. In that context, I weighted ROC-AUC, F1-score, and the precision-recall trade-off more heavily than raw accuracy, because a model that simply predicts “no” for everyone would already achieve roughly 89 % accuracy without being useful at all.

In [31]:
# Build the comparison table from metrics computed in Q1 and Q3
skip_cols = {'tn', 'fp', 'fn', 'tp', 'single_fit_time_sec', 'grid_search_time_sec'}
comparison_rows = [
    {'model': 'Q1 \u2014 Baseline (no regularisation)',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in baseline_metrics.items() if k not in skip_cols}},
    {'model': 'Q3 \u2014 L1 (LASSO)',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in l1_metrics.items() if k not in skip_cols}},
    {'model': 'Q3 \u2014 L2 (Ridge)',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in l2_metrics.items() if k not in skip_cols}},
]
main_comparison = pd.DataFrame(comparison_rows)

print("=== Three-Model Comparison (Q1 & Q3) ===\n")
display(main_comparison)

# ── bar chart of key metrics ──
plot_metrics = ['accuracy', 'precision', 'recall', 'f1', 'roc_auc', 'avg_precision', 'specificity']
plot_df = main_comparison.set_index('model')[plot_metrics].T

fig, ax = plt.subplots(figsize=(10, 5))
plot_df.plot(kind='bar', ax=ax, width=0.75)
ax.set_ylabel("Score")
ax.set_title("Q4 \u2014 Model Performance Comparison (Q1 vs Q3)")
ax.set_xticklabels(plot_metrics, rotation=30, ha='right')
ax.legend(title='Model', bbox_to_anchor=(1.02, 1), loc='upper left', fontsize=8)
ax.set_ylim(0, 1.05)
plt.tight_layout()
plt.show()

# ── ROC curves ──
fig, ax = plt.subplots(figsize=(7, 5))
for label, proba in [('Q1 \u2014 Baseline', baseline_proba),
                      ('Q3 \u2014 L1 (LASSO)', l1_proba),
                      ('Q3 \u2014 L2 (Ridge)', l2_proba)]:
    fpr, tpr, _ = roc_curve(y_test, proba)
    auc_val = roc_auc_score(y_test, proba)
    ax.plot(fpr, tpr, label=f'{label} (AUC={auc_val:.4f})')

ax.plot([0, 1], [0, 1], 'k--', alpha=0.4, label='Random classifier')
ax.set_xlabel("False Positive Rate")
ax.set_ylabel("True Positive Rate")
ax.set_title("Q4 \u2014 ROC Curves for the Three Main Logistic Models")
ax.legend(loc='lower right')
plt.tight_layout()
plt.show()

# ── confusion matrices side by side ──
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
for ax, pred, title in zip(axes,
                            [baseline_pred, l1_pred, l2_pred],
                            ['Baseline', 'L1 (LASSO)', 'L2 (Ridge)']):
    ConfusionMatrixDisplay.from_predictions(
        y_test, pred, display_labels=['No', 'Yes'], cmap='Blues', ax=ax)
    ax.set_title(title)
plt.suptitle("Q4 \u2014 Confusion Matrices", fontsize=13, y=1.02)
plt.tight_layout()
plt.show()

# ── interpretation ──
best_idx = main_comparison['f1'].idxmax()
best_model_name = main_comparison.loc[best_idx, 'model']
print(f"\nBased on the comparison, the best-performing model is: {best_model_name}")
print()
print("I chose this model because it achieves the strongest balance between precision")
print("and recall (highest F1), while maintaining competitive ROC-AUC. The baseline")
print("has higher accuracy and specificity, but its recall is very low, which means it")
print("misses most actual subscribers \u2014 a serious limitation in a marketing context")
print("where identifying potential subscribers is the whole point of the model.")
print()
print("Between L1 and L2, the differences are marginal, but L1 has the added benefit")
print("of embedded feature selection: it can shrink irrelevant coefficients to exactly")
print("zero, which makes the model easier to interpret and slightly more parsimonious.")
=== Three-Model Comparison (Q1 & Q3) ===

model accuracy precision recall f1 specificity roc_auc avg_precision
0 Q1 — Baseline (no regularisation) 0.9008 0.6881 0.2188 0.3320 0.9874 0.8008 0.4659
1 Q3 — L1 (LASSO) 0.8343 0.3662 0.6444 0.4670 0.8584 0.8012 0.4618
2 Q3 — L2 (Ridge) 0.8337 0.3657 0.6487 0.4678 0.8572 0.8009 0.4609
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
Based on the comparison, the best-performing model is: Q3 — L2 (Ridge)

I chose this model because it achieves the strongest balance between precision
and recall (highest F1), while maintaining competitive ROC-AUC. The baseline
has higher accuracy and specificity, but its recall is very low, which means it
misses most actual subscribers — a serious limitation in a marketing context
where identifying potential subscribers is the whole point of the model.

Between L1 and L2, the differences are marginal, but L1 has the added benefit
of embedded feature selection: it can shrink irrelevant coefficients to exactly
zero, which makes the model easier to interpret and slightly more parsimonious.

My verdict on the three-way comparison¶

Across Q1, L1, and L2, the regularised models are better choices for this task because they recover many more actual subscribers at acceptable precision.

The baseline has strong accuracy/specificity but is too conservative for campaign targeting. For this business use case, recall/F1 and balanced trade-off matter more than raw accuracy.

My selected model for downstream threshold analysis is the best-performing regularised logistic model from this comparison.

Question 5 - Change the prediction threshold¶

For this question I picked the best-performing Q4 model (by F1-score) programmatically, rather than hard-coding a choice, so the analysis stays correct even if the ranking changes on a different random seed. The default threshold in scikit-learn is 0.5, but in an imbalanced marketing dataset the optimal threshold may differ because the costs of false positives (wasted marketing calls) and false negatives (missed subscribers) are not equal.

I evaluate exactly the six thresholds listed in the task - 0.2, 0.3, 0.4, 0.6, 0.7, 0.8. I still report 0.5 separately as a labelled reference point so I can compare the default decision rule with the required set, but I do not let 0.5 compete for the "best required threshold" choice.

For each required threshold I compute the full set of metrics and then select the best threshold based on the F1-score, since F1 captures the balance between precision (not wasting calls) and recall (not missing subscribers) in a single number.

In [32]:
proba_lookup = {
    'Q1 — Baseline (no regularisation)': baseline_proba,
    'Q3 — L1 (LASSO)': l1_proba,
    'Q3 — L2 (Ridge)': l2_proba,
}
best_idx_q4 = main_comparison['f1'].idxmax()
best_name_q4 = main_comparison.loc[best_idx_q4, 'model']
best_q4_proba = proba_lookup[best_name_q4]
print(f"Threshold study applied to the best Q4 model: {best_name_q4}\n")

required_thresholds = [0.2, 0.3, 0.4, 0.6, 0.7, 0.8]
reference_threshold = 0.5
threshold_rows = []

for t in required_thresholds:
    t_pred = (best_q4_proba >= t).astype(int)
    row = evaluate_model(y_test, t_pred, best_q4_proba)
    row['threshold'] = t
    threshold_rows.append(row)

threshold_df = pd.DataFrame(threshold_rows)
col_order = ['threshold', 'accuracy', 'precision', 'recall', 'f1',
             'specificity', 'roc_auc', 'avg_precision', 'tn', 'fp', 'fn', 'tp']
threshold_df = threshold_df[col_order].round(4)

ref_pred = (best_q4_proba >= reference_threshold).astype(int)
reference_row = evaluate_model(y_test, ref_pred, best_q4_proba)
reference_row['threshold'] = reference_threshold
reference_df = pd.DataFrame([reference_row])[col_order].round(4)

print(f"=== Required threshold analysis on the best Q4 model: {best_name_q4} ===\n")
display(threshold_df)

print("=== Default threshold reference (not included in the best-threshold search) ===\n")
display(reference_df)

fig, ax = plt.subplots(figsize=(9, 5))
for metric in ['accuracy', 'precision', 'recall', 'f1', 'specificity']:
    ax.plot(threshold_df['threshold'], threshold_df[metric], marker='o', label=metric)
ax.axvline(reference_threshold, color='black', linestyle='--', linewidth=1,
           label='reference t=0.5')
ax.set_xlabel("Prediction threshold")
ax.set_ylabel("Score")
ax.set_title(f"Q5 — Effect of threshold on model performance ({best_name_q4})")
ax.legend(loc='center left', bbox_to_anchor=(1.02, 0.5))
ax.set_xticks(required_thresholds + [reference_threshold])
ax.set_ylim(0, 1.05)
plt.tight_layout()
plt.show()

pr_prec, pr_rec, pr_thr = precision_recall_curve(y_test, best_q4_proba)
pr_f1 = 2 * pr_prec * pr_rec / (pr_prec + pr_rec + 1e-12)
best_cont_idx = int(np.nanargmax(pr_f1[:-1]))

fig, ax = plt.subplots(figsize=(7, 4.5))
ax.plot(pr_rec, pr_prec, label='PR curve')
ax.scatter(pr_rec[best_cont_idx], pr_prec[best_cont_idx], color='red', zorder=5,
           label=f'continuous F1 max @ t={pr_thr[best_cont_idx]:.2f}')
for t in required_thresholds + [reference_threshold]:
    t_pred = (best_q4_proba >= t).astype(int)
    recall_at_t = recall_score(y_test, t_pred, zero_division=0)
    precision_at_t = precision_score(y_test, t_pred, zero_division=0)
    marker = 'D' if t == reference_threshold else 'x'
    ax.scatter(recall_at_t, precision_at_t, marker=marker, s=60)
    label = 't=0.5 ref' if t == reference_threshold else f't={t}'
    ax.annotate(label, (recall_at_t, precision_at_t),
                textcoords='offset points', xytext=(5, 4), fontsize=8)
ax.set_xlabel("Recall")
ax.set_ylabel("Precision")
ax.set_title(f"Q5 — Precision-recall curve ({best_name_q4})")
ax.legend(loc='lower left')
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.tight_layout()
plt.show()

best_row = threshold_df.loc[threshold_df['f1'].idxmax()]
print(f"\nBest threshold from the required set by F1-score: {best_row['threshold']}")
print(f"  Accuracy:    {best_row['accuracy']:.4f}")
print(f"  Precision:   {best_row['precision']:.4f}")
print(f"  Recall:      {best_row['recall']:.4f}")
print(f"  F1:          {best_row['f1']:.4f}")
print(f"  Specificity: {best_row['specificity']:.4f}")
print()
print(f"The default 0.5 threshold is shown separately as a reference point, but the")
print("recommended operating threshold above is chosen only from the exact task list.")
print("Lower thresholds below 0.4 recover more subscribers but create too many false")
print("positives, while higher thresholds above 0.7 become too conservative.")
Threshold study applied to the best Q4 model: Q3 — L2 (Ridge)

=== Required threshold analysis on the best Q4 model: Q3 — L2 (Ridge) ===

threshold accuracy precision recall f1 specificity roc_auc avg_precision tn fp fn tp
0 0.2 0.2117 0.1221 0.9688 0.2168 0.1156 0.8009 0.4609 845 6465 29 899
1 0.3 0.4869 0.1640 0.8675 0.2758 0.4386 0.8009 0.4609 3206 4104 123 805
2 0.4 0.7469 0.2707 0.7360 0.3958 0.7483 0.8009 0.4609 5470 1840 245 683
3 0.6 0.8594 0.4168 0.6207 0.4987 0.8897 0.8009 0.4609 6504 806 352 576
4 0.7 0.8801 0.4710 0.5259 0.4969 0.9250 0.8009 0.4609 6762 548 440 488
5 0.8 0.8927 0.5312 0.4041 0.4590 0.9547 0.8009 0.4609 6979 331 553 375
=== Default threshold reference (not included in the best-threshold search) ===

threshold accuracy precision recall f1 specificity roc_auc avg_precision tn fp fn tp
0 0.5 0.8337 0.3657 0.6487 0.4678 0.8572 0.8009 0.4609 6266 1044 326 602
No description has been provided for this image
No description has been provided for this image
Best threshold from the required set by F1-score: 0.6
  Accuracy:    0.8594
  Precision:   0.4168
  Recall:      0.6207
  F1:          0.4987
  Specificity: 0.8897

The default 0.5 threshold is shown separately as a reference point, but the
recommended operating threshold above is chosen only from the exact task list.
Lower thresholds below 0.4 recover more subscribers but create too many false
positives, while higher thresholds above 0.7 become too conservative.

What the threshold study tells me¶

Threshold tuning changes the campaign trade-off directly:

  • Lower thresholds increase recall but create too many false positives.
  • Higher thresholds increase precision/specificity but miss more true subscribers.

From the tested set [0.2, 0.3, 0.4, 0.6, 0.7, 0.8], the best choice is the threshold that gives the strongest balance (highest practical F1 with acceptable precision/recall for outreach capacity). This becomes my recommended operating threshold for deployment.

Question 6 - KNN tuning and comparison with logistic regression¶

Continuing from Question 4 and using the same evaluation setting, I now build and tune a K-Nearest Neighbours (KNN) classifier. I tune the following hyperparameters on the training set using stratified 5-fold cross-validation:

Hyperparameter Values
K (n_neighbors) 21, 31, 51, 75, 101
Weight scheme uniform, distance
Distance metric (p) 1 (Manhattan), 2 (Euclidean)

After finding the optimal K, I evaluate the best KNN model on the held-out test set and then compare it with all four logistic regression models from the previous questions. To keep the timing story fair, I report both the total GridSearchCV time and the single-fit time of the final best estimator for every model.

In [33]:
knn_pipeline = Pipeline([
    ('prep', preprocessor),
    ('model', KNeighborsClassifier()),
])

knn_grid = {
    'model__n_neighbors': [21, 31, 51, 75, 101],
    'model__weights': ['uniform', 'distance'],
    'model__p': [1, 2],
}

t0 = time.time()
knn_search = GridSearchCV(
    knn_pipeline, knn_grid, scoring='roc_auc',
    cv=cv, n_jobs=-1, return_train_score=True,
)
knn_search.fit(X_train, y_train)
knn_grid_search_time = time.time() - t0
knn_single_fit_time = time_single_fit(knn_search.best_estimator_, X_train, y_train)

print("Top 10 KNN configurations (ranked by CV ROC-AUC):\n")
knn_results = pd.DataFrame(knn_search.cv_results_)[[
    'param_model__n_neighbors', 'param_model__weights', 'param_model__p',
    'mean_test_score', 'rank_test_score',
]].sort_values('rank_test_score').head(10).reset_index(drop=True)
display(knn_results)

print(f"\nBest parameters: {knn_search.best_params_}")
print(f"Best CV ROC-AUC:  {knn_search.best_score_:.4f}")
print(f"Optimal K:        {knn_search.best_params_['model__n_neighbors']}")

knn_cv = pd.DataFrame(knn_search.cv_results_).copy()
knn_cv['setting'] = ('w=' + knn_cv['param_model__weights'].astype(str) +
                     ' | p=' + knn_cv['param_model__p'].astype(str))
knn_pivot = knn_cv.pivot_table(
    values='mean_test_score', index='param_model__n_neighbors',
    columns='setting', aggfunc='mean',
)

fig, ax = plt.subplots(figsize=(8, 4.5))
sns.heatmap(knn_pivot, annot=True, fmt='.4f', cmap='YlGnBu', ax=ax)
ax.set_title("Q6 — KNN GridSearchCV: Mean ROC-AUC by K and Setting")
ax.set_xlabel("Weight | Distance Metric")
ax.set_ylabel("K (n_neighbors)")
plt.tight_layout()
plt.show()

knn_k_perf = (knn_cv.groupby('param_model__n_neighbors')['mean_test_score']
              .max().reset_index())
knn_k_perf.columns = ['K', 'best_cv_roc_auc']

fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(knn_k_perf['K'], knn_k_perf['best_cv_roc_auc'], marker='o', linewidth=2)
best_k_row = knn_k_perf.loc[knn_k_perf['best_cv_roc_auc'].idxmax()]
ax.scatter([best_k_row['K']], [best_k_row['best_cv_roc_auc']],
           color='red', s=120, zorder=5,
           label=f"optimal K={int(best_k_row['K'])} (AUC={best_k_row['best_cv_roc_auc']:.4f})")
ax.set_xlabel("K (n_neighbors)")
ax.set_ylabel("Best CV ROC-AUC (across weight/p settings)")
ax.set_title("Q6 — KNN: ROC-AUC vs K")
ax.legend()
ax.set_xticks(knn_k_perf['K'].astype(int))
plt.tight_layout()
plt.show()

knn_proba = knn_search.predict_proba(X_test)[:, 1]
knn_pred = (knn_proba >= 0.5).astype(int)
knn_metrics = evaluate_model(y_test, knn_pred, knn_proba)
knn_metrics['grid_search_time_sec'] = round(knn_grid_search_time, 4)
knn_metrics['single_fit_time_sec'] = round(knn_single_fit_time, 4)

print("\n--- KNN Performance on Test Set ---")
skip_cols = {'tn', 'fp', 'fn', 'tp'}
display(pd.DataFrame([{k: round(v, 4) if isinstance(v, float) else v
                       for k, v in knn_metrics.items()
                       if k not in skip_cols and not k.endswith('_sec')}]))

fitted_prep = l1_search.best_estimator_.named_steps['prep']
n_features = fitted_prep.transform(X_train.iloc[:1]).shape[1]

all_models = pd.DataFrame([
    {'model': 'Q1 — Baseline (no regularisation)',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in baseline_metrics.items()
        if k not in skip_cols and not k.endswith('_sec')}},
    {'model': 'Q2 — Optimised broad sweep',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in q2_metrics.items()
        if k not in skip_cols and not k.endswith('_sec')}},
    {'model': 'Q3 — L1 (LASSO)',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in l1_metrics.items()
        if k not in skip_cols and not k.endswith('_sec')}},
    {'model': 'Q3 — L2 (Ridge)',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in l2_metrics.items()
        if k not in skip_cols and not k.endswith('_sec')}},
    {'model': 'Q6 — KNN (optimised)',
     **{k: round(v, 4) if isinstance(v, float) else v
        for k, v in knn_metrics.items()
        if k not in skip_cols and not k.endswith('_sec')}},
])

print("\n=== Unified Performance Comparison — All 5 Models ===\n")
display(all_models)

param_table = pd.DataFrame([
    {'model': 'Q1 — Baseline', 'trainable_parameters': n_features + 1,
     'note': f'{n_features} coefficients + 1 intercept'},
    {'model': 'Q2 — Optimised', 'trainable_parameters': n_features + 1,
     'note': f'{n_features} coefficients + 1 intercept'},
    {'model': 'Q3 — L1 (LASSO)', 'trainable_parameters': n_features + 1,
     'note': f'{n_features} coefficients + 1 intercept (some shrunk to zero by L1)'},
    {'model': 'Q3 — L2 (Ridge)', 'trainable_parameters': n_features + 1,
     'note': f'{n_features} coefficients + 1 intercept (all shrunk smoothly by L2)'},
    {'model': 'Q6 — KNN', 'trainable_parameters': 0,
     'note': f'Stores all {X_train.shape[0]:,} training samples; no learned coefficients'},
])
print("\n--- Number of Trainable Parameters ---\n")
display(param_table)

time_table = pd.DataFrame([
    {'model': 'Q1 — Baseline', 'grid_search_total_sec': np.nan,
     'single_fit_sec': baseline_metrics['single_fit_time_sec'],
     'note': 'No grid search in Q1'},
    {'model': 'Q2 — Optimised', 'grid_search_total_sec': q2_metrics['grid_search_time_sec'],
     'single_fit_sec': q2_metrics['single_fit_time_sec'],
     'note': 'Broad logistic sweep'},
    {'model': 'Q3 — L1 (LASSO)', 'grid_search_total_sec': l1_metrics['grid_search_time_sec'],
     'single_fit_sec': l1_metrics['single_fit_time_sec'],
     'note': 'Regularised logistic fit'},
    {'model': 'Q3 — L2 (Ridge)', 'grid_search_total_sec': l2_metrics['grid_search_time_sec'],
     'single_fit_sec': l2_metrics['single_fit_time_sec'],
     'note': 'Regularised logistic fit'},
    {'model': 'Q6 — KNN', 'grid_search_total_sec': knn_metrics['grid_search_time_sec'],
     'single_fit_sec': knn_metrics['single_fit_time_sec'],
     'note': 'KNN stores neighbours; fit itself is cheap'},
]).round(4)
print("\n--- Training Time Comparison ---\n")
display(time_table)

fig, ax = plt.subplots(figsize=(8, 5.5))
for label, proba in [('Q1 — Baseline', baseline_proba),
                     ('Q2 — Optimised', q2_proba),
                     ('Q3 — L1 (LASSO)', l1_proba),
                     ('Q3 — L2 (Ridge)', l2_proba),
                     ('Q6 — KNN', knn_proba)]:
    fpr, tpr, _ = roc_curve(y_test, proba)
    auc_val = roc_auc_score(y_test, proba)
    ax.plot(fpr, tpr, label=f'{label} (AUC={auc_val:.4f})')

ax.plot([0, 1], [0, 1], 'k--', alpha=0.4, label='Random')
ax.set_xlabel("False Positive Rate")
ax.set_ylabel("True Positive Rate")
ax.set_title("Q6 — ROC Curves: All Models")
ax.legend(loc='lower right', fontsize=8)
plt.tight_layout()
plt.show()

plot_metrics = ['accuracy', 'precision', 'recall', 'f1', 'roc_auc', 'avg_precision']
plot_df = all_models.set_index('model')[plot_metrics].T

fig, ax = plt.subplots(figsize=(12, 5))
plot_df.plot(kind='bar', ax=ax, width=0.8)
ax.set_ylabel("Score")
ax.set_title("Q6 — Unified Model Comparison")
ax.set_xticklabels(plot_metrics, rotation=30, ha='right')
ax.legend(title='Model', bbox_to_anchor=(1.02, 1), loc='upper left', fontsize=7)
ax.set_ylim(0, 1.05)
plt.tight_layout()
plt.show()

optimal_k = knn_search.best_params_['model__n_neighbors']
print(f"\n--- My Interpretation ---")
print(f"\nThe optimal K found by cross-validation is {optimal_k}.")
print()
print("Comparing KNN to the logistic regression models across the three required dimensions:")
print()
print("1. TRAINABLE PARAMETERS")
print(f"   Logistic regression learns {n_features + 1} explicit coefficients, while KNN")
print(f"   stores all {X_train.shape[0]:,} training samples and has no explicit learned weights.")
print()
print("2. TRAINING TIME")
print("   The total GridSearchCV time is driven by how many cross-validated fits each search")
print("   has to perform. Looking only at the single-fit column, KNN is cheap to fit, whereas")
print("   logistic regression spends more time estimating coefficients. KNN still remains more")
print("   expensive at prediction time because it must compute distances to stored neighbours.")
print()
print("3. MODEL PERFORMANCE")
print("   KNN keeps strong accuracy and specificity but lags behind the regularised logistic")
print("   models on recall, F1, and average precision. For this marketing problem, that means")
print("   KNN misses too many real subscribers.")
print()
print("Overall, I would deploy regularised logistic regression instead of KNN because it")
print("handles class imbalance better, gives interpretable coefficients, and is more suitable")
print("for wide one-hot encoded tabular data.")
Top 10 KNN configurations (ranked by CV ROC-AUC):

param_model__n_neighbors param_model__weights param_model__p mean_test_score rank_test_score
0 101 uniform 1 0.779638 1
1 101 uniform 2 0.778310 2
2 75 uniform 1 0.777395 3
3 75 uniform 2 0.776016 4
4 51 uniform 1 0.774992 5
5 51 uniform 2 0.773127 6
6 31 uniform 1 0.770537 7
7 101 distance 2 0.768311 8
8 31 uniform 2 0.767994 9
9 101 distance 1 0.767774 10
Best parameters: {'model__n_neighbors': 101, 'model__p': 1, 'model__weights': 'uniform'}
Best CV ROC-AUC:  0.7796
Optimal K:        101
No description has been provided for this image
No description has been provided for this image
--- KNN Performance on Test Set ---
accuracy precision recall f1 specificity roc_auc avg_precision
0 0.9006 0.7121 0.1972 0.3089 0.9899 0.795 0.4587
=== Unified Performance Comparison — All 5 Models ===

model accuracy precision recall f1 specificity roc_auc avg_precision
0 Q1 — Baseline (no regularisation) 0.9008 0.6881 0.2188 0.3320 0.9874 0.8008 0.4659
1 Q2 — Optimised broad sweep 0.8343 0.3662 0.6444 0.4670 0.8584 0.8012 0.4619
2 Q3 — L1 (LASSO) 0.8343 0.3662 0.6444 0.4670 0.8584 0.8012 0.4618
3 Q3 — L2 (Ridge) 0.8337 0.3657 0.6487 0.4678 0.8572 0.8009 0.4609
4 Q6 — KNN (optimised) 0.9006 0.7121 0.1972 0.3089 0.9899 0.7950 0.4587
--- Number of Trainable Parameters ---

model trainable_parameters note
0 Q1 — Baseline 64 63 coefficients + 1 intercept
1 Q2 — Optimised 64 63 coefficients + 1 intercept
2 Q3 — L1 (LASSO) 64 63 coefficients + 1 intercept (some shrunk to ...
3 Q3 — L2 (Ridge) 64 63 coefficients + 1 intercept (all shrunk smoo...
4 Q6 — KNN 0 Stores all 32,950 training samples; no learned...
--- Training Time Comparison ---

model grid_search_total_sec single_fit_sec note
0 Q1 — Baseline NaN 2.0452 No grid search in Q1
1 Q2 — Optimised 14.4587 1.1130 Broad logistic sweep
2 Q3 — L1 (LASSO) 10.3379 1.1030 Regularised logistic fit
3 Q3 — L2 (Ridge) 1.3000 0.1353 Regularised logistic fit
4 Q6 — KNN 123.1453 0.0775 KNN stores neighbours; fit itself is cheap
No description has been provided for this image
No description has been provided for this image
--- My Interpretation ---

The optimal K found by cross-validation is 101.

Comparing KNN to the logistic regression models across the three required dimensions:

1. TRAINABLE PARAMETERS
   Logistic regression learns 64 explicit coefficients, while KNN
   stores all 32,950 training samples and has no explicit learned weights.

2. TRAINING TIME
   The total GridSearchCV time is driven by how many cross-validated fits each search
   has to perform. Looking only at the single-fit column, KNN is cheap to fit, whereas
   logistic regression spends more time estimating coefficients. KNN still remains more
   expensive at prediction time because it must compute distances to stored neighbours.

3. MODEL PERFORMANCE
   KNN keeps strong accuracy and specificity but lags behind the regularised logistic
   models on recall, F1, and average precision. For this marketing problem, that means
   KNN misses too many real subscribers.

Overall, I would deploy regularised logistic regression instead of KNN because it
handles class imbalance better, gives interpretable coefficients, and is more suitable
for wide one-hot encoded tabular data.

My verdict on KNN vs logistic regression¶

KNN was tuned correctly, but logistic regression remains the better fit for this dataset.

Why:

  • Better minority-class trade-off after class weighting/regularisation.
  • More interpretable feature effects for business explanation.
  • More deployment-friendly behaviour on wide one-hot encoded tabular data.

KNN has no explicit trainable coefficients, but it is less robust here due to imbalance and high-dimensional distance behaviour. So I would deploy logistic regression, not KNN.

Question 7 - Which clients are more likely to subscribe?¶

To answer this question I took a multi-angle approach rather than relying on just one method. I combined three complementary analytical perspectives so that the conclusions are robust to the limitations of any single view:

  1. Observed subscription rates. I computed the actual subscription rate for each subgroup in the raw dataset. This tells me which groups historically subscribed more often, without any modelling bias.

  2. Average predicted probability. I used the best logistic model (L1 LASSO) to score every client in the dataset, then averaged those predicted probabilities within each subgroup. To keep this analysis unbiased I used cross_val_predict for the training rows (so every score is out-of-fold) and the held-out test probabilities for the remaining rows - no client is ever scored by a model that was fitted on their own label. This tells me which groups the model believes are more likely to subscribe after accounting for all features simultaneously.

  3. Logistic regression coefficients. I extracted the fitted coefficients from the L1 model and ranked them by magnitude. Positive coefficients increase the log-odds of subscription; negative coefficients decrease them. For numeric variables, these magnitudes are on the standardised scale, so a one-unit shift means roughly a one-standard-deviation change rather than a one-point raw-unit increase.

By triangulating across all three perspectives I can identify client groups that are consistently associated with higher subscription likelihood - not just in the raw data, but also in the fitted model. I finish the section with a small combined-profile analysis to give the bank an actionable, marketing-ready recommendation.

In [34]:
categorical_cols = ['job', 'marital', 'education', 'default', 'housing',
                    'loan', 'contact', 'month', 'day_of_week', 'poutcome']

segment_rows = []
for col in categorical_cols:
    rates = df_model.groupby(col)['y_num'].agg(['mean', 'count']).reset_index()
    rates.columns = [col, 'subscribe_rate', 'count']
    for _, r in rates.iterrows():
        segment_rows.append({
            'feature': col,
            'value': r[col],
            'subscribe_rate': round(r['subscribe_rate'], 4),
            'count': int(r['count']),
        })

segment_df = pd.DataFrame(segment_rows).sort_values('subscribe_rate', ascending=False)

print("=== Top 15 Subgroups by Observed Subscription Rate ===\n")
display(segment_df.head(15).reset_index(drop=True))

top_n = segment_df.head(12).copy()
top_n['label'] = top_n['feature'] + ' = ' + top_n['value'].astype(str)

fig, ax = plt.subplots(figsize=(9, 5))
sns.barplot(data=top_n, y='label', x='subscribe_rate', hue='label',
            dodge=False, legend=False, palette='viridis', ax=ax)
ax.set_xlabel("Observed Subscription Rate")
ax.set_ylabel("")
ax.set_title("Q7 — Top Client Segments by Subscription Rate")
for i, (rate, cnt) in enumerate(zip(top_n['subscribe_rate'], top_n['count'])):
    ax.text(rate + 0.01, i, f'{rate:.1%} (n={cnt:,})', va='center', fontsize=9)
ax.set_xlim(0, top_n['subscribe_rate'].max() * 1.3)
plt.tight_layout()
plt.show()

oof_train_proba = cross_val_predict(
    l1_search.best_estimator_, X_train, y_train,
    cv=cv, method='predict_proba', n_jobs=-1,
)[:, 1]

pred_prob_all = pd.Series(index=df_model.index, dtype=float)
pred_prob_all.loc[X_train.index] = oof_train_proba
pred_prob_all.loc[X_test.index] = l1_proba
df_model['pred_prob'] = pred_prob_all

print("\n=== Subscription Rate & Predicted Probability by Job ===\n")
job_table = (df_model.groupby('job')
             .agg(subscribe_rate=('y_num', 'mean'),
                  avg_pred_prob=('pred_prob', 'mean'),
                  count=('y_num', 'count'))
             .sort_values('subscribe_rate', ascending=False)
             .round(4))
display(job_table)

print("\n=== Subscription Rate & Predicted Probability by Month ===\n")
month_table = (df_model.groupby('month')
               .agg(subscribe_rate=('y_num', 'mean'),
                    avg_pred_prob=('pred_prob', 'mean'),
                    count=('y_num', 'count'))
               .sort_values('subscribe_rate', ascending=False)
               .round(4))
display(month_table)

print("\n=== Subscription Rate & Predicted Probability by Contact Method ===\n")
contact_table = (df_model.groupby('contact')
                 .agg(subscribe_rate=('y_num', 'mean'),
                      avg_pred_prob=('pred_prob', 'mean'),
                      count=('y_num', 'count'))
                 .sort_values('subscribe_rate', ascending=False)
                 .round(4))
display(contact_table)

print("\n=== Subscription Rate & Predicted Probability by Previous Outcome ===\n")
poutcome_table = (df_model.groupby('poutcome')
                  .agg(subscribe_rate=('y_num', 'mean'),
                       avg_pred_prob=('pred_prob', 'mean'),
                       count=('y_num', 'count'))
                  .sort_values('subscribe_rate', ascending=False)
                  .round(4))
display(poutcome_table)

l1_best = l1_search.best_estimator_
feature_names = (numeric_features +
                 list(l1_best.named_steps['prep']
                      .named_transformers_['cat']
                      .named_steps['onehot']
                      .get_feature_names_out(categorical_features)))
coef_df = pd.DataFrame({
    'feature': feature_names,
    'coefficient': l1_best.named_steps['model'].coef_[0],
}).sort_values('coefficient', ascending=False)

print("\n=== Top 15 Positive Coefficients (increase subscription likelihood) ===\n")
display(coef_df.head(15).round(4).reset_index(drop=True))

print("\n=== Top 15 Negative Coefficients (decrease subscription likelihood) ===\n")
display(coef_df.tail(15).sort_values('coefficient').round(4).reset_index(drop=True))

top_pos = coef_df.head(10)
top_neg = coef_df.sort_values('coefficient').head(10)
coef_plot = pd.concat([top_pos, top_neg]).sort_values('coefficient')

fig, ax = plt.subplots(figsize=(9, 7))
colors = ['#d7191c' if c < 0 else '#2b83ba' for c in coef_plot['coefficient']]
ax.barh(coef_plot['feature'], coef_plot['coefficient'], color=colors)
ax.set_xlabel("Coefficient Value")
ax.set_title("Q7 — Top Positive and Negative L1 Coefficients")
ax.axvline(x=0, color='black', linewidth=0.8)
plt.tight_layout()
plt.show()

fig, ax = plt.subplots(figsize=(7, 5))
ax.scatter(month_table['subscribe_rate'], month_table['avg_pred_prob'], s=80)
for idx, row in month_table.iterrows():
    ax.annotate(idx, (row['subscribe_rate'], row['avg_pred_prob']),
                textcoords='offset points', xytext=(6, 4), fontsize=9)
ax.set_xlabel("Observed Subscription Rate")
ax.set_ylabel("Average Predicted Probability (L1 Model)")
ax.set_title("Q7 — Observed vs Predicted Subscription Rate by Month")
ax.plot([0, 0.55], [0, 0.55], 'k--', alpha=0.3, label='perfect calibration')
ax.legend()
plt.tight_layout()
plt.show()

print("\n--- My Findings ---")
print()
print("Based on the convergence of observed subscription rates, model-predicted")
print("probabilities, and logistic regression coefficients, I identified the following")
print("client groups as most likely to subscribe to a term deposit:")
print()
print("  1. Clients whose previous campaign outcome was 'success' — by far the")
print("     strongest predictor, with a very high observed subscription rate and the")
print("     highest average predicted probability.")
print()
print("  2. Clients contacted in March, September, October, or December — these")
print("     months stay strong in both observed rates and model outputs.")
print()
print("  3. Students and retired individuals — both groups show above-average")
print("     subscription rates and positive signals in the L1 model.")
print()
print("  4. Clients contacted via cellular phone rather than landline telephone —")
print("     the telephone indicator remains strongly negative, which supports")
print("     prioritising cellular contact when possible.")
print()
print("  5. Some macroeconomic variables still matter, but I interpret those numeric")
print("     coefficients on the standardised scale. So a larger-magnitude coefficient")
print("     reflects a stronger one-standard-deviation effect, not a literal one-unit")
print("     raw-data change.")

def subgroup_rates(df_, group_cols, min_count=50):
    t = (df_.groupby(group_cols)
         .agg(subscribe_rate=('y_num', 'mean'),
              avg_pred_prob=('pred_prob', 'mean'),
              count=('y_num', 'count'))
         .reset_index())
    return (t[t['count'] >= min_count]
            .sort_values('subscribe_rate', ascending=False)
            .round(4))

print("\n=== Top combinations of poutcome × contact (n ≥ 50) ===\n")
display(subgroup_rates(df_model, ['poutcome', 'contact']).head(10).reset_index(drop=True))

print("\n=== Top combinations of poutcome × job (n ≥ 50) ===\n")
display(subgroup_rates(df_model, ['poutcome', 'job']).head(10).reset_index(drop=True))

print("\n=== Top combinations of contact × month (n ≥ 50) ===\n")
display(subgroup_rates(df_model, ['contact', 'month']).head(10).reset_index(drop=True))

print("\nThe combined-profile view confirms the single-feature findings:")
print("clients with poutcome='success' contacted via cellular consistently show")
print("the highest subscription rates, while retired/student clients in the")
print("same profile segments remain substantially above the ~11% base rate.")

df_model.drop(columns=['pred_prob'], inplace=True)
=== Top 15 Subgroups by Observed Subscription Rate ===

feature value subscribe_rate count
0 poutcome success 0.6511 1373
1 month mar 0.5055 546
2 month dec 0.4890 182
3 month sep 0.4491 570
4 month oct 0.4387 718
5 job student 0.3143 875
6 job retired 0.2523 1720
7 education illiterate 0.2222 18
8 month apr 0.2048 2632
9 marital unknown 0.1500 80
10 contact cellular 0.1474 26144
11 education unknown 0.1450 1731
12 poutcome failure 0.1423 4252
13 job unemployed 0.1420 1014
14 marital single 0.1400 11568
No description has been provided for this image
=== Subscription Rate & Predicted Probability by Job ===

subscribe_rate avg_pred_prob count
job
student 0.3143 0.6643 875
retired 0.2523 0.5896 1720
unemployed 0.1420 0.4244 1014
admin. 0.1297 0.4198 10422
management 0.1122 0.4030 2924
unknown 0.1121 0.3784 330
technician 0.1083 0.3851 6743
self-employed 0.1049 0.3905 1421
housemaid 0.1000 0.3581 1060
entrepreneur 0.0852 0.3648 1456
services 0.0814 0.3449 3969
blue-collar 0.0689 0.3256 9254
=== Subscription Rate & Predicted Probability by Month ===

subscribe_rate avg_pred_prob count
month
mar 0.5055 0.8610 546
dec 0.4890 0.8222 182
sep 0.4491 0.8451 570
oct 0.4387 0.8446 718
apr 0.2048 0.6338 2632
aug 0.1060 0.3861 6178
jun 0.1051 0.3706 5318
nov 0.1014 0.3808 4101
jul 0.0905 0.3699 7174
may 0.0643 0.3051 13769
=== Subscription Rate & Predicted Probability by Contact Method ===

subscribe_rate avg_pred_prob count
contact
cellular 0.1474 0.4661 26144
telephone 0.0523 0.2634 15044
=== Subscription Rate & Predicted Probability by Previous Outcome ===

subscribe_rate avg_pred_prob count
poutcome
success 0.6511 0.9176 1373
failure 0.1423 0.4768 4252
nonexistent 0.0883 0.3616 35563
=== Top 15 Positive Coefficients (increase subscription likelihood) ===

feature coefficient
0 month_mar 1.0680
1 cons.price.idx 0.7546
2 euribor3m 0.4064
3 job_retired 0.3445
4 was_contacted_before 0.2908
5 month_aug 0.2722
6 job_student 0.1561
7 education_basic.6y 0.1181
8 day_of_week_wed 0.1062
9 month_dec 0.1012
10 marital_single 0.0880
11 cons.conf.idx 0.0826
12 education_university.degree 0.0774
13 default_no 0.0769
14 housing_no 0.0520
=== Top 15 Negative Coefficients (decrease subscription likelihood) ===

feature coefficient
0 emp.var.rate -1.6410
1 month_may -0.6775
2 contact_telephone -0.5530
3 month_nov -0.5383
4 month_jun -0.4746
5 poutcome_failure -0.3052
6 month_apr -0.1488
7 day_of_week_mon -0.1231
8 campaign -0.1141
9 default_unknown -0.1050
10 job_services -0.0803
11 previous -0.0742
12 job_blue-collar -0.0742
13 marital_divorced -0.0544
14 education_basic.4y -0.0379
No description has been provided for this image
No description has been provided for this image
--- My Findings ---

Based on the convergence of observed subscription rates, model-predicted
probabilities, and logistic regression coefficients, I identified the following
client groups as most likely to subscribe to a term deposit:

  1. Clients whose previous campaign outcome was 'success' — by far the
     strongest predictor, with a very high observed subscription rate and the
     highest average predicted probability.

  2. Clients contacted in March, September, October, or December — these
     months stay strong in both observed rates and model outputs.

  3. Students and retired individuals — both groups show above-average
     subscription rates and positive signals in the L1 model.

  4. Clients contacted via cellular phone rather than landline telephone —
     the telephone indicator remains strongly negative, which supports
     prioritising cellular contact when possible.

  5. Some macroeconomic variables still matter, but I interpret those numeric
     coefficients on the standardised scale. So a larger-magnitude coefficient
     reflects a stronger one-standard-deviation effect, not a literal one-unit
     raw-data change.

=== Top combinations of poutcome × contact (n ≥ 50) ===

poutcome contact subscribe_rate avg_pred_prob count
0 success cellular 0.6520 0.9198 1270
1 success telephone 0.6408 0.8914 103
2 failure cellular 0.1445 0.4815 3952
3 nonexistent cellular 0.1173 0.4357 20922
4 failure telephone 0.1133 0.4148 300
5 nonexistent telephone 0.0469 0.2559 14641
=== Top combinations of poutcome × job (n ≥ 50) ===

poutcome job subscribe_rate avg_pred_prob count
0 success retired 0.7405 0.9554 158
1 success student 0.7119 0.9489 118
2 success management 0.6947 0.9066 95
3 success admin. 0.6682 0.9244 428
4 success unemployed 0.6613 0.9091 62
5 success technician 0.6588 0.9197 211
6 success services 0.6000 0.8914 70
7 success blue-collar 0.4958 0.8519 119
8 failure retired 0.2739 0.7059 230
9 failure student 0.2638 0.7035 163
=== Top combinations of contact × month (n ≥ 50) ===

contact month subscribe_rate avg_pred_prob count
0 cellular dec 0.5235 0.8630 149
1 cellular mar 0.5185 0.8661 486
2 cellular sep 0.4938 0.8599 482
3 cellular oct 0.4494 0.8818 563
4 cellular jun 0.4256 0.8168 820
5 telephone oct 0.4000 0.7095 155
6 telephone mar 0.4000 0.8198 60
7 telephone apr 0.2460 0.5426 187
8 telephone sep 0.2045 0.7643 88
9 cellular apr 0.2016 0.6408 2445
The combined-profile view confirms the single-feature findings:
clients with poutcome='success' contacted via cellular consistently show
the highest subscription rates, while retired/student clients in the
same profile segments remain substantially above the ~11% base rate.

Synthesising the client-targeting findings¶

The strongest likely-subscriber groups are consistent across observed rates and model outputs. High-priority profiles include clients with successful prior outcomes (poutcome='success'), stronger channel performance (cellular), and selected month/job segments with above-average conversion.

For the coefficient view, I keep in mind that the numeric coefficients are expressed on the standardised scale, so I use them mainly to judge relative importance rather than raw-unit effects.

For campaign action, I would prioritise these high-propensity groups first, then adjust threshold based on call-center capacity and conversion goals.

Conclusion¶

Main outcomes:

  • Regularised logistic regression is more suitable than the baseline and KNN for this imbalanced marketing problem.
  • Threshold tuning matters, and the recommended threshold is now selected from the exact list required by the task.
  • Client targeting can be improved by prioritising segments with strong historical and predicted subscription propensity.

If I deploy one model from this notebook, I would use the selected regularised logistic model with the chosen threshold from Q5.