Session 10 · Classification: bad days

Session 10: Classification

Will today be a bad day for Apple? Four ways to answer a yes-or-no question from data, and how to tell which answer to trust.

Data Science and Advanced Programming · UNIL · 2026

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Where session 9 left us

1 · modela line:
ŷ = a + b x
→
2 · lossmean squared error,
from a likelihood
→
3 · minimisea formula, or
gradient descent
→
4 · teston days the model
has not seen

Session 9 used this recipe for regression: was a number, Apple's return. Along the way you met everything today needs: train and test sets, overfitting, bias and variance, the likelihood, gradient descent, one-hot columns.

Today is a category: yes or no. The recipe stays; each step changes a little.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

A question with a yes-or-no answer

ticker shares price value
AAPL 10 190.50 1905.00
NESN 4 102.30 409.20
VOO 2 512.00 1024.00

Apple is more than half of the ledger. A risk manager does not need tomorrow's exact return. They need to know: is today a bad day for Apple, a fall of more than 2 %?

On the ledger's 1905.00 in Apple, a bad day costs more than 38. Predicting a category from data is classification, the second kind of supervised learning.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Today

  1. The question as data
  2. k-nearest neighbours
  3. Logistic regression
  4. Judging a classifier
  5. Decision trees
  6. Many trees
  7. Four classifiers, one test year

Four methods, each with its own idea: look at similar days, fit a probability curve, ask yes-or-no questions, let many models vote. All four are judged the same way, on the same test year.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
history.csv

The data: five years

history.csv: daily prices of the four ledger positions, 2022-01-17 to 2026-10-30.

  • The last year is session 9's prices.csv, unchanged.
  • The four years before it are simulated the same way, with another seed (make_history.py).

Why more days? Bad days are rare: about one in ten. To learn what precedes them and to judge a classifier honestly, one year is too little. We train on the four years and test on the year you already know.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
classify.py
1import pandas as pd
2from sklearn.linear_model import LogisticRegression
3from sklearn.metrics import confusion_matrix
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7
8X = returns[["VOO", "MSFT"]] # the same day
9y = (returns["AAPL"] < -2).astype(int) # 1 = a bad day
10
11train = returns.index < "2025-11-17" # four years
12test = ~train # session 9's year
13
14model = LogisticRegression().fit(X[train], y[train])
15p = model.predict_proba(X[test])[:, 1] # P(bad day)
16alarm = p > 0.2
17
18print("test year:", test.sum(), "days,", y[test].sum(), "bad")
19print(confusion_matrix(y[test], alarm))
20hits = (alarm & (y[test] == 1)).sum()
21print("caught:", hits, "of", y[test].sum())
$ python classify.py
not run yet

Read it cold

Two minutes, on your own.

  • Line 9 turns Apple's return into 0 or 1. What does a 1 mean?
  • Lines 11–12 split the days. Which part does the model learn from?
  • Line 15 asks the model for a probability. Line 16 turns it into a decision. How?
  • Predict: the test year has 24 bad days. How many will the alarm catch?
Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
classify.py
1import pandas as pd
2from sklearn.linear_model import LogisticRegression
3from sklearn.metrics import confusion_matrix
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7
8X = returns[["VOO", "MSFT"]] # the same day
9y = (returns["AAPL"] < -2).astype(int) # 1 = a bad day
10
11train = returns.index < "2025-11-17" # four years
12test = ~train # session 9's year
13
14model = LogisticRegression().fit(X[train], y[train])
15p = model.predict_proba(X[test])[:, 1] # P(bad day)
16alarm = p > 0.2
17
18print("test year:", test.sum(), "days,", y[test].sum(), "bad")
19print(confusion_matrix(y[test], alarm))
20hits = (alarm & (y[test] == 1)).sum()
21print("caught:", hits, "of", y[test].sum())
$ python classify.py
test year: 250 days, 24 bad
[[208 18]
[ 10 14]]
caught: 14 of 24caught

What it prints

  • The test year: 250 days, 24 of them bad.
  • A small table: the confusion matrix. Part 4 explains every number in it.
  • The alarm caught 14 of the 24 bad days.

Is 14 of 24 good? What did it cost? And is this the best method? By the end of the session you can answer all three, with numbers.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Part 1

The question as data

What exactly do we predict, from what, and against which baseline?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
The target

A target that is 0 or 1

Line 9 of the script. 1 Each day gets a class label: 1 for a bad day, the positive class, and 0 for a normal day.

The share of ones is the base rate: about one day in ten. Bad days are the rare class, and that will shape everything we measure.

The labels come from Apple's return, but the model is not allowed to see that return: it is what we want to predict.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
classify.py
1import pandas as pd
2from sklearn.linear_model import LogisticRegression
3from sklearn.metrics import confusion_matrix
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7
8X = returns[["VOO", "MSFT"]] # the same day
9y = (returns["AAPL"] < -2).astype(int) # 1 = a bad day
10
11train = returns.index < "2025-11-17" # four years
12test = ~train # session 9's year
13
14model = LogisticRegression().fit(X[train], y[train])
15p = model.predict_proba(X[test])[:, 1] # P(bad day)
16alarm = p > 0.2
17
18print("test year:", test.sum(), "days,", y[test].sum(), "bad")
19print(confusion_matrix(y[test], alarm))
20hits = (alarm & (y[test] == 1)).sum()
21print("caught:", hits, "of", y[test].sum())
$ python classify.py
not run yet

Train and test (session 9)

Lines 11–12: the first four years train, the last year tests. The comparison works on the date strings, because dates written year-month-day (the ISO standard format) sort in the right order.

  • .fit (line 14) sees only training days.
  • predict_proba (line 15) is asked only about test days.

Session 9 showed why: a model judged on the days it learned from looks better than it is. Everything we report today is from the test year, a year none of the models saw.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Bad days in the cloud of session 9

Where the bad days are

Session 9's cloud, now for the four training years. Red triangles: the 91 bad days, below the dashed line.

  • Almost every bad day comes with a market fall.
  • But not every market fall is a bad day for Apple: some days below −1 % on VOO are normal for Apple.

The market tells us something about the risk, not everything. A classifier has to turn "something" into a decision.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Regression and classification

session 9: regression today: classification
target a number: Apple's return a class: bad day or not
the model gives a predicted number a probability , then a class
loss squared error the log loss (Part 3)
judged by mean squared error on test days confusion matrix, recall, precision (Part 4)
overfitting yes, the same danger yes, the same danger

The features are the same kind of thing as before: numbers we know on day . Today: VOO's and Microsoft's returns, the same day.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Four classification tasks

Classification is everywhere

Our bad-day question is one case of a very common task: put each case into a class, from numbers you know about it.

  • A bank decides on a loan: will this borrower default?
  • A card network checks every payment: is it fraud?
  • A hospital reads a scan: is the tumour malignant?
  • A post office reads an envelope: which digit is this?

The next four slides look at each one. The same methods of today apply to all of them.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Credit default (simulated borrowers)

