Spot Overfitting

A model is only useful if it predicts rows it has never seen, yet the easiest score to compute is the one on the rows it learned from. A model that learns its training rows too closely scores well on them and worse on new rows, and one that learns too little scores poorly on both; only comparing a training score with a validation score shows which of the two is happening.

How much a model can learn

Every model has a limit on how much detail it can pick up from its training rows. That limit is called model complexity. A simple model can only learn a broad rule; a complex one can learn fine distinctions, down to single rows.

For a decision tree, the complexity is set mainly by its depth: the number of yes-or-no questions on the longest path from the top of the tree to an answer at the bottom (a leaf). A tree of depth 1 asks one question and splits the rows into two groups. Each extra level can split every group in two again, so a tree of depth \( d \) can have up to \( 2^d \) leaves: 8 at depth 3, 32 at depth 5, 1,024 at depth 10.

Depth 1: one question
  • Monthly contract?
  • Leaves
  • Stays
  • Monthly contract? to Leaves: yes
  • Monthly contract? to Stays: no
Depth 2: up to four leaves
  • Monthly contract?
  • Under 6 months?
  • High bill?
  • Leaves
  • Stays
  • Leaves
  • Stays
  • Monthly contract? to Under 6 months?: yes
  • Monthly contract? to High bill?: no
  • Under 6 months? to Leaves: yes
  • Under 6 months? to Stays: no
  • High bill? to Leaves: yes
  • High bill? to Stays: no

In scikit-learn the limit is the max_depth setting of DecisionTreeClassifier, chosen before training. Its default is None, which means no limit at all. The tree then keeps asking questions until every leaf holds rows with a single answer. It stops early only where a group cannot be split: with the default settings, a group of a single row, or a group whose rows look the same in every feature but have different answers. A tree created with no settings is therefore the most complex tree there is.

from sklearn.tree import DecisionTreeClassifier

small_tree = DecisionTreeClassifier(max_depth=3, random_state=0)
full_tree = DecisionTreeClassifier(max_depth=None, random_state=0)  # no depth limit, the default

More room to learn sounds like an advantage, and up to a point it is: a tree with a few more questions can capture a pattern that one question misses. The next section shows what happens past that point.

Learning the training rows instead of the pattern

Real data always holds some noise: answers that the features cannot explain. Two customers can look the same in every column, and one leaves while the other stays, for a reason no column records (a move to another city, a friend's advice). No model can predict that part, because it is not in the data.

A tree with no depth limit does not know which differences are pattern and which are noise. It keeps splitting until each small group is pure or cannot be split further, so it also builds questions whose only purpose is to separate one unusual row from its neighbours. Look at the small table below: the pattern is that customers on a monthly contract in their first months tend to leave, and one row breaks it.

Training rows with one exception
ContractMonths as customerLeft?
monthly2yes
monthly3yes
monthly4no (the exception)
monthly5yes
yearly3no
yearly30no

A deep tree can add the questions "more than 3 months?" and "fewer than 5 months?" just to put the exception in a leaf of its own, labelled "stays". On its training rows the tree is now right every time. But the next monthly customer at 4 months is more likely to leave, like the rows around them, and the tree predicts "stays". The extra questions describe one past customer, not customers in general.

This is overfitting: the model has learned its training rows, noise included, so closely that it scores very well on them and worse on new rows. It is not a bug in the library; it is what an unlimited tree does by design, and the scikit-learn documentation lists limiting the depth as one of the ways to prevent it.

True or false?

A model that is right on every one of its training rows has found the true rule.

False. A model that simply remembered every training row would also be right on all of them, and could still be wrong on new rows. A perfect training score says nothing about new rows.

A tree with no depth limit can give a single unusual training row its own leaf.

True. It keeps splitting while a group still mixes answers and can be split, so it adds questions until even an exception is separated from its neighbours.

An overfit model scores badly on its training rows.

False. The opposite: an overfit model scores high on its training rows. It is the score on new rows that falls behind.

The gap between two scores

Overfitting cannot be seen in the training score alone, because the training score only measures how well the model repeats what it has already seen. To see it, score the model twice. The first score is on its training rows: the rows passed to fit. The second is on its validation rows: rows held out from training and kept for comparing choices. For a classifier, score returns the accuracy, the share of rows it predicts right.

for depth in [1, 3, 5, 10, None]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
    tree.fit(X_train, y_train)
    train_score = tree.score(X_train, y_train)  # rows it learned from
    val_score = tree.score(X_val, y_val)        # rows it has never seen
    print(depth, round(train_score, 3), round(val_score, 3))

The loop trains one tree per depth and prints both scores, so you can watch them as the tree is allowed to grow. Its exact numbers depend on the data, but the shape is the same on almost every dataset, and the chart below draws that typical shape.

The training score keeps rising with depth, because every extra level lets the tree fit its own rows more closely. The validation score rises at first, while the new questions still capture real pattern, then levels off and starts to fall once the new questions mostly describe noise.

Typical shape as a tree grows (illustration)

Accuracy against Maximum depth

  • Training rows
  • Validation rows

The gap between the two curves is the sign of overfitting. A small gap means the model does about as well on rows it has never seen as on the rows it learned from. A gap that widens as the model grows means the extra complexity is being spent on memorising training rows.

Only the validation score estimates how the model will do on new rows, because only the validation rows were kept out of fit; to the model they are as new as tomorrow's customers.

That is also why every choice, such as which depth to keep, is made on validation rows. The test rows are never used for a choice; they wait for one final measurement. Even the validation score is slightly flattering once you use it: the depth you keep is the one that scored best, so its score was picked for being high. The untouched test rows give the honest number at the end.

True or false?

If the training score keeps rising as a tree grows deeper, the tree is getting better at predicting new rows.

False. The training score rises with depth almost by definition. Whether new rows benefit shows only in the validation score, which often falls once the tree is deep.

A training score far above the validation score is the typical sign of overfitting.

True. The model does much better on rows it has seen than on rows it has not, which means part of what it learned only holds for its own training rows.

The depth to keep should be chosen by the score on the test rows.

False. Test rows must never be used to make a choice, or their score stops being an honest estimate. Choices are compared on validation rows.

Too simple to learn the pattern

The left end of the same curve shows the opposite failure. A tree of depth 1, often called a decision stump, asks a single question. If the answer really depends on several features together, one question cannot capture it, and the tree makes many mistakes everywhere: on its own training rows as well as on the validation rows.

This is underfitting: a model too simple for the pattern, so that both scores are low and close together. A small gap here is no comfort, because the model is not memorising anything; it simply has not learned enough. The extreme case is a baseline that ignores the features and always gives the most common answer: it has no detail at all, and its two scores are both just the share of that answer.

Underfitting and overfitting are the two ends of one setting. Too little complexity and the model misses the pattern; too much and it learns the noise along with it. The depth worth keeping lies between them, where the validation score is at its highest.

Reading the two scores
What you seeTraining scoreValidation scoreDiagnosis
both low, small gaplowlowunderfitting: allow more complexity
both good, small gapgoodgooda good fit
training far above validationhighclearly loweroverfitting: limit complexity

True or false?

A model whose training and validation scores are almost equal can still be a poor model.

True. If both scores are low, the model is underfitting: a small gap only says it is not memorising, not that it has learned the pattern.

Underfitting is fixed by limiting the depth of the tree further.

False. An underfit model is already too simple. It needs more room to learn, such as a larger depth, not less.