IFI 8410 — Session 13: Introductory Machine Learning

Learning from Examples

The examples are the input; the rule is the output

The problem

Rules nobody can write down

  • Which customers are about to cancel?
  • Which transactions are fraudulent?
  • Will tomorrow be a busy day?
  • Which restaurants will have closed by next year?

What usually exists is a record of past cases with their outcomes. Machine learning hands those examples to a program and lets it find a rule. That takes three lines of code. The problem is everything around them:

Is the model any good?

Compared with what?

Will it work on cases it has not seen?

A model can score perfectly on its own examples and be useless on new ones.

Which mistakes does it make?

Missing a fraud and raising a false alarm are not the same error.

Is it cheating?

A model will use any column that helps, including ones that would not exist when a real prediction is needed.

The tools

Four packages

scikit-learn

machine learning

Dozens of models behind one interface: fit, predict, score. Splitting data, metrics, baselines, cross-validation.

pandas

preparing the data

Building the table of features: filling blanks, encoding categories, selecting columns.

NumPy

arrays

What scikit-learn computes on and returns.

matplotlib

looking

Accuracy against model complexity; pictures of what a model has learned.

scikit-learn's strength is uniformity: every model is used with the same four steps, so what you learn on one transfers to all.

Concept 1

Features and target

X = days[["temperature", "rain", "weekend"]]
y = days["busy"]
NameExample
what the model may look atfeatures, Xtemperature, rain, weekend
what it should predicttarget, ybusy or not
  • Missing values: fill them, and keep the fact in a column of its own. A blank is often informative.
  • True/False: 1 and 0.
  • Categories: one 0/1 column per value (one-hot). Numbering them 1, 2, 3 invents an order.
  • Identifiers and names: leave them out. They let a model memorise rows.

A target that is a category makes the task classification; a number makes it regression. Today: two classes, 0 and 1, where 1 is the outcome you are looking for.

Concept 2

Train and test

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=13)

Score a model on the rows it learned from and the answer is often close to 100 %. That is an exam whose questions were handed out beforehand.

  1. The test set is put aside first.
  2. Nothing that is learned or chosen may use it.
  3. It is used once, at the end.

Breaking any of the three produces a number that looks better than the truth. When the model will predict the future from the past, the honest test set is the later part of the data, not a random part.

Concept 3

The baseline

majority = y_train.value_counts().idxmax()     # learned from the training set
baseline = (y_test == majority).mean()         # measured on the test set
  • Before any model: how well does the simplest possible guess do?
  • "70 % accurate" means little if always saying "no" scores 67 %.
  • When one class is rare, the baseline is very high: one positive in forty, and "never" is 97.5 % accurate and finds nothing.

A model that does not beat the baseline is a finding, and should be reported as one.

Concept 4

A decision tree

from sklearn.tree import DecisionTreeClassifier, export_text

model = DecisionTreeClassifier(max_depth=2, random_state=13)   # make
model.fit(X_train, y_train)                                    # learn
predictions = model.predict(X_test)                            # predict
model.score(X_test, y_test)                                    # accuracy

print(export_text(model, feature_names=list(X.columns)))       # read it
  • Twenty questions: is the temperature at most 15 degrees? Each answer leads to another question or to a verdict.
  • Training means choosing the questions: the one that sorts the training examples most cleanly, then the same on each side.
  • A small tree can be read, and checked against common sense.

Concept 5

Overfitting

DepthTraining rowsUnseen rows
1modestmodest
4betterbest
20nearly 100 %lower again

Training accuracy can only rise. Test accuracy rises, stalls, then falls. The widening gap is the picture of overfitting.

  • max_depth limits how many questions the tree may ask in a row.
  • Without a limit it keeps splitting until nearly every training example has a verdict of its own.
  • A small tree shades one broad area: "cold days are busy". An unlimited one shades a bar code of slivers.
  • A deep enough tree can end up below the baseline on new data while scoring 99 % on its own.

Concept 5, continued

Choosing the depth honestly

