TExcelTAD
Home › Machine Learning › ML Mini Project

ML Mini Project

In this project you'll build a complete customer churn predictor for an imaginary mobile and internet provider, from raw data to a saved model that scores new customers. "Churn" means a customer cancels their contract. If the company can predict who is likely to leave, it can offer them a better deal before they go.

The project uses almost everything from the course: exploring data, a train/test split, a baseline, ColumnTransformer pipelines, model comparison with cross validation, grid search, ROC AUC, threshold choice, permutation importance and model persistence.

Real customer data is private, so we simulate 1 500 customers with a small, seeded function. Each step below is a complete program that starts by generating the same data set; in a real project you would load a CSV once instead.

Column Meaning
tenure_months how long the customer has been with the company
monthly_charges current monthly bill (30 values are missing)
support_calls calls to customer support in the last quarter
contract monthly, one_year or two_year
internet dsl, fiber or none
churn 1 if the customer left (the target)

Step 1: Generate and explore the data

The generator gives churn a realistic structure: monthly contracts, many support calls, high bills and short tenure make leaving more likely. Of course, in a real project you wouldn't know these rules — finding them is the point.

python · try it yourself
import numpy as np
import pandas as pd

def make_customers(n=1500, seed=7):
    rng = np.random.default_rng(seed)
    contract = rng.choice(["monthly", "one_year", "two_year"], n, p=[0.55, 0.25, 0.20])
    internet = rng.choice(["dsl", "fiber", "none"], n, p=[0.40, 0.45, 0.15])
    tenure = rng.integers(1, 73, n)
    charges = (35 + 30 * (internet == "fiber") + 15 * (internet == "dsl") + rng.normal(0, 8, n)).round(2)
    calls = rng.poisson(1.5, n)
    logit = (-1.2 + 1.5 * (contract == "monthly") - 1.0 * (contract == "two_year")
             - 0.03 * tenure + 0.02 * (charges - 60) + 0.45 * calls + 0.4 * (internet == "fiber"))
    churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure_months": tenure, "monthly_charges": charges, "support_calls": calls,
                       "contract": contract, "internet": internet, "churn": churn})
    df.loc[rng.choice(n, 30, replace=False), "monthly_charges"] = np.nan
    return df

customers = make_customers()
print(customers.head())
print("shape:", customers.shape, " churn rate:", round(customers["churn"].mean(), 3))
print("missing:", customers.isna().sum()[customers.isna().sum() > 0].to_dict())
print()
print(customers.groupby("contract")["churn"].mean().round(3))
print()
print(customers.groupby("churn")[["tenure_months", "monthly_charges", "support_calls"]].mean().round(2))
   tenure_months  monthly_charges  support_calls  contract internet  churn
0             45            52.38              1  one_year    fiber      0
1             15            69.02              1  two_year    fiber      0
2             23            57.41              2  one_year      dsl      0
3             59            66.77              1   monthly      dsl      0
4             10            63.79              1   monthly      dsl      0
shape: (1500, 6)  churn rate: 0.332
missing: {'monthly_charges': 30}

contract
monthly     0.469
one_year    0.242
two_year    0.064
Name: churn, dtype: float64

       tenure_months  monthly_charges  support_calls
churn
0              39.50            52.98           1.36
1              30.06            56.97           1.91

About a third of customers churned. The grouped tables already tell a story: monthly-contract customers leave far more often than two-year customers, and churners have shorter tenure, higher bills and more support calls.

Step 2: Split and set a baseline

We hold out 25 % of the customers as a test set before any modelling decision, stratified so both parts have the same churn rate. Because churners are the minority, we'll measure models with ROC AUC rather than accuracy. A DummyClassifier shows what "no skill" looks like:

python · try it yourself
import numpy as np
import pandas as pd

def make_customers(n=1500, seed=7):
    rng = np.random.default_rng(seed)
    contract = rng.choice(["monthly", "one_year", "two_year"], n, p=[0.55, 0.25, 0.20])
    internet = rng.choice(["dsl", "fiber", "none"], n, p=[0.40, 0.45, 0.15])
    tenure = rng.integers(1, 73, n)
    charges = (35 + 30 * (internet == "fiber") + 15 * (internet == "dsl") + rng.normal(0, 8, n)).round(2)
    calls = rng.poisson(1.5, n)
    logit = (-1.2 + 1.5 * (contract == "monthly") - 1.0 * (contract == "two_year")
             - 0.03 * tenure + 0.02 * (charges - 60) + 0.45 * calls + 0.4 * (internet == "fiber"))
    churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure_months": tenure, "monthly_charges": charges, "support_calls": calls,
                       "contract": contract, "internet": internet, "churn": churn})
    df.loc[rng.choice(n, 30, replace=False), "monthly_charges"] = np.nan
    return df

