This is Module 6, the last module of the Data Analyst to Data Scientist path. Modules 4 and 5 were about measuring what happened. This one is about predicting what will happen, and, more importantly, deciding what to do with a prediction. A model is only as good as the decisions it improves.

You’ll build: a regression and a classifier, each compared with a baseline, and a cost calculation that chooses when to act on the classifier’s predictions.

You need: Python with scikit-learn (pip install scikit-learn). Both datasets are generated or included, so the numbers below should match yours.

1. Predicting a number: regression

The diabetes dataset that ships with scikit-learn records ten measurements for 442 patients and “a quantitative measure of disease progression one year after baseline.” Save this as regression.py:

# Regression: predict a number, and judge it against the simplest possible guess.
from sklearn.datasets import load_diabetes
from sklearn.dummy import DummyRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split

X, y = load_diabetes(return_X_y=True)          # 442 patients; target: disease progression one year later
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

for name, model in [("baseline (always the mean)", DummyRegressor()), ("linear regression", LinearRegression())]:
    pred = model.fit(X_train, y_train).predict(X_test)
    print(f"{name:28} MAE {mean_absolute_error(y_test, pred):5.1f}   R² {r2_score(y_test, pred):5.2f}")
baseline (always the mean)   MAE  58.3   R² -0.00
linear regression            MAE  45.1   R²  0.36

Read it in that order: the baseline guesses the average every time and is off by 58.3 points on average (mean absolute error, MAE). The model is off by 45.1. That’s a real improvement, but R² of 0.36 says most of the variation is still unexplained. Report both: MAE in the unit people understand, and the baseline beside it so nobody quotes 45.1 without context.

2. Predicting yes or no, and what each error costs

For a yes-or-no prediction, like “will this customer cancel?”, the model gives a probability, and something has to turn it into an action. scikit-learn’s default predicts “yes” when the probability is greater than 0.5, as its documentation explains. That number is a convention, not a decision about your business.

Suppose a retention offer costs 20, a customer who leaves unnoticed costs 200 in lost margin, and an offer keeps half of the churners it reaches. (These are assumptions for the example; use your own.) Save this as costs.py:

# Classification: choose the decision threshold from what each kind of error costs.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(3)
n = 4_000
tickets, tenure = rng.poisson(1.5, n), rng.integers(1, 60, n)
churn = (rng.random(n) < 1 / (1 + np.exp(-(-1.2 + 0.5 * tickets - 0.05 * tenure)))).astype(int)
X = np.column_stack([tickets, tenure])
X_train, X_test, y_train, y_test = train_test_split(X, churn, test_size=0.5, stratify=churn, random_state=0)
p = LogisticRegression().fit(X_train, y_train).predict_proba(X_test)[:, 1]

OFFER, LOST = 20, 200        # a retention offer costs 20; a customer who leaves unnoticed costs 200 in margin
def cost(threshold):
    tn, fp, fn, tp = confusion_matrix(y_test, (p >= threshold).astype(int)).ravel()
    # Offers go to everyone flagged; assume an offer keeps half of the true churners it reaches.
    return fp * OFFER + tp * (OFFER + 0.5 * LOST) + fn * LOST, tp, fp, fn

print(f"test customers {len(y_test)}, churners {y_test.sum()}")
for t in (0.5, 0.3, 0.2, 0.1):
    c, tp, fp, fn = cost(t)
    print(f"threshold {t:.1f}: flagged {tp + fp:4}, churners caught {tp:3}, missed {fn:3}, total cost {c:7,.0f}")
best = min(np.arange(0.02, 0.9, 0.01), key=lambda t: cost(t)[0])
print(f"lowest-cost threshold: {best:.2f} (cost {cost(best)[0]:,.0f}); doing nothing costs {y_test.sum() * LOST:,}")
test customers 2000, churners 334
threshold 0.5: flagged   75, churners caught  39, missed 295, total cost  64,400
threshold 0.3: flagged  354, churners caught 132, missed 202, total cost  60,680
threshold 0.2: flagged  674, churners caught 206, missed 128, total cost  59,680
threshold 0.1: flagged 1171, churners caught 286, missed  48, total cost  61,620
lowest-cost threshold: 0.21 (cost 59,360); doing nothing costs 66,800

At the default 0.5, the model flags only 75 customers and misses 295 of 334 churners: it saves 2,400 against doing nothing. At 0.21, it flags many more people, accepts more wasted offers, and saves 7,440. Because a missed churner costs ten times an offer, it pays to act on weaker signals. Go too low, at 0.1, and the wasted offers start to cost more than they save.

To check the arithmetic at 0.5: 36 wasted offers × 20 + 39 caught churners × (20 + 100 expected loss) + 295 missed × 200 = 64,400.

3. Choosing a metric that matches the decision

If the decision is… Report Why
A number people will plan with MAE, with the baseline’s MAE In the unit people use
Act or don’t act, with known costs Expected cost at the chosen threshold It is the business outcome
Act or don’t act, rare positives Precision and recall at the threshold Accuracy hides rare cases
Rank customers for a team with fixed capacity Share of positives in the top N Matches how the list will be used

Whatever you report, keep the test set untouched until the end, and choose the threshold on the training data or a separate validation set when you have the data; this example uses one held-out half to keep the code short.

Project: finish the path

Take a yes-or-no question from your own work. Build a model, compare it with a baseline on held-out data, write down what each kind of error costs, and choose the threshold that minimises cost. Present it on one page: the question, the baseline, the model, the threshold, the expected saving, and the assumptions it depends on. That page, with the projects from Modules 1 to 5, is a data science portfolio.