Which depth, then? Not the one with the best test score: that would use the test set to choose.

 all rows ──▶ training set ──▶ fit part          models are trained here
          │                └──▶ validation part  the settings are chosen here
          └──▶ test set                          the final model is measured here, once
  • The choice is part of the learning, so it gets its own rows.
  • cross_val_score repeats the validation split several times, which shows how much one split's number can move by chance.

Concept 6

Beyond accuracy

The confusion matrix

Is 1Is 0
Predicted 1true positivefalse positive:
a false alarm
Predicted 0false negative:
a miss
true negative

Two more scores

ScoreFormulaQuestion
precisiontp / (tp + fp)when it says 1, how often is it right?
recalltp / (tp + fn)of the real 1s, how many does it find?
  • Precision is about false alarms; recall is about misses. They pull against each other.
  • Which matters more depends on what each mistake costs: a business decision, not a setting.
  • "Always 0" has recall 0 and undefined precision. With a rare class, never compare accuracy alone.

confusion_matrix(y_test, predictions) is laid out [[tn, fp], [fn, tp]].

Concept 7

Leakage

A feature leaks when it carries information that would not be available at the moment a real prediction is needed.

What it looks like

A column filled in after the outcome. An average that includes the row itself. A statistic computed over training and test rows together.

The symptom

A score too good to be true. The model seizes on the leak, scores brilliantly, and is worthless in use.

  • Read what the model uses: print the tree.
  • Ask of every feature: would I have this value on the day?
  • Compute anything learned from data, including fill values and group averages, from the training rows only.

Worked example — notebook 1

Staffing a coffee cart

A year of records: temperature, rain, weekend, and whether the day was busy.

95 %

A tree trained and scored on all the days.

65 %

The same kind of tree, scored on days put aside.

57 %

Always saying "quiet".

  • The model has earned eight points, not ninety-five.
  • A tree of depth two says cold days are busy, which the owner can check against experience.
  • Predicting "quiet" on a busy day means a queue down the street; "busy" on a quiet day means paying someone to stand around. Recall and precision put numbers on those two.

Worked example — notebook 2

97.5 % accurate and useless

1.3 million consumer complaints; one in forty is answered late. An agency would like to flag those on arrival.

ModelWhat happened
Always "on time"97.5 % accurate.
Product, channel, dateAlso 97.5 %, and flags nothing: recall 0.
Adds the company's response categoryPerfect precision. One value is "untimely response", written after the outcome. A leak: discard.
Each company's past share of late answers, from training rows onlyAccuracy 97.5 % → 97.9 %. Recall 0 → about 0.3, with seven alarms in ten real.
Trained on earlier years, tested on later onesPrecision falls to about five in ten. The random split had been optimistic.

Most of the improvement came from the choice of feature, not from the algorithm, which is the usual experience.

Reporting

What a model is not, and what to report

It finds what goes together

Not what causes what. Does a restaurant close because it lists no hours, or does a closed restaurant's listing lose its hours?

It knows only the world it was shown

It predicts the future only as far as the future resembles the past.

It has no judgement about its inputs

It will use any column that helps.

  • the task, the target, and how the classes divide; the features, and what was left out and why;
  • the split and its seed; the baseline; how settings were chosen;
  • the result on the test set: accuracy, precision, recall; how steady it is across seeds;
  • what the model cannot tell you.

To take away

Key points

  • The examples are the input; the rule is the output.
  • Put the test rows aside first, and use them once.
  • Compute the baseline before any model.
  • Watch training and test accuracy together: the gap is overfitting.
  • Choose settings on a validation set, never on the test set.
  • Report which mistakes, not only how many.
  • A score that is too good is a warning. Look for a leak.

Now: hands-on

Over to the notebooks

Folder 13-Intro-Machine-Learning — work them in this order:

1Learning from Examples

Concepts

The coffee cart: features, the split, the baseline, a tree, overfitting, and the confusion matrix. Four exercises.

2Late Answers

Worked example

A model that is 97.5 % accurate and useless, and how to do better, in nine steps. Run it on ARC.

3Reference

Look things up

scikit-learn calls and the modelling workflow to keep open while you work.

As you work, ask of every score: compared with what, and on which rows?
Homework: Homework 12: Does It Beat Guessing?

◀ Slides