from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.dummy import DummyClassifier

customers = make_customers()
X = customers.drop(columns="churn")
y = customers["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
print("train:", X_train.shape, " test:", X_test.shape)
print("churn rate train/test:", round(y_train.mean(), 3), round(y_test.mean(), 3))

dummy = DummyClassifier(strategy="most_frequent")
print("baseline accuracy:", cross_val_score(dummy, X_train, y_train, cv=5).mean().round(3))
print("baseline ROC AUC: ", cross_val_score(dummy, X_train, y_train, cv=5, scoring="roc_auc").mean().round(3))
train: (1125, 5)  test: (375, 5)
churn rate train/test: 0.332 0.331
baseline accuracy: 0.668
baseline ROC AUC:  0.5

The baseline is about 67 % "accurate" by always predicting "stays" — which is exactly why accuracy is a poor guide here. Its AUC of 0.5 is the bar to beat.

Step 3: A preprocessing pipeline

The data mixes numbers (one with gaps) and text categories. A ColumnTransformer imputes and scales the numeric columns and one-hot encodes the categorical ones. Wrapped in a pipeline with a logistic regression, raw DataFrames go straight in:

python · try it yourself
import numpy as np
import pandas as pd

def make_customers(n=1500, seed=7):
    rng = np.random.default_rng(seed)
    contract = rng.choice(["monthly", "one_year", "two_year"], n, p=[0.55, 0.25, 0.20])
    internet = rng.choice(["dsl", "fiber", "none"], n, p=[0.40, 0.45, 0.15])
    tenure = rng.integers(1, 73, n)
    charges = (35 + 30 * (internet == "fiber") + 15 * (internet == "dsl") + rng.normal(0, 8, n)).round(2)
    calls = rng.poisson(1.5, n)
    logit = (-1.2 + 1.5 * (contract == "monthly") - 1.0 * (contract == "two_year")
             - 0.03 * tenure + 0.02 * (charges - 60) + 0.45 * calls + 0.4 * (internet == "fiber"))
    churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure_months": tenure, "monthly_charges": charges, "support_calls": calls,
                       "contract": contract, "internet": internet, "churn": churn})
    df.loc[rng.choice(n, 30, replace=False), "monthly_charges"] = np.nan
    return df

from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression

customers = make_customers()
X = customers.drop(columns="churn")
y = customers["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

numeric = ["tenure_months", "monthly_charges", "support_calls"]
categorical = ["contract", "internet"]
preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])

model = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X_train, y_train, cv=5, scoring="roc_auc")
print("CV ROC AUC per fold:", scores.round(3))
print("mean:", scores.mean().round(3))

model.fit(X_train, y_train)
print("features the model sees:", len(model[0].get_feature_names_out()))
CV ROC AUC per fold: [0.833 0.799 0.756 0.79  0.774]
mean: 0.79
features the model sees: 9

A clear improvement over the baseline. The 5 input columns became 9 model features (3 numeric + 6 one-hot).

Step 4: Compare models

Is a more powerful model better? We compare logistic regression with a random forest and gradient boosting, all with the same preprocessing and the same cross validation:

python · try it yourself
import numpy as np
import pandas as pd

def make_customers(n=1500, seed=7):
    rng = np.random.default_rng(seed)
    contract = rng.choice(["monthly", "one_year", "two_year"], n, p=[0.55, 0.25, 0.20])
    internet = rng.choice(["dsl", "fiber", "none"], n, p=[0.40, 0.45, 0.15])
    tenure = rng.integers(1, 73, n)
    charges = (35 + 30 * (internet == "fiber") + 15 * (internet == "dsl") + rng.normal(0, 8, n)).round(2)
    calls = rng.poisson(1.5, n)
    logit = (-1.2 + 1.5 * (contract == "monthly") - 1.0 * (contract == "two_year")
             - 0.03 * tenure + 0.02 * (charges - 60) + 0.45 * calls + 0.4 * (internet == "fiber"))
    churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure_months": tenure, "monthly_charges": charges, "support_calls": calls,
                       "contract": contract, "internet": internet, "churn": churn})
    df.loc[rng.choice(n, 30, replace=False), "monthly_charges"] = np.nan
    return df

