The Final Test: One Honest Number
Once a model has been chosen, one question is left: how well will it do on examples it has never seen? Every score so far was used to make a choice, and a score used to pick the winner tends to make that winner look a little better than it is. The test set, held back from the start, gives an answer that no choice has touched. Getting that answer means training the chosen model one last time, measuring it once, and reading the result against what cross-validation predicted; the model's probabilities then show which cases to act on first.
The final fit: learn from every row that is not test data
While you compared models and settings, every model was trained on only part of the rows that are not test data: the training rows, scored on the validation rows, or, with cross-validation, all folds but one, scored on the fold held out. Those models were only there to score the choices, and they are thrown away. Once the choice is made, no rows have a measuring job left except the test rows. The training and validation rows are still good examples with known answers, and a model usually predicts a little better when it learns from more examples.
So the chosen model, with the settings you picked, is trained once more on the training and validation rows together. This is the final fit. The test rows stay out of it, exactly as they stayed out of every step before.
- every row that is not test data
- training rows
- validation
- test rows
- final fit
- scored once, never learned from
In code, the final fit joins the two parts and calls fit again. pd.concat stacks tables (or columns) one under the other. Join the features and the answers in the same order, so that every row keeps its own answer:
import pandas as pd
X_dev = pd.concat([X_train, X_val])
y_dev = pd.concat([y_train, y_val])
chosen_model.fit(X_dev, y_dev)Calling fit on a model that was already trained does not add the new rows to what it learned before. It starts over: the old result is thrown away and everything is learned again from the rows you pass. When the model is a pipeline, that includes the preparation steps, so the list of category values and the scaling are also learned again from the combined rows. With the same fixed seed, the same rows give the same model on every run.
Refitting on the validation rows is not leakage. Leakage means held-out rows reaching training while they are still supposed to measure the model. The validation rows have finished measuring; only the test rows still have a measuring job, and they are never passed to fit.
True or false?
Training the chosen model again on the training and validation rows lets information leak from the test set.
False. The test rows are not part of the final fit at all. The validation rows have already done their job of comparing choices, so learning from them now is fair.
If the chosen model is a pipeline, its preparation steps are learned again from the combined rows during the final fit.
True. Fitting a pipeline fits every step in order, so the encoder and the scaler are learned from the training and validation rows together, and still never from the test rows.
Calling fit a second time keeps what the model learned the first time and adds the new rows to it.
False. A second call to fit starts over. The model learns only from the rows passed in that call.
One measurement on the test set
The trained model is now scored on the test rows. For a classifier, score gives the accuracy: the share of rows whose predicted answer is right.
test_accuracy = chosen_model.score(X_test, y_test)
print(round(test_accuracy, 3))This number is your estimate of how the model will do on new data, and it can play that role for one reason: nothing about the model was decided by looking at these rows. The settings came from cross-validation, the model was trained without them, and the test rows were only read at the very end.
That is why the rule is to measure the test set once, with the final model, and change nothing afterwards. Suppose the score disappoints. You try a different depth and score again, then another model and score again, and you keep the best. Now the version you keep was chosen because it did well on these particular rows. Part of that is real skill, and part is the luck of which rows happen to be in the test set. The winner's score carries that luck with it, so it is higher than what the model will reach on truly new rows. The test set has turned into one more validation set, and nothing is left to give an honest number.
- Choose with CV
- Final fit
- Score test rows
- Report the score
- Change the model
- Choose with CV to Final fit
- Final fit to Score test rows
- Score test rows to Report the score: honest
- Score test rows to Change the model: after seeing it
- Change the model to Final fit: score again
One measurement does not mean one metric. You can compute accuracy, precision and recall from the same test predictions; together they describe the same final model. What makes the result dishonest is a decision about the model that follows from it.
True or false?
Computing precision and recall on the test set, as well as accuracy, breaks the rule of measuring the test set once.
False. Several metrics from the same predictions of the same final model are still one measurement. The rule is broken only when the model changes because of what the test set showed.
If you keep changing a model until its test score looks good, that final score is likely higher than what the model will reach on new data.
True. The version you kept was picked partly for its luck on these particular rows, and that luck does not carry over to new rows.
Comparing the test score with the cross-validated estimate
Before the test, cross-validation already gave a forecast. The mean of the fold scores was the estimate of how the model would do. Their spread, how far the fold scores typically sit from that mean, showed how much a score moves just because of which rows land in the part being scored. The test set is one more part of that kind, so its score moves by about the same amount. The useful question is therefore not whether the test score equals the mean, but whether it falls where the spread said it could.
- 0.70
- 0.75
- 0.80
- accuracy
- mean ± spread of the folds
- test A: 0.79, agrees
- test B: 0.72, a surprise
In this picture, five fold scores between 0.785 and 0.81 give a mean of 0.80 and a spread of about 0.01. A test score of 0.79, like test A, sits inside that band: the result agrees with the forecast. That is the outcome to hope for, and it means the process held up: the estimate you made the choice with was a fair one, and 0.79 is the number to report.
A test score that lands a little below the mean is normal. The setting you kept was the one with the best cross-validated score. The best of several scores tends to be slightly lucky, so the mean you chose by is itself a little optimistic. The final model also learned from more rows than each fold's model did, which can push the other way. Small differences in either direction are not worth explaining.
A score far outside the band, like test B at 0.72, is a surprise, and it says something about the process rather than about the model alone. A far lower score often means the estimate itself was flattered: for example, a preparation step fitted on all the rows used for cross-validation before they were cut into folds, so that each fold's held-out rows had already shaped it, or settings that happened to suit those particular folds. It can also mean that the test rows differ from the rest, for example because they come from a later period. A score far higher than the forecast deserves the same suspicion. And a leak that also reaches the test rows, such as a feature that is only known after the answer, makes the estimate and the test score agree while both are too good; only new data in use would show it.
In both cases the honest response is to report the number as it is and look for the cause in the process. Tuning the model until the test score looks better is the trap from the previous section. If you do find and fix a real mistake, the test set has already shown you its answer, so say so when you report the new score, and use fresh rows for the next final test when you can.
True or false?
A test score slightly below the cross-validated mean, inside the spread, means the model failed the final test.
False. The spread says scores move by about that much from one set of rows to another. A result inside it agrees with the forecast.
A test score far above the cross-validated mean is also a reason to check the process.
True. A result far outside the spread in either direction means something differs from what the estimate assumed, such as leakage or test rows unlike the rest.
Ranking cases by their predicted probability
A test score says how good the model is overall. In use, the question is usually more practical: a team can only act on so many cases, so which ones come first? Suppose a subscription service can phone 3 customers this week to offer help before they leave. A bare yes or no from predict does not order the customers; the probabilities do.
predict_proba returns one column per possible answer, and each row adds up to 1. A trained model keeps the answers it learned, in sorted order, in its attribute classes_, and the columns follow that order. With the answers "No" and "Yes", the probability of "Yes" is therefore the second column. Print classes_ to confirm the order rather than assume it:
proba = chosen_model.predict_proba(X_new)
print(chosen_model.classes_) # ['No' 'Yes']
p_leave = proba[:, 1] # the "Yes" column
ranked = X_new.assign(p_leave=p_leave)
ranked = ranked.sort_values("p_leave", ascending=False)
print(ranked.head(10))assign returns a copy of the table with a new column added, here the probability of leaving. sort_values orders the rows by a column, from smallest to largest unless you pass ascending=False, and head(10) shows the first 10 rows of the result. The top of the list is where the model is most confident that the customer will leave:
| Rank | Customer | Probability of leaving | This week |
|---|---|---|---|
| 1 | C-104 | 0.91 | phone |
| 2 | C-087 | 0.84 | phone |
| 3 | C-215 | 0.77 | phone |
| 4 | C-032 | 0.58 | later |
| 5 | C-150 | 0.41 | later |
| 6 | C-009 | 0.12 | no call |
The ranking also frees the decision from the default rule of predicting the more probable answer. With room for 3 calls you take the top 3; with room for 50 you go further down the same list, even below 0.5. The list stays the same, only the cut moves.
A probability is the model's confidence, not a certainty. When a model's probabilities match how often the answer really occurs, so that about 80 out of 100 cases given 0.8 really have that answer, the model is called well calibrated. Logistic regression often comes close to this, but it is not guaranteed. Ranking asks for less than that: it needs the cases in the right order, not the probabilities exactly right, so a model whose probabilities run a little high or low can still rank well.
True or false?
For a yes-or-no question, predict_proba returns a single probability for each row.
False. It returns one column per answer, in the order of classes_, and each row adds up to 1. You pick the column of the answer you care about.
Ranking cases by probability can be useful even when the probabilities themselves are a little off, as long as their order is right.
True. Deciding who comes first only depends on the order. Any change that keeps higher probabilities higher keeps the same ranking.