Vocabulary for this course

The terms the chapters assume, in plain words. You can open this from any chapter.

accuracy
The share of predictions that are correct, counting every class the same.
additive
Built by summing separate contributions, so each part’s effect can be read on its own.
baseline
A reference score from a rule so plain it needs no learning, such as always naming the most common answer.
features
The input columns for one example — the numbers a model is allowed to read before it predicts.
fitting
Adjusting a model’s numbers so its predictions get closer to the answers in the training data.
generalisation
How well a model performs on examples it never saw while being fitted.
hypothesis class
The family of shapes a model is allowed to use, such as a straight line or a tree.
label
The correct answer for one example — what you want the model to predict.
loss
A single number measuring how wrong a prediction is; smaller means better.
metric
A single number used to judge predictions, such as the share answered correctly.
noise
Random variation in data that carries no real signal, which a model can mistake for a pattern.
optimiser
The procedure that changes a model’s numbers to make its loss smaller.
overfitting
When a model memorises accidental details of its training examples and does worse on new ones.
parameters
The numbers inside a model that fitting adjusts, as opposed to the inputs it reads.
regularisation
Any penalty or limit that discourages a model from chasing noise in its training examples. The aim is better performance on new data.
supervised learning
A setting where each example carries the answer you want the model to predict.
test set
Examples kept out of fitting, used to estimate how the model will do on data it has not seen.
training set
The examples a model is fitted on; a score there is not an estimate of performance on new data.
weights
The numbers a model multiplies each input by before adding the results together.

Classical machine learning

Decision trees

A tree asks a sequence of yes/no questions. Gini or entropy picks each split, and depth is the regularisation that keeps it honest.

Part 6 of 10

Beginner16 min readBack to Courses

Recursive partitioning

A decision tree splits the feature space into rectangles. Each internal node asks whether one feature is above or below a threshold. Each leaf predicts the majority label of the training rows that reached it. The boundary is a staircase of axis-aligned cuts, not a smooth curve.

The tree is built greedily. At each node, try every feature and every candidate threshold. Score the split and keep the best one. Then repeat on the two children. Greedy means the tree never revisits an early choice. A locally good split can block a better one two levels down. That is a limitation, and it is also what makes the algorithm fast.

The greedy choice is not the only way to build a tree. It is the one that keeps the algorithm tractable. Trying every possible tree and picking the best would take exponential time. The greedy tree is a heuristic, a rule of thumb rather than a guarantee. Its quality depends on the data and on the rule used to score splits. Random forests and boosted trees build many such trees because one greedy tree is unstable.

Impurity

A split is good if the children are purer than the parent. Purity here means how much a node leans toward one class. Gini impurity is one minus the sum of squared class proportions. It is zero when a node is pure and highest when the classes are evenly mixed. Entropy is the other common measure. Information gain is the drop in entropy. The two measures usually agree on which split is best.

The score for a candidate is the weighted average of the children’s impurity. The weights are the share of rows that land in each child. A split that isolates one row perfectly but leaves the rest mixed is not necessarily good. The large child still carries most of the uncertainty. The parent’s impurity minus this weighted score is the gain.

A tree with a depth limit

from sklearn.tree import DecisionTreeClassifier

model = DecisionTreeClassifier(
    criterion="gini",
    max_depth=3,
    min_samples_leaf=5,
    random_state=0,
)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))

Score every split

Compute the parent impurity and the weighted score for each candidate, then add a threshold at 2.25 and explain why it ties with 2.5.

Output
Click "Run" to execute your code

Overfitting and pruning

An unconstrained tree can keep splitting until every training row is its own leaf. That gives perfect training accuracy and a boundary that follows every noisy point. The tree has low bias and high variance. It fits the sample closely, but a different sample would produce a different set of cuts. Depth, minimum leaf size and minimum impurity decrease are the usual pre-pruning controls.

Post-pruning grows a full tree and then removes branches. A branch goes if it does not pay for itself on validation data. Cost-complexity pruning is the standard version. It penalises the number of leaves and chooses the penalty by cross-validation. Either way, the goal is the same. Stop before the splits describe the sample rather than the pattern.

Cost-complexity pruning has a clear objective. It minimises the training impurity plus a penalty times the number of leaves. The penalty is chosen by cross-validation. The tree is then pruned against held-out data rather than against the training set. That is the same discipline as early stopping, applied to a structure instead of a number of epochs.

A tree is unstable. Change one training row and a split near the root can move, which changes every threshold below it. That is why a single tree is a good explanation and a poor production model compared with an ensemble of them.

Strengths and limits

Trees need no feature scaling. With the right encoding they handle mixed numeric and categorical columns. They can capture interactions that a linear model would need to be told about. A shallow tree can be read aloud as a set of rules. That is valuable when someone has to approve the decision. Training is fast and prediction is a sequence of comparisons.

The axis-aligned boundary is also the weakness. A diagonal relationship needs many staircase steps. A smooth function is approximated crudely. Trees cannot extrapolate. A leaf predicts a training average, so a value beyond the observed range gets the same answer as the edge of the leaf. Ensembles fix much of the variance. The cost is the single tree’s readability.

The split rule also has a subtle bias. Gini and entropy favour features with many distinct values. More thresholds give more chances to find a good cut. So a random forest’s feature importance can be misleading when the columns have different numbers of distinct values. Permutation importance, measured on held-out data, is a better check on whether a feature actually matters.

Depth buys training accuracy

Run depths one through four, then explain why the training score rises to one while the test score stays at seven-eighths.

Output
Click "Run" to execute your code

Check what you learned

One question at a time. A wrong answer explains itself — take another go.

Part 1 of 5

What is Gini impurity when a node contains only one class?