from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier

customers = make_customers()
X = customers.drop(columns="churn")
y = customers["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

numeric = ["tenure_months", "monthly_charges", "support_calls"]
categorical = ["contract", "internet"]
preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])

candidates = {
    "logistic regression": LogisticRegression(max_iter=1000),
    "random forest": RandomForestClassifier(n_estimators=100, min_samples_leaf=5, random_state=0),
    "gradient boosting": HistGradientBoostingClassifier(max_iter=100, learning_rate=0.05, random_state=0),
}
for name, clf in candidates.items():
    auc = cross_val_score(make_pipeline(preprocess, clf), X_train, y_train, cv=5, scoring="roc_auc").mean()
    print(f"{name:20} CV ROC AUC = {auc:.3f}")
logistic regression  CV ROC AUC = 0.790
random forest        CV ROC AUC = 0.765
gradient boosting    CV ROC AUC = 0.741

The simple logistic regression wins. That's not unusual: when the true relationship is roughly linear in the features (as in our simulation) and the data set is small, flexible models mostly add variance. It's also the easiest model to explain to the business — a bonus.

Step 5: Tune and evaluate on the test set

We tune the regularization strength C with a grid search on the training data, then evaluate the winner once on the untouched test set:

python · try it yourself
import numpy as np
import pandas as pd

def make_customers(n=1500, seed=7):
    rng = np.random.default_rng(seed)
    contract = rng.choice(["monthly", "one_year", "two_year"], n, p=[0.55, 0.25, 0.20])
    internet = rng.choice(["dsl", "fiber", "none"], n, p=[0.40, 0.45, 0.15])
    tenure = rng.integers(1, 73, n)
    charges = (35 + 30 * (internet == "fiber") + 15 * (internet == "dsl") + rng.normal(0, 8, n)).round(2)
    calls = rng.poisson(1.5, n)
    logit = (-1.2 + 1.5 * (contract == "monthly") - 1.0 * (contract == "two_year")
             - 0.03 * tenure + 0.02 * (charges - 60) + 0.45 * calls + 0.4 * (internet == "fiber"))
    churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure_months": tenure, "monthly_charges": charges, "support_calls": calls,
                       "contract": contract, "internet": internet, "churn": churn})
    df.loc[rng.choice(n, 30, replace=False), "monthly_charges"] = np.nan
    return df

from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report

customers = make_customers()
X = customers.drop(columns="churn")
y = customers["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

numeric = ["tenure_months", "monthly_charges", "support_calls"]
categorical = ["contract", "internet"]
preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])

pipe = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
search = GridSearchCV(pipe, {"logisticregression__C": [0.01, 0.1, 1, 10]}, cv=5, scoring="roc_auc")
search.fit(X_train, y_train)
print("best C:", search.best_params_["logisticregression__C"], " CV AUC:", round(search.best_score_, 3))

proba = search.predict_proba(X_test)[:, 1]
print("test ROC AUC:", round(roc_auc_score(y_test, proba), 3))
print(classification_report(y_test, search.predict(X_test), target_names=["stays", "churns"]))
best C: 10  CV AUC: 0.79
test ROC AUC: 0.802
              precision    recall  f1-score   support

       stays       0.77      0.84      0.81       251
      churns       0.61      0.49      0.54       124

    accuracy                           0.73       375
   macro avg       0.69      0.67      0.68       375
weighted avg       0.72      0.73      0.72       375

The test AUC is close to the cross-validation estimate, so the model generalises as expected. But look at the churn row of the report: with the default 0.5 threshold, recall for churners is low — many leavers would be missed.

Step 6: Choose a business threshold

Suppose the retention team can call customers and offer a discount. Missing a churner costs much more than calling a customer who would have stayed anyway. So we lower the threshold. We plot the ROC curve and compare a few thresholds on the test set:

python · try it yourself
import numpy as np
import pandas as pd