Credit: will the borrower default?

Each dot is one past borrower (simulated, 800 of them). Red crosses: those who did not repay.

  • Features: debt-to-income ratio, years of credit history.
  • Label: defaulted (1) or repaid (0). Base rate: 5.5 %.

Defaults sit at the bottom right: high debt, short history. But the classes overlap, as our bad days did.

Missing a default costs the loan; refusing a good borrower costs the interest. Two mistakes, two prices: Part 4.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Card payments (simulated)

Payments: is this one fraud?

4020 payments (simulated): when they happened, and how much. Red stars: the 20 frauds.

  • Base rate: 0.5 %. A "classifier" that never flags fraud is 99.5 % accurate, and useless.
  • Frauds stand out here: large amounts at night. In real data they are much better hidden.

Fraud detection is the extreme case of a rare positive class. Keep it in mind when Part 4 asks what "accuracy" is worth.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Handwritten digits (scikit-learn's digits data)

Images: which digit is this?

1797 real handwritten digits, scanned at 8 × 8 pixels; they ship with scikit-learn (load_digits).

  • Features: the 64 grey levels of the pixels, from 0 (white) to 16 (black). An image is just a table of numbers.
  • Label: one of ten classes, 0 to 9. Not yes or no: Part 3 shows how a model handles more than two classes.

Mail sorting, cheque reading and, with bigger images and neural networks (later in Part 2), face and object recognition all start here.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Breast tumours (scikit-learn's breast cancer data)

Medicine: is the tumour malignant?

569 real tumour samples, measured under a microscope (load_breast_cancer in scikit-learn). Red: the 212 malignant ones.

  • Features: 30 measurements of the cell nuclei; two of them on the left.
  • Label: malignant or benign. Base rate: 37 %, far less rare than bad days.

The two classes separate well, but not perfectly. And here a missed malignant tumour costs far more than a second test: the threshold must reflect that.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

What the tasks share

task features label share positive worst mistake
bad day VOO, MSFT returns bad / normal 9.1 % missed bad day
credit debt ratio, history default / repaid 5.5 % loan to a defaulter
fraud hour, amount fraud / normal 0.5 % fraud let through
tumour 30 cell measurements malignant / benign 37 % missed malignancy
digits 64 pixels 0, 1, …, 9 ten classes depends on use

Same ingredients every time: known numbers , a class , past cases with both, a rare or costly class, and two kinds of mistake. Back to bad days: today's methods are general.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Two features

The plane a classifier must split

Each dot is one training day: across, VOO; up, Microsoft. Red triangles: bad days for Apple.

  • Bad days sit at the bottom left, where both fell.
  • They are mixed with normal days there: the classes overlap.

A classifier divides this plane into a region where it says "bad" and a region where it says "normal". The line between them is the decision boundary. Each method today draws a different kind of boundary.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
What a classifier gives

A probability, then a decision

1 Read "the probability that is 1, given the features ". Most classifiers estimate this.

2 A threshold turns the probability into a decision. The script uses (line 16): raise the alarm when the chance of a bad day is above 20 %.

Two separate choices: the model, which gives , and the threshold, which depends on what a mistake costs.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
The lazy classifier

The baseline: never raise an alarm

A "classifier" that always says "normal" is right 90.4 % of the time on the test year, and catches no bad day at all.

Every model today has to beat this, and "right 90.4 % of the time" already shows that the share of correct answers is a poor way to judge it. Part 4 fixes that.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Part 2

k-nearest neighbours

A market scenario arrives. How likely is a bad day for Apple?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

The problem

A risk manager runs scenarios, as in session 9 ("if the market falls 2 %"). Today's scenario:

VOO falls -1.49 % and Microsoft -1.68 %. How likely is a bad day for Apple?

  • The answer should be a probability, so that we can decide whether to hedge.
  • We have no formula linking the two returns to a bad day. We do have four years of days, each with its two returns and its label.

The simplest idea: look at the past days that looked like this scenario, and count how often they were bad.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
One new day

The closest days decide

The scenario is the star: VOO -1.49 %, Microsoft -1.68 %. Which training days looked most like it?

  • Draw the circle around the star that holds its 15 nearest training days.
  • 6 of those 15 days were bad for Apple.
  • So the estimate for the new day: %.

No equation, no parameters to fit. The training days are the model.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
k-nearest neighbours

The rule, written down

1 : the training days closest to the new day . The estimate is the share of bad days among them: the average of their 0/1 labels.

  • With , the rule is a majority vote of the neighbours.
  • is a hyperparameter: chosen by you, not learned from the data.

Two things are still open: what "closest" means, and how to choose .

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Distances

What "closest" means

Two days and , with features (VOO) and (MSFT).

  • Euclidean: the straight-line distance, as with a ruler.
  • Manhattan: walk along the axes only, as on a city grid. One large difference counts less than when it is squared.
  • Minkowski: one formula for both: is Euclidean, is Manhattan.

The last test day (2026-10-30) and its nearest training day (2024-03-01): Euclidean distance 0.034, Manhattan 0.046, in standardised units. Standardised?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
A common unit

Features need a common unit

A distance adds up differences across features. Microsoft moves about 1.450 % on a typical day, VOO 0.952 %: unscaled, Microsoft's differences would weigh more, for no good reason.

1 Standardise: subtract the mean, divide by the standard deviation (session 9's and ). Every feature then has mean 0 and standard deviation 1.

Min–max rescales to instead. Simpler, but one extreme day squeezes all the others together. Standardisation is the usual choice.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
knn_scratch.py
1import numpy as np
2import pandas as pd
3
4history = pd.read_csv("history.csv", index_col="Date")
5returns = history.pct_change().dropna() * 100 # in %
6X = returns[["VOO", "MSFT"]].to_numpy()
7y = (returns["AAPL"] < -2).astype(int).to_numpy()
8train = (returns.index < "2025-11-17")
9Z = (X - X[train].mean(axis=0)) / X[train].std(axis=0)
10
11def knn_proba(new, Z_train, y_train, k):
12 """Share of bad days among the k closest days."""
13 d = np.sqrt(((Z_train - new) ** 2).sum(axis=1))
14 closest = np.argsort(d)[:k] # k smallest distances
15 return y_train[closest].mean()
16
17p = []
18for new in Z[~train]: # every test day
19 p.append(knn_proba(new, Z[train], y[train], k=15))
20p = np.array(p)
21alarm = p > 0.2
22print("caught:", (alarm & (y[~train] == 1)).sum(), "of",
23 y[~train].sum())
24print("false alarms:", (alarm & (y[~train] == 0)).sum())
$ python knn_scratch.py
caught: 14 of 24
false alarms: 19

k-nearest neighbours, by hand

The whole method is the function on lines 11–15: a dozen symbols.

  • Line 9: standardise, with the mean and standard deviation of the training years.
  • Line 13: the Euclidean distance from the new day to every training day, all at once (numpy, session 5).
  • Line 14: np.argsort gives the positions in order of distance; [:k] keeps the first .
  • Line 15: the average of their 0/1 labels is the share of bad days: .

Lines 17–20 ask this for every test day. Same result as scikit-learn's KNeighborsClassifier: 14 caught, 19 false alarms (Part 7).

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
knn.py
1import pandas as pd
2from sklearn.neighbors import KNeighborsClassifier
3from sklearn.preprocessing import StandardScaler
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7X = returns[["VOO", "MSFT"]]
8y = (returns["AAPL"] < -2).astype(int)
9train = returns.index < "2025-11-17"
10test = ~train
11
12scaler = StandardScaler().mean and sd of the training years onlyfit(X[train]) # mean and sd: train
13Z = scaler.transform(X) # every column: sd 1
14
15print("k, train error, test error, caught, false alarms")
16for k in [1, 5, 15, 51, 151]:
17 knn = KNeighborsClassifier(n_neighbors=k)
18 knn.fit(Z[train], y[train])
19 err_train = (knn.predict(Z[train]) != y[train]).mean()
20 guess = knn.predict(Z[test])
21 err_test = (guess != y[test]).mean()
22 caught = ((guess == 1) & (y[test] == 1)).sum()
23 wrong = ((guess == 1) & (y[test] == 0)).sum()
24 print(k, round(err_train, 3), round(err_test, 3),
25 caught, wrong)
$ python knn.py
k, train error, test error, caught, false alarms
1 0.0 0.124 7 14
5 0.065 0.08 8 4
15 0.072 0.084 6 3
51 0.075 0.092 3 2
151 0.091 0.096 0 0

k-nearest neighbours, in code

Lines 12–13: the scaler learns the mean and standard deviation from the training years only, then transforms all days. The test year must not shape the model, not even through the scaling.

Each round (lines 16–25): fit, predict with the majority vote, count. Output columns: , error rate on training and test days, bad days caught, false alarms.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
k = 1, 15 and 151

What does to the boundary

Colour: the predicted probability of a bad day. White below 0.2, orange above, darker above 0.5.

  • : every bad training day claims an island around itself. The boundary follows single days.
  • : a smooth region at the bottom left, where both stocks fell.
  • : so many neighbours that the bad days are always outvoted. Nothing is dark.
Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Error rate against k

Bias and variance, again (session 9)

  • Small , flexible: has zero training error, since each training day is its own nearest neighbour, and the worst test error. Variance: it memorises noise.
  • Large , rigid: the error climbs to the dotted line, the error of never raising an alarm. Bias: it cannot follow the pattern.
  • In between, the test error is lowest.

The same picture as the polynomial degree in session 9, with as the dial, turned the other way.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Reading the k-nearest-neighbours (kNN) output

test error caught false alarms
1 12.4 % 7 14
5 8.0 % 8 4
15 8.4 % 6 3
151 9.6 % 0 0

is worse than no alarms at all (9.6 %). The best, , still misses 16 of 24 bad days. And the error rate counts a miss and a false alarm the same, though they do not cost the same: we need better measures (Part 4).

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

k-nearest neighbours, summed up

strengths weaknesses
no training: the data are the model every prediction searches all training days
any shape of boundary needs scaled features
easy to explain: "days like this one" with many features, "near" stops meaning much
works for numbers too: average the neighbours' must be chosen

The last weakness has a name, the curse of dimensionality: in many dimensions, every day is far from every other day. With two or three features, k-nearest neighbours (kNN) is a strong, simple baseline.

Two things it cannot give: a smooth probability (with only 0, 1/15, 2/15, …) and a number to interpret, such as "how much does the risk rise per 1 % of market fall". Logistic regression gives both.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Part 3

Logistic regression

k-nearest neighbours gives jumpy probabilities and no number to interpret. Can a formula do better?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Least squares on 0s and 1s

Why not session 9's line?

Fit a straight line to the 0/1 labels, by least squares, on VOO alone.

  • The line slopes the right way: lower market, higher risk.
  • But on a market day of +3 %, it predicts -0.295: a negative probability.

A line has no floor and no ceiling. A probability has both. We keep the line, and pass it through a function that maps any number into .

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
The sigmoid

The logistic function

  • very negative: is huge, so is close to 0.
  • : .
  • very positive: is close to 0, so is close to 1.

It squeezes the whole number line into , steepest in the middle and flat at both ends. It is also called the sigmoid.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
The model

Logistic regression

Session 9's line gives a score ; the sigmoid turns it into a probability.

1 The odds: the chance of a bad day against the chance of a normal one. A probability of 20 % is odds of 20 to 80, or 1 to 4.

Undo the sigmoid, and the log of the odds is exactly session 9's line. Logistic regression is a linear model, on the log-odds scale.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Fitted on the training years, VOO only

Four market days

The fitted model, with VOO's return as the only feature.

  • A calm market: 2.8 % chance of a bad day. Rare, not impossible.
  • A 1 % fall: 19.9 %. A 2 % fall: 68.5 %, more likely than not.

Each 1 % changes by the same amount, . The probability does not change by the same amount: the sigmoid is flat at the ends and steep in the middle.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
The fitted curve

The curve and the data

Each dot is a training day, at 1 (bad) or 0 (normal), spread a little vertically so the dots do not hide each other.

  • Where the market rises, the curve is near 0, and nearly all dots are at 0.
  • Where it falls more than about 2 %, the curve passes one half, and most dots are at 1.

Unlike the line, the curve stays between 0 and 1 everywhere.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Odds

The slope, in plain words

On the log-odds scale the model adds; on the odds scale it multiplies.

1 Every additional 1 % fall of the market multiplies the odds of a bad day by .

This is how logistic models are reported in finance, economics and medicine, as odds ratios: "each extra percentage point of market fall multiplies the odds of a bad day for Apple by about nine."

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
From probability to decision, VOO only

The threshold moves the boundary

With one feature, the boundary is a single market return: where the curve crosses .

  • : an alarm only when the market falls more than -1.64 %.
  • , as in the script: an alarm from about -1.00 %.

A lower threshold raises more alarms: it catches more bad days, and cries wolf more often. Which threshold is right is a question about costs, not about the model.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Likelihood of one day (session 9)

The loss, from the likelihood

In session 9, least squares came from the likelihood of normal noise. Here the same move gives the loss.

1 The probability the model gives to what actually happened: on a bad day (), on a normal one. One formula says both.

Days are independent, so these multiply; the log turns the product into a sum. Minus the average is the log loss, also called cross-entropy. Maximum likelihood = minimum log loss.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Log loss of one day

What the log loss punishes

  • A bad day predicted with costs .
  • With : 2.30. With : 4.61.

Confident and wrong is punished hardest. A model that says "impossible" about something that happens pays without limit.

On the training years: a log loss of 0.196, against 0.305 for a model that predicts the base rate every day.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
logit_gd.py
1import numpy as np
2import pandas as pd
3from sklearn.linear_model import LogisticRegression
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7train = returns[returns.index < "2025-11-17"]
8x = train["VOO"]
9y = (train["AAPL"] < -2).astype(int)
10
11a, b, rate = 0.0, 0.0, 0.5
12print("step, log loss, a, b")
13for step in range(1, 3001):
14 p = 1 / (1 + np.exp(-(a + b * x))) # the sigmoid
15 a = a - rate * (p - y).mean()
16 b = b - rate * ((p - y) * x).mean()
17 if step in [1, 10, 100, 1000, 3000]:
18 loss = -(y * np.log(p) + (1 - y) * np.log(1 - p))
19 loss = round(loss.mean(), 4)
20 print(step, loss, round(a, 3), round(b, 3))
21
22m = LogisticRegression(C=np.inf).fit(train[["VOO"]], y)
23print("sklearn:", m.intercept_.round(3), m.coef_.round(3))
$ python logit_gd.py
step, log loss, a, b
1 0.6931 -0.204 -0.066
10 0.3393 -1.253 -0.429
100 0.2046 -2.845 -1.567
1000 0.1965 -3.651 -2.26
3000 0.1965 -3.656 -2.264
sklearn: [-3.651] [[-2.26]]the same

Minimising it: gradient descent (session 9)

There is no formula for the best and : hides them inside an exponential. So we walk downhill, exactly as in session 9.

  • Line 14: the sigmoid replaces the line.
  • Lines 15–16: the gradient is prediction minus truth, times : the same shape as for least squares.
  • After 1000 steps: , the same as scikit-learn's LogisticRegression(C=np.inf) (line 22).

C=np.inf switches off a small built-in penalty. The default, C = 1, shrinks the slope slightly: . That is the model on the earlier slides.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
VOO and MSFT

Two features: a straight boundary

Line 14 of the script: the same model with both features.

  • The places where , or , are where is constant: straight lines in the plane. Logistic regression always draws straight boundaries.
  • Microsoft's slope, -0.093, is small next to VOO's -2.076. Session 9 again: Microsoft follows the market, so once VOO is in the model, Microsoft adds little.
Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Three classes

More than two classes

Add a third class: a good day, Apple up more than 2 %. In the training years: 91 bad, 799 normal, 109 good.

One score per class, each with its own line. 1 The softmax turns the scores into probabilities that add up to 1. With two classes, it is the sigmoid again.

A calm market: 95 % normal. VOO −2 %: 68 % bad. VOO +2 %: 78 % good. LogisticRegression does this by itself when has more than two labels.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Part 4

Judging a classifier

We have probabilities and alarms. How good are they, and which mistakes do they make?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Accuracy and error rate

The obvious measure, and its problem

The accuracy is the share of days classified correctly; the error rate, used for k-nearest neighbours, is the rest.

With a rare positive class, both are dominated by the easy majority. A model that never raises an alarm scores 90.4 %. A model that catches every bad day but also raises a few false alarms can score lower.

We need to count the two kinds of mistake separately.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Confusion matrix

Four kinds of outcome

  • TP, true positive: a bad day, and an alarm.
  • FN, false negative: a bad day, missed.
  • FP, false positive: an alarm on a normal day.
  • TN, true negative: a normal day, and quiet.

This table is the confusion matrix. confusion_matrix in scikit-learn prints it with the true class in rows, in the order 0 then 1: the first row is the normal days, the second the bad days.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Logistic regression, test year

The model's answers on the test year

Each dot is one test day, placed at the probability the model gave it. Top: the 24 bad days. Bottom: the 226 normal days.

  • Most normal days get a probability near 0: good.
  • The bad days are spread out: some clearly high, many low.
  • A threshold is a vertical line: everything to its right gets an alarm.

At few bad days are to the right. At many more, and some normal days too. The next slides count them.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Logistic regression, test year, t = 0.5

The usual threshold of 0.5

The two-feature model of the script, with instead of 0.2.

  • Accuracy 91.6 %, a little above never raising an alarm.
  • 1 18 of the 24 bad days missed: false negatives (FN).
  • Only 3 false alarms, false positives (FP): the model is cautious.

Accuracy adds the diagonal, TP and TN. The bad-day row is where the model fails.

TP: true positives (bad days caught). TN: true negatives (quiet normal days). FN: false negatives (missed bad days). FP: false positives (false alarms).

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Recall, precision, F1 at t = 0.5

Two questions instead of one

  • Recall, also sensitivity or true positive rate: of the bad days, how many did we catch? 25.0 %.
  • Precision: of the alarms, how many were right? 66.7 %.

combines them by their harmonic mean, which is low if either one is low.

At : precise, but it misses three bad days out of four.

TP: true positives (bad days caught). FN: false negatives (missed bad days). FP: false positives (false alarms).

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Which mistake costs more?

The data cannot tell you the price of a mistake. The situation can.

  • A missed bad day, a false negative (FN): Apple falls more than 2 % with no protection. On 1905.00 of Apple, more than 38 in one day.
  • A false alarm, a false positive (FP): you hedge for nothing, and pay the cost of the hedge.

If a miss costs several times a false alarm, a rule that catches more bad days, at the price of more alarms, is better, even if its accuracy is lower.

The threshold is a business decision. 0.5 is a habit, not a rule.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
classify.py
1import pandas as pd
2from sklearn.linear_model import LogisticRegression
3from sklearn.metrics import confusion_matrix
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7
8X = returns[["VOO", "MSFT"]] # the same day
9y = (returns["AAPL"] < -2).astype(int) # 1 = a bad day
10
11train = returns.index < "2025-11-17" # four years
12test = ~train # session 9's year
13
14model = LogisticRegression().fit(X[train], y[train])
15p = model.predict_proba(X[test])[:, 1] # P(bad day)
16alarm = p > 0.2
17
18print("test year:", test.sum(), "days,", y[test].sum(), "bad")
19print(confusion_matrix(y[test], alarm))
20hits = (alarm & (y[test] == 1)).sum()
21print("caught:", hits, "of", y[test].sum())
$ python classify.py
test year: 250 days, 24 bad
[[208 18]false alarms
[ 10 14]]
caught: 14 of 24

Lower the threshold to 0.2

The script, line 16. Its confusion matrix (line 19), in scikit-learn's layout:

  • 14 bad days caught instead of 6.
  • 18 false alarms instead of 3.

TN: true negatives (quiet normal days). FP: false positives (false alarms). FN: false negatives (missed bad days). TP: true positives (bad days caught).

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
t = 0.2

More useful, less accurate

  • Recall more than doubles: 25.0 % → 58.3 %.
  • Precision falls: 66.7 % → 43.8 %. More than half of the alarms are false.
  • rises from 0.36 to 0.50.
  • Accuracy falls, from 91.6 % to 88.8 %.

For a risk manager this rule is much more useful, and the accuracy says the opposite.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Every threshold, test year

The trade-off, for every threshold

  • Lower the threshold: recall (red) rises, precision (blue) falls.
  • No threshold makes both high: the model only has two market returns to go on.

Choosing the threshold means choosing a point on these curves, with the costs of the two mistakes in mind.

To compare models, not thresholds, we need a summary over all thresholds at once.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
ROC curve, test year

The ROC (receiver operating characteristic) curve

For every threshold, plot the share of bad days caught (TPR, true positive rate: the recall) against the share of normal days with an alarm (FPR, false positive rate).

  • Bottom left: no alarms. Top right: alarms every day. Dotted: a coin flip.

The closer to the top left, the better the model separates the classes.

TP: true positives (bad days caught). FN: false negatives (missed bad days). FP: false positives (false alarms). TN: true negatives (quiet normal days).

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Area under the ROC curve

AUC: one number for all thresholds

The area under the ROC curve (AUC; ROC: receiver operating characteristic) has a direct meaning: pick one bad day and one normal day at random. AUC is the probability that the model gave the bad day the higher probability.

  • 0.5: no better than a coin. 1: perfect separation.
  • Logistic regression, test year: 0.861.

AUC judges the ranking of days; the threshold is chosen afterwards. That makes it the fair number for comparing methods, and we use it from now on.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
metrics_scratch.py
1import numpy as np
2import pandas as pd
3from sklearn.linear_model import LogisticRegression
4from sklearn.metrics import roc_auc_score
5
6history = pd.read_csv("history.csv", index_col="Date")
7returns = history.pct_change().dropna() * 100 # in %
8X = returns[["VOO", "MSFT"]]
9y = (returns["AAPL"] < -2).astype(int).to_numpy()
10train = returns.index < "2025-11-17"
11model = LogisticRegression().fit(X[train], y[train])
12p = model.predict_proba(X[~train])[:, 1]
13y_te = y[~train]
14
15alarm = p > 0.2
16tp = (alarm & (y_te == 1)).sum()
17fp = (alarm & (y_te == 0)).sum()
18fn = (~alarm & (y_te == 1)).sum()
19print("recall:", round(tp / (tp + fn), 3),
20 " precision:", round(tp / (tp + fp), 3))
21
22wins = 0 # AUC: bad day vs normal day, all pairs
23for p_bad in p[y_te == 1]:
24 for p_normal in p[y_te == 0]:
25 wins = wins + (p_bad > p_normal)
26pairs = (y_te == 1).sum() * (y_te == 0).sum()
27print("AUC, counting pairs:", round(wins / pairs, 3))
28auc = roc_auc_score(y_te, p)
29print("AUC, scikit-learn: ", round(auc, 3))
$ python metrics_scratch.py
recall: 0.583 precision: 0.438
AUC, counting pairs: 0.861
AUC, scikit-learn: 0.861

The measures, by hand

Nothing in Part 4 needs a library.

  • Lines 16–18: TP (true positives), FP (false positives), FN (false negatives) are counts of days. Recall and precision follow (lines 19–20).
  • Lines 22–25: the definition of AUC (area under the curve of caught against false alarms): take every pair of one bad day and one normal day, and count how often the bad day got the higher probability.

24 × 226 pairs, two for loops (session 3). Same answer as roc_auc_score: 0.861. The library is only faster.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Averages over the two classes, t = 0.2

One number per class, or one for all?

Precision, recall and exist for each class, the normal days included. classification_report prints them, with three averages:

  • Macro: each class counts the same. The rare class weighs half.
  • Weighted: each class weighted by its number of days. The normal days dominate.
  • Micro: pool every decision first. With one label per day, that is the accuracy.

With a rare class that matters, read its own row. If you need one number, use the macro average.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Which number to report

question measure
how often is it right? accuracy (misleading if a class is rare)
of the real events, how many were caught? recall, TPR: true positive rate
of the alarms, how many were real? precision
one number from precision and recall
how often is a normal day flagged? FPR: false positive rate
does it rank events above non-events? AUC: area under the curve of caught vs false alarms
one number over classes macro average

Always report the base rate too: 43.8 % precision is poor if half the days are bad, useful if one in ten is.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Part 5

Decision trees

Can we learn rules a person can read and check?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

The problem

The risk committee asks for something neither model gives: a rule they can read and check.

  • Logistic regression gives a probability and one straight boundary. To explain it, you need the sigmoid and two slopes.
  • k-nearest neighbours gives any boundary, but its only explanation is "days like this one".

What the committee wants looks like this: "Raise the alarm when VOO falls more than ⋯ %, unless ⋯".

Can we learn such rules from the data, and choose the cut-offs automatically?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
tree.py
1import pandas as pd
2from sklearn.tree import DecisionTreeClassifier, export_text
3from sklearn.metrics import roc_auc_score
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7X = returns[["VOO", "MSFT"]]
8y = (returns["AAPL"] < -2).astype(int)
9train = returns.index < "2025-11-17"
10test = ~train
11
12small = DecisionTreeClassifier(criterion="entropy", max_depth=2)
13small.fit(X[train], y[train])
14print(export_text(small, feature_names=["VOO", "MSFT"],
15 show_weights=True))
16
17print("depth, train AUC, test AUC")
18for depth in [1, 2, 3, 5, 10, None]:
19 tree = DecisionTreeClassifier(criterion="entropy",
20 max_depth=depth,
21 random_state=0)
22 tree.fit(X[train], y[train])
23 p_train = tree.predict_proba(X[train])[:, 1]
24 p_test = tree.predict_proba(X[test])[:, 1]
25 print(depth, round(roc_auc_score(y[train], p_train), 3),
26 round(roc_auc_score(y[test], p_test), 3))
$ python tree.py
|--- VOO <= -0.36
| |--- VOO <= -2.07
| | |--- weights: [1.00, 17.00] class: 117 bad, 1 normal
| |--- VOO > -2.07
| | |--- weights: [255.00, 69.00] class: 0
|--- VOO > -0.36
| |--- VOO <= -0.08
| | |--- weights: [100.00, 4.00] class: 0
| |--- VOO > -0.08
| | |--- weights: [552.00, 1.00] class: 0
depth, train AUC, test AUC
1 0.832 0.748
2 0.87 0.785
3 0.906 0.802
5 0.935 0.815
10 0.984 0.71
None 1.0 0.692

A tree of questions

DecisionTreeClassifier with at most two questions in a row (line 12). Its rules, as text:

  • Is VOO below −0.36 %? If not, almost no bad days: 5 in 657.
  • If yes: is VOO below −2.07 %? Then 17 of 18 days were bad.
  • Between the two: 86 − 17 = 69 bad days among 324.

The weights are [normal, bad] days in the training years. A tree is a set of rules you can read aloud, and check.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
The depth-2 tree

The same tree, drawn

Each box is a group of training days. The top box holds all 999; each question sends a day left (yes) or right (no).

  • Each box: how many training days land there, how many of them were bad, and its entropy: how mixed it is (0 means one class only).
  • Red: bad days are the majority, so the tree answers "bad" for a new day that lands there.

How did the tree choose these questions, and these cut-offs? It measures how much each question reduces the mixing.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Entropy of a yes/no outcome

Entropy: how mixed is a group?

Claude Shannon's measure of uncertainty (1948), named after Boltzmann's entropy in physics. is the share of bad days in a group.

  • : a coin. 1 bit: the most uncertain a yes/no can be.
  • or : no uncertainty, 0 bits.
  • Our training years, %: 0.440 bits. Not very mixed, because bad days are rare.

1 Logarithm to base 2, so the unit is the bit: the information in one fair yes/no answer.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Information gain of one question

How much does a question help?

Ask "is VOO below −0.36 %?". It splits the 999 training days in two groups:

  • yes: 342 days, 86 bad: entropy 0.814, quite mixed.
  • no: 657 days, 5 bad: entropy 0.064, almost pure.

The entropy after the question is the average of the two, weighted by group size. This is the conditional entropy.

1 The drop is the information gain: 0.119 bits. The tree asks the question with the largest gain.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
entropy.py
1import numpy as np
2import pandas as pd
3
4def entropy(p):
5 """Bits of uncertainty in a yes/no with P(yes) = p."""
6 if p == 0 or p == 1:
7 return 0.0
8 return -(p * np.log2(p) + (1 - p) * np.log2(1 - p))
9
10history = pd.read_csv("history.csv", index_col="Date")
11returns = history.pct_change().dropna() * 100 # in %
12train = returns[returns.index < "2025-11-17"]
13x = train["VOO"]
14y = (train["AAPL"] < -2).astype(int)
15
16print("before any question:", round(entropy(y.mean()), 3))
17print("question, left days, right days, entropy after, gain")
18for cut in [-2.0, -1.0, -0.359, 0.0]:
19 left = x <= cut # the question's "yes"
20 h_left = entropy(y[left].mean())
21 h_right = entropy(y[~left].mean())
22 after = left.mean() * h_left + (~left).mean() * h_right
23 gain = entropy(y.mean()) - after
24 print("VOO <=", cut, left.sum(), (~left).sum(),
25 round(after, 3), round(gain, 3))
$ python entropy.py
before any question: 0.44
question, left days, right days, entropy after, gain
VOO <= -2.0 21 978 0.387 0.053
VOO <= -1.0 137 862 0.341 0.099
VOO <= -0.359 342 657 0.321 0.119the largest gain
VOO <= 0.0 474 525 0.343 0.097

Trying every cut-off

The function entropy (lines 4–8) is the formula of two slides back. Lines 18–25 try four cut-offs for VOO and compute the gain of each.

  • −2 %: a very pure "yes" group, but only 21 days. Little gain.
  • 0 %: two big groups, both still mixed.
  • −0.359 %: the best of the four, and the tree's first question.

The real tree tries every cut-off between two observed values, for every feature, and keeps the best.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Growing the whole tree

  1. Start with all training days in one group.
  2. For every feature and every cut-off, compute the information gain. Ask the best question; split the group in two.
  3. Do the same again inside each new group.
  4. Stop when a group is pure, too small, or the tree has reached its maximum depth.
  5. Each final group (a leaf) answers with its share of bad days.

Numerical features are split by a cut-off, as above. Categories, like the weekday, are split by one-hot columns (session 9): "is it a Monday?" is a yes-or-no question like any other.

Trees need no scaling: a cut-off works the same in % or in basis points.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
tree_scratch.py
1import numpy as np
2import pandas as pd
3
4def entropy(p):
5 if p == 0 or p == 1:
6 return 0.0
7 return -(p * np.log2(p) + (1 - p) * np.log2(1 - p))
8
9def best_split(x, y):
10 """The cut-off on x with the largest information gain."""
11 best_cut, best_gain = None, 0.0
12 values = np.sort(np.unique(x))
13 for cut in (values[:-1] + values[1:]) / 2: # midpoints
14 left = x <= cut
15 after = (left.mean() * entropy(y[left].mean())
16 + (~left).mean() * entropy(y[~left].mean()))
17 gain = entropy(y.mean()) - after
18 if gain > best_gain:
19 best_cut, best_gain = cut, gain
20 return best_cut, best_gain
21
22history = pd.read_csv("history.csv", index_col="Date")
23returns = history.pct_change().dropna() * 100 # in %
24train = returns[returns.index < "2025-11-17"]
25x = train["VOO"].to_numpy()
26y = (train["AAPL"] < -2).astype(int).to_numpy()
27
28cut, gain = best_split(x, y) # question 1
29print("VOO <=", round(cut, 3), " gain", round(gain, 3))
30yes = x <= cut
31cut_yes, g_yes = best_split(x[yes], y[yes]) # 2a: if yes
32cut_no, g_no = best_split(x[~yes], y[~yes]) # 2b: if no
33print(" if yes: VOO <=", round(cut_yes, 3),
34 " gain", round(g_yes, 3))
35print(" if no: VOO <=", round(cut_no, 3),
36 " gain", round(g_no, 3))
$ python tree_scratch.py
VOO <= -0.359 gain 0.119
if yes: VOO <= -2.067 gain 0.09
if no: VOO <= -0.079 gain 0.011

A tree, by hand

best_split (lines 9–20) is step 2 of the recipe: try every cut-off, keep the one with the largest information gain.

  • Line 13: the candidate cut-offs, halfway between neighbouring values.
  • Lines 14–17: the entropy after each question, and the gain: the formula of the entropy slides.

Then grow: ask the best question of all training days (line 28), and again inside each of the two groups (lines 31–32). The three cut-offs, −0.359, −2.067 and −0.079, are exactly those of scikit-learn's depth-2 tree.

Deeper trees repeat the same step inside every new group, until a stopping rule.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Regions of two trees

Boxes, not curves

Every question cuts the plane along one axis, so a tree's regions are boxes.

  • Depth 2: two cuts, both on VOO. Simple and readable.
  • No depth limit: the tree keeps splitting until every leaf is pure. Tiny boxes around single bad days, like in k-nearest neighbours.

What does that do on the test year?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
tree.py
1import pandas as pd
2from sklearn.tree import DecisionTreeClassifier, export_text
3from sklearn.metrics import roc_auc_score
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7X = returns[["VOO", "MSFT"]]
8y = (returns["AAPL"] < -2).astype(int)
9train = returns.index < "2025-11-17"
10test = ~train
11
12small = DecisionTreeClassifier(criterion="entropy", max_depth=2)
13small.fit(X[train], y[train])
14print(export_text(small, feature_names=["VOO", "MSFT"],
15 show_weights=True))
16
17print("depth, train AUC, test AUC")
18for depth in [1, 2, 3, 5, 10, None]:
19 tree = DecisionTreeClassifier(criterion="entropy",
20 max_depth=depth,
21 random_state=0)
22 tree.fit(X[train], y[train])
23 p_train = tree.predict_proba(X[train])[:, 1]
24 p_test = tree.predict_proba(X[test])[:, 1]
25 print(depth, round(roc_auc_score(y[train], p_train), 3),
26 round(roc_auc_score(y[test], p_test), 3))
$ python tree.py
|--- VOO <= -0.36
| |--- VOO <= -2.07
| | |--- weights: [1.00, 17.00] class: 1
| |--- VOO > -2.07
| | |--- weights: [255.00, 69.00] class: 0
|--- VOO > -0.36
| |--- VOO <= -0.08
| | |--- weights: [100.00, 4.00] class: 0
| |--- VOO > -0.08
| | |--- weights: [552.00, 1.00] class: 0
depth, train AUC, test AUC
1 0.832 0.748
2 0.87 0.785
3 0.906 0.802
5 0.935 0.815
10 0.984 0.71
None 1.0 0.692memorised

Depth is the flexibility dial

Six trees, judged by AUC (area under the curve of bad days caught against false alarms) on the training years and on the test year.

  • Training AUC rises with every level, to a perfect 1.0.
  • Test AUC peaks around depth 5, then falls to 0.692.

The unlimited tree memorised the four training years, noise included. Session 9's overfitting, a third time today: the degree of a polynomial, in k-nearest neighbours, and now the depth of a tree.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
AUC against depth

Trees, summed up

strengths weaknesses
rules you can read and check a small change in the data can change the whole tree
no scaling needed overfit easily: depth must be limited
numbers and categories alike boxes only, so diagonal boundaries need many cuts

The best single tree here (depth 5, area under the curve, AUC, 0.815) is clearly behind logistic regression (0.861). The first weakness, instability, is also the key to fixing the second.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Part 6

Many trees

Deep trees memorise the past. Can we keep their flexibility without their instability?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

The problem

The trees of Part 5 face the trade-off of session 9 head-on:

  • A deep tree follows the data closely: training AUC 1.0, test AUC 0.692. It memorised noise: variance.
  • A shallow tree is stable but crude: depth 5 reaches only 0.815, behind logistic regression.

Limiting the depth trades one problem for the other. Is there a way to keep the flexibility of deep trees and remove their instability?

AUC: area under the curve of bad days caught against false alarms.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
The average of independent errors

Why a committee beats a member

Ask models and take a majority vote, or average their probabilities. Each model is wrong in its own way, with errors of spread .

1 If those errors are independent, their average has variance : it shrinks as the committee grows. The errors cancel; what the models agree on remains.

Left: a random forest's test AUC (area under the curve) as trees are added: 0.80 with one tree, 0.86 with 300.

The catch: models trained on the same data make the same mistakes. To profit, the members must be different: the next slide shows how.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Three trees, three bootstrap samples

Bagging and random forests

Bagging ("bootstrap aggregating"): build each tree on a bootstrap sample: 999 days drawn from the training years with replacement. Some days appear twice, some not at all.

Left: three depth-6 trees, each on its own bootstrap sample. Same method, slightly different pasts, visibly different boxes.

Random forest: bagging, plus a random subset of features at every split, for even more different trees. Then all trees vote, or average their probabilities.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
bagging_scratch.py
1import numpy as np
2import pandas as pd
3from sklearn.tree import DecisionTreeClassifier
4from sklearn.metrics import roc_auc_score
5
6history = pd.read_csv("history.csv", index_col="Date")
7returns = history.pct_change().dropna() * 100 # in %
8X = returns[["VOO", "MSFT"]].to_numpy()
9y = (returns["AAPL"] < -2).astype(int).to_numpy()
10train = returns.index < "2025-11-17"
11X_tr, y_tr = X[train], y[train]
12X_te, y_te = X[~train], y[~train]
13
14rng = np.random.default_rng(0)
15total = np.zeros(len(y_te))
16for b in range(100):
17 rows = rng.choice(len(y_tr), size=len(y_tr)) # bootstrap
18 tree = DecisionTreeClassifier(criterion="entropy",
19 random_state=b)
20 tree.fit(X_tr[rows], y_tr[rows])
21 total = total + tree.predict_proba(X_te)[:, 1]
22 if b == 0:
23 auc = roc_auc_score(y_te, total)
24 print("1 tree, test AUC:", round(auc, 3))
25p = total / 100 # the average vote
26auc = roc_auc_score(y_te, p)
27print("100 trees, test AUC:", round(auc, 3))
$ python bagging_scratch.py
1 tree, test AUC: 0.567
100 trees, test AUC: 0.823

Bagging, by hand

One loop (lines 16–24), one tree per round:

  • Line 17: draw 999 row numbers with replacement: a bootstrap sample (session 4's random, now numpy's).
  • Lines 18–20: grow a deep tree on those rows only.
  • Line 21: add its probabilities for the test days to a running total.

Line 25: divide by 100, the average vote. One tree on its own: AUC (area under the curve) 0.567. A hundred, averaged: 0.823.

A random forest adds one line inside the tree: at each split, only a random subset of features may be used.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
forest.py
1import pandas as pd
2from sklearn.tree import DecisionTreeClassifier
3from sklearn.ensemble import BaggingClassifier
4from sklearn.ensemble import RandomForestClassifier
5from sklearn.metrics import roc_auc_score
6
7history = pd.read_csv("history.csv", index_col="Date")
8returns = history.pct_change().dropna() * 100 # in %
9X = returns[["VOO", "MSFT"]]
10y = (returns["AAPL"] < -2).astype(int)
11train = returns.index < "2025-11-17"
12test = ~train
13
14models = {
15 "one deep tree": DecisionTreeClassifier(
16 criterion="entropy", random_state=0),
17 "100 bagged trees": BaggingClassifier(
18 DecisionTreeClassifier(criterion="entropy"),
19 n_estimators=100, random_state=0),
20 "random forest": RandomForestClassifier(
21 n_estimators=300, min_samples_leaf=5, random_state=0),
22}
23for name in models:
24 m = models[name].fit(X[train], y[train])
25 p = m.predict_proba(X[test])[:, 1]
26 auc = roc_auc_score(y[test], p)
27 print(name, "test AUC:", round(auc, 3))
$ python forest.py
one deep tree test AUC: 0.692
100 bagged trees test AUC: 0.826
random forest test AUC: 0.864from 0.69

One tree against a forest

Three models in a dictionary (lines 14–22, session 5), each fitted and judged on the test year in the same loop.

  • One unlimited tree: 0.692.
  • 100 trees, each on a bootstrap sample: 0.826.
  • 300 trees with random feature choice: 0.864.

The same kind of overfitted tree, averaged a few hundred times, becomes one of the best models of the day.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
One deep tree, and a forest

What averaging does to the boxes

  • One deep tree: islands around single training days. It memorised them.
  • The forest: hundreds of such trees, each with different islands. Averaged, the islands blur, and what remains is the pattern they share: a smooth region at the bottom left.

The forest has lost the readable rules of a single tree. That is the price: accuracy against explanation.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Boosting

Bagging trains its trees side by side and averages them. Boosting trains them one after another:

  1. Fit a small, simple tree.
  2. Give more weight to the days it got wrong.
  3. Fit the next small tree to those weights. Repeat.
  4. Combine all trees, the better ones with more say.

AdaBoost was the first such method; gradient boosting (XGBoost, LightGBM) is the most used today, and wins many prediction competitions on tables of data. Same idea as gradient descent: each new tree takes a small step that reduces the remaining error.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Part 7

Four classifiers, one test year

Four methods. Which one goes to the risk manager?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

The problem

Four methods, each with its own idea, each with numbers that look good. Which one should the risk manager use?

A fair comparison needs the same of everything:

  • the same two features, VOO and MSFT, the same day;
  • the same training years, and the same test year, unseen by every model;
  • the same measures: AUC (area under the curve of bad days caught against false alarms) to compare the rankings, and bad days caught and false alarms at the same threshold, .
Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Test year, all four models

The comparison

model AUC caught false
logistic 0.861 14 18
kNN, 0.865 14 19
tree, depth 5 0.815 14 16
forest 0.864 16 23

Caught and false alarms at , of 24 bad days.

Three tie: the boundary is nearly straight. Occam's razor (session 9): take logistic regression.

kNN: k-nearest neighbours. AUC: area under the curve of bad days caught against false alarms.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
tomorrow.py changed on this slide
1import pandas as pd
2from sklearn.linear_model import LogisticRegression
3from sklearn.metrics import roc_auc_score
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7bad = (returns["AAPL"] < -2).astype(int)
8
9data = pd.DataFrame({"today_VOO": returns["VOO"].shift(-1),
10 "tomorrow_bad": bad.shift(-1)}).dropna()
11X = data[["today_VOO"]]
12y = data["tomorrow_bad"].astype(int)
13train = data.index < "2025-11-17"
14test = ~train
15
16model = LogisticRegression().fit(X[train], y[train])
17p = model.predict_proba(X[test])[:, 1]
18print("test days:", test.sum(), " bad:", y[test].sum())
19print("test AUC:", round(roc_auc_score(y[test], p), 3))
$ python tomorrow.py
test days: 249 bad: 24
test AUC: 0.858tomorrow, predicted?

Spot the lie

A classmate wants to predict tomorrow's bad day from today's market, to hedge in advance. Same method, trained on four years, judged on the test year: AUC (area under the curve of bad days caught against false alarms) 0.858.

  • As good as our same-day model.
  • A proper test year, no crash, no warning.

Is this a money machine? What is wrong?

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
tomorrow.py
1import pandas as pd
2from sklearn.linear_model import LogisticRegression
3from sklearn.metrics import roc_auc_score
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7bad = (returns["AAPL"] < -2).astype(int)
8
9data = pd.DataFrame({"today_VOO": returns["VOO"],
10 "tomorrow_bad": bad.shift(-1)}).dropna()
11X = data[["today_VOO"]]
12y = data["tomorrow_bad"].astype(int)
13train = data.index < "2025-11-17"
14test = ~train
15
16model = LogisticRegression().fit(X[train], y[train])
17p = model.predict_proba(X[test])[:, 1]
18print("test days:", test.sum(), " bad:", y[test].sum())
19print("test AUC:", round(roc_auc_score(y[test], p), 3))
$ python tomorrow.py
test days: 249 bad: 24
test AUC: 0.623

The lie, explained

Their line 9 read returns["VOO"].shift(-1): shifted the wrong way.

  • honest (left): VOO on day → bad day on
  • the classmate's: VOO on day → bad day on

Their model saw the market of the very day it predicted. With today's return, the AUC (area under the curve of bad days caught against false alarms) is 0.623: close to a coin. In make_history.py the days are independent, so today says nothing about tomorrow.

This is leakage: information that would not exist at the moment of prediction. A test year cannot catch it.

Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

Before you trust a classifier

  • Base rate first. What does "never an alarm" score? Compare everything with that.
  • Look past accuracy. Confusion matrix, recall, precision, AUC (area under the curve of bad days caught against false alarms).
  • Choose the threshold from the costs of the two mistakes, not from habit.
  • Judge on unseen days. Fit everything, scaling included, on the training days only.
  • Check for leakage. Would every feature be known at the moment you predict?
  • Prefer the simpler model when the test year cannot tell them apart.
Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
classify.py
1import pandas as pd
2from sklearn.linear_model import LogisticRegression
3from sklearn.metrics import confusion_matrix
4
5history = pd.read_csv("history.csv", index_col="Date")
6returns = history.pct_change().dropna() * 100 # in %
7
8X = returns[["VOO", "MSFT"]] # the same day
9y = (returns["AAPL"] < -2).astype(int) # 1 = a bad day
10
11train = returns.index < "2025-11-17" # four years
12test = ~train # session 9's year
13
14model = LogisticRegression().fit(X[train], y[train])
15p = model.predict_proba(X[test])[:, 1] # P(bad day)
16alarm = p > 0.2
17
18print("test year:", test.sum(), "days,", y[test].sum(), "bad")
19print(confusion_matrix(y[test], alarm))
20hits = (alarm & (y[test] == 1)).sum()
21print("caught:", hits, "of", y[test].sum())
$ python classify.py
test year: 250 days, 24 bad
[[208 18]
[ 10 14]]
caught: 14 of 24

Read it again

The script from the start of the session:

  • 8–9: two features, and a 0/1 target with a base rate of about 10 % (Part 1)
  • 11–12: four years to learn from, a year to judge on (session 9)
  • 14–15: logistic regression; a probability for each test day (Part 3)
  • 16: a threshold of 0.2, chosen for recall over accuracy (Part 4)
  • 19–21: the confusion matrix, and the bad days caught (Part 4)
Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days
Today, in five lines

TP, FN, FP: true positives, false negatives, false positives

Check yourself

  1. k-nearest neighbours with has zero training error. Why is that not good news?
  2. Why must the scaler be fitted on the training days only?
  3. A fraud detector is 99.9 % accurate; 0.1 % of payments are fraud. What do you ask next?
  4. Moving the threshold from 0.5 to 0.2: what happens to recall, to precision, to the AUC (area under the curve of bad days caught against false alarms)?
  5. A group has 50 bad and 50 normal days. What is its entropy? And with 100 bad, 0 normal?
Data Science and Advanced Programming · UNIL · 2026
Session 10 · Classification: bad days

What you can now do

  • Turn a yes-or-no question into a 0/1 target, and find its base rate.
  • Classify with k-nearest neighbours: choose the distance, scale the features, choose .
  • Fit logistic regression; read probabilities and odds ratios; explain the log loss from the likelihood and fit it by gradient descent.
  • Judge a classifier with the confusion matrix, recall, precision, , the ROC curve (receiver operating characteristic) and the AUC (area under it); choose a threshold from costs.
  • Grow a decision tree from entropy and information gain, and limit its depth.
  • Explain why bagging and random forests beat a single tree.
  • Spot leakage.

Next session: learning without labels: clustering and principal components.

Data Science and Advanced Programming · UNIL · 2026

GENERATED from slides.src.md by tools/codewalk/build.py. Edit the source, not this file.