def make_customers(n=1500, seed=7):
    rng = np.random.default_rng(seed)
    contract = rng.choice(["monthly", "one_year", "two_year"], n, p=[0.55, 0.25, 0.20])
    internet = rng.choice(["dsl", "fiber", "none"], n, p=[0.40, 0.45, 0.15])
    tenure = rng.integers(1, 73, n)
    charges = (35 + 30 * (internet == "fiber") + 15 * (internet == "dsl") + rng.normal(0, 8, n)).round(2)
    calls = rng.poisson(1.5, n)
    logit = (-1.2 + 1.5 * (contract == "monthly") - 1.0 * (contract == "two_year")
             - 0.03 * tenure + 0.02 * (charges - 60) + 0.45 * calls + 0.4 * (internet == "fiber"))
    churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure_months": tenure, "monthly_charges": charges, "support_calls": calls,
                       "contract": contract, "internet": internet, "churn": churn})
    df.loc[rng.choice(n, 30, replace=False), "monthly_charges"] = np.nan
    return df

from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, precision_score, recall_score

customers = make_customers()
X = customers.drop(columns="churn")
y = customers["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

numeric = ["tenure_months", "monthly_charges", "support_calls"]
categorical = ["contract", "internet"]
preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])

model = make_pipeline(preprocess, LogisticRegression(C=10, max_iter=1000)).fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]

fpr, tpr, _ = roc_curve(y_test, proba)
plt.plot(fpr, tpr, label="logistic regression")
plt.plot([0, 1], [0, 1], "k--", label="random guess")
plt.xlabel("False positive rate")
plt.ylabel("True positive rate")
plt.legend()
plt.show()

print("threshold  customers called  precision  recall")
for t in [0.5, 0.4, 0.3, 0.2]:
    pred = (proba >= t).astype(int)
    print(f"{t:9}  {pred.sum():16}  {precision_score(y_test, pred):9.3f}  {recall_score(y_test, pred):6.3f}")
threshold  customers called  precision  recall
      0.5               100      0.610   0.492
      0.4               142      0.613   0.702
      0.3               191      0.529   0.815
      0.2               251      0.466   0.944

With a threshold of 0.3 the team calls more customers but catches far more of the real churners. Which row is "best" is a business decision (cost of a call vs. value of a saved customer), and the table gives the numbers to make it. In a stricter workflow you'd pick the threshold on a validation split rather than the test set.

Step 7: Explain the model

What drives churn? Permutation importance measures how much the test AUC drops when one column is shuffled, and the logistic coefficients show the direction of each effect:

python · try it yourself
import numpy as np
import pandas as pd

def make_customers(n=1500, seed=7):
    rng = np.random.default_rng(seed)
    contract = rng.choice(["monthly", "one_year", "two_year"], n, p=[0.55, 0.25, 0.20])
    internet = rng.choice(["dsl", "fiber", "none"], n, p=[0.40, 0.45, 0.15])
    tenure = rng.integers(1, 73, n)
    charges = (35 + 30 * (internet == "fiber") + 15 * (internet == "dsl") + rng.normal(0, 8, n)).round(2)
    calls = rng.poisson(1.5, n)
    logit = (-1.2 + 1.5 * (contract == "monthly") - 1.0 * (contract == "two_year")
             - 0.03 * tenure + 0.02 * (charges - 60) + 0.45 * calls + 0.4 * (internet == "fiber"))
    churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure_months": tenure, "monthly_charges": charges, "support_calls": calls,
                       "contract": contract, "internet": internet, "churn": churn})
    df.loc[rng.choice(n, 30, replace=False), "monthly_charges"] = np.nan
    return df

from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.inspection import permutation_importance

customers = make_customers()
X = customers.drop(columns="churn")
y = customers["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

numeric = ["tenure_months", "monthly_charges", "support_calls"]
categorical = ["contract", "internet"]
preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])

model = make_pipeline(preprocess, LogisticRegression(C=10, max_iter=1000)).fit(X_train, y_train)

result = permutation_importance(model, X_test, y_test, scoring="roc_auc", n_repeats=10, random_state=0)
print("permutation importance (drop in AUC):")
for i in result.importances_mean.argsort()[::-1]:
    print(f"  {X.columns[i]:16} {result.importances_mean[i]:.3f}")

print("logistic coefficients:")
names = model[0].get_feature_names_out()
for name, coef in sorted(zip(names, model[-1].coef_[0]), key=lambda p: p[1]):
    print(f"  {name:26} {coef:+.2f}")
permutation importance (drop in AUC):
  contract         0.159
  tenure_months    0.066
  support_calls    0.058
  monthly_charges  0.011
  internet         0.008
logistic coefficients:
  cat__contract_two_year     -1.81
  num__tenure_months         -0.57
  cat__internet_none         -0.48
  cat__internet_dsl          -0.39
  cat__contract_one_year     -0.12
  cat__internet_fiber        -0.03
  num__monthly_charges       +0.19
  num__support_calls         +0.57
  cat__contract_monthly      +1.03

The contract type matters most, followed by tenure and support calls. Positive coefficients increase the churn probability (monthly contract, support calls, higher bills), negative ones decrease it (long tenure, two-year contracts). Among the internet options, fibre has the least negative coefficient, so fibre customers are the most likely to leave. These match the rules hidden in the generator — the model has recovered them from data alone.

Step 8: Save the model and score new customers

Finally, we save the fitted pipeline (to an in-memory file here; open("churn.pkl", "wb") in a real project), load it back as a deployment script would, and score three new customers — one with a missing bill:

python · try it yourself
import numpy as np
import pandas as pd

def make_customers(n=1500, seed=7):
    rng = np.random.default_rng(seed)
    contract = rng.choice(["monthly", "one_year", "two_year"], n, p=[0.55, 0.25, 0.20])
    internet = rng.choice(["dsl", "fiber", "none"], n, p=[0.40, 0.45, 0.15])
    tenure = rng.integers(1, 73, n)
    charges = (35 + 30 * (internet == "fiber") + 15 * (internet == "dsl") + rng.normal(0, 8, n)).round(2)
    calls = rng.poisson(1.5, n)
    logit = (-1.2 + 1.5 * (contract == "monthly") - 1.0 * (contract == "two_year")
             - 0.03 * tenure + 0.02 * (charges - 60) + 0.45 * calls + 0.4 * (internet == "fiber"))
    churn = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
    df = pd.DataFrame({"tenure_months": tenure, "monthly_charges": charges, "support_calls": calls,
                       "contract": contract, "internet": internet, "churn": churn})
    df.loc[rng.choice(n, 30, replace=False), "monthly_charges"] = np.nan
    return df

import io
import pickle
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression

customers = make_customers()
X = customers.drop(columns="churn")
y = customers["churn"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)

numeric = ["tenure_months", "monthly_charges", "support_calls"]
categorical = ["contract", "internet"]
preprocess = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])

model = make_pipeline(preprocess, LogisticRegression(C=10, max_iter=1000)).fit(X_train, y_train)
buffer = io.BytesIO()
pickle.dump({"model": model, "threshold": 0.3}, buffer)
buffer.seek(0)

saved = pickle.load(buffer)
new_customers = pd.DataFrame({
    "tenure_months":   [3, 48, 14],
    "monthly_charges": [82.5, 41.0, np.nan],
    "support_calls":   [4, 0, 2],
    "contract":        ["monthly", "two_year", "one_year"],
    "internet":        ["fiber", "dsl", "fiber"],
})
proba = saved["model"].predict_proba(new_customers)[:, 1]
new_customers["churn_risk"] = proba.round(3)
new_customers["call_them"] = proba >= saved["threshold"]
print(new_customers.to_string())
   tenure_months  monthly_charges  support_calls  contract internet  churn_risk  call_them
0              3             82.5              4   monthly    fiber       0.924       True
1             48             41.0              0  two_year      dsl       0.013      False
2             14              NaN              2  one_year    fiber       0.442       True

The new short-tenure fibre customer on a monthly contract with four support calls is a clear call; the loyal two-year DSL customer is not.

Ideas to extend the project

  • Add a feature such as charges_per_tenure_month or calls_per_year and check whether the CV AUC improves.
  • Try class_weight="balanced" and compare precision/recall at the default threshold.
  • Replace the simulated data with a public churn data set on your own computer (pd.read_csv("churn.csv")) — every step works unchanged once the column lists match.
  • Compute recall separately for each internet type: does the model serve every customer segment equally well?

Test yourself

Why did the project use ROC AUC instead of accuracy to compare models?

  1. AUC is faster to compute
  2. Churners are the minority, so accuracy rewards predicting 'stays' for everyone
  3. Accuracy can't be cross-validated
  4. AUC works only for logistic regression

Why was the decision threshold lowered from 0.5 to around 0.3?

  1. To increase precision
  2. Because missing a churner costs more than an unnecessary call, so higher recall is worth it
  3. Because scikit-learn requires it
  4. To make the model train faster

Why is the whole pipeline saved instead of only the logistic regression?

  1. Pickle can't save single models
  2. New customers need exactly the same imputing, scaling and encoding as the training data
  3. It makes the file smaller
  4. To hide the coefficients