🏅 Model Evaluation
By now you have met a whole range of models, from naive Bayes and nearest neighbors to neural networks and large language models. With each of them, the same question comes up sooner or later: how well does this model actually work? That seems a simple question: let the model make predictions and count how many it gets right. But that simple measurement hides three pitfalls, and each of them can make a bad model look excellent.
- 🙈 You measure on the wrong data. A model that memorized its training examples scores perfectly on them, and that says nothing about new cases. That is why you measure on data the model never saw, and keep that data strictly apart from every choice you make.
- 🎯 You measure the wrong number. You can "predict" a disease that affects 1 in 10,000 people with 99.99% accuracy by always saying "not sick". Which number does tell you something depends on which mistakes matter to you.
- 🎲 You measure only once. A single score on a single random split of your data can be a lucky or an unlucky one. Only when you measure several times do you know how reliable your number is.
This chapter examines the three pitfalls in that order, and ends with the question of what you do when there are no correct answers to compare with, as with a chatbot or an image generator. Everything else that can go wrong when you build a real AI system is covered in the next chapter, on AI challenges.
🎛️ Overfitting & underfitting
The easiest measurement is also the worst one: look at how well the model scores on the data you trained it with. With nearest neighbors you already saw why that says nothing: with , the nearest neighbor of every training point is the point itself, so the model is guaranteed to score 100% on its own training data. And that does not only happen with the nearest-neighbor algorithm. Any model that is flexible enough can memorize its training data instead of understanding the pattern in it.
🧸 Not too simple, not too complex
When you train almost any model, you run into the same dilemma: how closely should the model follow the training data? If it follows the data too loosely, it is too rigid to capture the pattern: we call that underfitting. If it follows the data too closely, it also memorizes every bit of noise and every small measurement error instead of understanding the data: we call that overfitting.
You are looking for the Goldilocks zone in between: a model that is neither too simple nor too complex, but fits the data just right.
🪫 Underfitting: too simple
Underfitting occurs when a model is too simple to capture the structure in the data. The model performs poorly on both the training data and new data, because it cannot represent the relevant patterns.
Take the student rooms from the regression chapter (a kot, as students in Leuven call such a room), and suppose that the true relationship between floor area and rent is slightly curved: small rooms are relatively expensive (fixed base costs), medium-sized rooms are the cheapest per m², and very large rooms become more expensive per m² again (the luxury segment). A straight line can never follow that curve, however you turn it: it does poorly on the training data and on new data alike. So you recognize underfitting by a model that does not even predict its own training data well.
🕸️ Overfitting: too complex
Overfitting occurs when a model follows the training data too closely, including noise and random variations, so that it generalizes poorly to new, unseen data. The model has effectively "memorized" the training data instead of discovering the underlying pattern.
A very flexible model can pass through every data point and so gets a perfect score on the training data. But as soon as you give it new data, it does poorly: it has "remembered" the random variations in the training data instead of learning the real pattern. You recognize overfitting by a large gap between an excellent score on the training data and a poor score on new data the model never saw. So on the training data alone you never see it: that is exactly where the overly complex model scores best.
⚖️ Finding the balance
To see that balance, we use polynomial regression: by using not only but also , , ... as features, a regression model can fit curves, and the degree of the polynomial is a dial for the complexity of the model. In the demo below, data is generated with a certain complexity (the degree of the true pattern), and a model with an adjustable complexity (the degree of the polynomial) is fitted to it. The filled points are the training data. The hollow circles are test data: points the model was not trained on, but that you hold back to check whether the model also works on new data.
Set the model complexity far below the data complexity, and you see underfitting: both the training error and the test error stay high. Set it far above, and you see overfitting: the training error drops to almost zero, but the test error shoots up.
🔄 Overfitting in classification
Overfitting is not limited to regression: a classification model can become too flexible as well. Give logistic regression polynomial features, and the decision boundary no longer has to be a straight line, but can follow curves and waves. Here too, too much flexibility leads to overfitting: an overly complex decision boundary winds around every individual data point instead of following the general pattern.
Below you see the same training data twice, classified by logistic regression; the background color shows which class the model predicts. Compare the straight boundary with the one of degree 12, and then turn on Show new points: points from the same two point clouds that neither model ever saw.
- Class 0
- Class 1
- Decision boundary
- Predicted wrong
56 of 60
turn on the new points
A straight boundary separates the two clouds. Four training points lie on the wrong side (circled in red), but the general pattern is right.
The goal of machine learning is not to fit the training data perfectly, but to generalize well to new, unseen data. You look for the middle ground between too simple and too complex, and that holds for every form of machine learning:
- 🌳 In decision trees: a tree that is too deep can overfit
- 🧠 In neural networks: too many neurons or layers can overfit
- 👥 In k-nearest neighbors: a that is too low leads to overfitting, a that is too high to underfitting
The lesson for measuring is clear: the score on the training data says nothing, because there the model that memorized the most wins. You judge a model on data it never saw during training. Which data you keep apart for that, and how you keep that data from creeping into your choices after all, is what we look at in the next section.
✂️ Data splits
So you judge a model on data it never saw. That means you do not give the model all your labeled data, but keep part of it apart. How many parts you need depends on how many choices you still want to make along the way.
📂 Training, validation, test
With nearest neighbors you already kept part of the fruit data apart to choose : the model only got the training set, and on the points you kept apart you read off which worked best. Why is that score not good enough as a final score? Because you chose precisely on the basis of those points: the setting that scores best there is tuned a little to those points, so its score is somewhat too optimistic. For a fair final score, you need points that played no part in any choice. That is why you split the data into three parts, each with its own purpose:
- 📚 Training set: the study material. The model learns from this data.
- 📝 Validation set: the mock exam. During development, you test the model on it to tune hyperparameters. If the model keeps scoring better on the training set but worse on the validation set, it is overfitting.
- 🎓 Test set: the final exam. You keep it under lock until the very last moment, and only when you are fully satisfied with your model do you measure on it, once, for a fair final score.
A hyperparameter is a setting you choose before you train the model. Hyperparameters influence how the model learns and performs, but they are not learned directly from the training data. Compare it with the settings on a camera: you choose the exposure and the focus yourself before you take a photo, not afterward.
Examples: the number of neighbors in nearest neighbors, the depth in decision trees, the learning rate in neural networks.
How large each part is depends on how much data you have: 70% training, 15% validation and 15% test data is a common split, and with larger datasets it is sometimes 80/10/10. Go through the four steps below with Next step, and switch between both splits:
- Training set: 700 (70%)
- Validation set: 150 (15%)
- Test set: 150 (15%)
Each dot stands for 50 examples.
Split: You divide your 1,000 labeled examples at random over three sets.
Never use the test set to make choices. Every time you look at your test result and adjust your model, information "leaks" from the test set into your model, and your final score becomes less fair. Below you see how that leak arises and how quickly it inflates your score.
🚰 Data leakage
Data leakage occurs when information from your test or validation set ends up in your training process. It is one of the most common mistakes in machine learning, and it is treacherous: your model seems much better than it is, and you only notice once it is in use. Common causes:
- 🚫 Overlap between sets: the same data points end up (by accident) in both the training set and the test set, for example because a photo appears twice in your dataset.
- 🚫 Information from the future: with time-dependent data (such as stock prices), you use information during training that only became available later.
- 🚫 Preprocessing on all the data: to scale your features, you calculate the mean and the spread on the full dataset, test set included, instead of only on the training data.
- 🚫 Test data in an earlier training phase: a language model first learns from texts on the internet and is later tested with a benchmark whose questions were already on the internet.
- 🚫 Tuning on the test set: you try setting after setting and each time keep the one that is best on the test set. That seems harmless: you are not training on the test set, are you? Yet it is a leak, and the sneakiest of them all.
You understand that last one best by trying it yourself. In the demo below, the model is a straight line that separates two classes, and every try is a new variant with other settings. The two classes overlap so much that even the best possible line gets only about three in four points right, and the variants are all of that caliber. Click 1 try about ten times (or 10 tries once): each time, the demo keeps the variant with the highest score on the test set, exactly what you would do if you tuned on the test set.
- 📈 The solid line is the score of your best variant on the test set. It climbs with every try that sets a new record, and by about fifty tries it has reached 90% on the first dataset.
- 📉 The dashed line is the score of that same variant on new data. It stays around 70%. The difference is the leak: you have not found the best variant, but the variant that happens to fit those twenty test points best.
- 🔢 Set the number of points per set to 200 and try again: the leak becomes much smaller. A larger test set leaks more slowly, but it keeps leaking as long as you make your choices on it.
- ✅ Finally, pick the best variant on a separate validation set, again with 20 points: the validation score climbs too, but the test set, which never took part in the choice, stays close to the score on new data. That is exactly why you need three sets.
Sometimes a test set happens to be hard or easy for all variants, and the leak looks smaller or larger than it is. That is the chance in the split itself, the third pitfall, which we come back to in the section on cross-validation.
🎯 Evaluation metrics
You have a test set, and your model gives a prediction for every test point. Compare those predictions with the true labels, and you have the raw material for a score. But which score? Summarizing quality in one number is harder than it seems, and the wrong number gives you a false sense of success.
💯 Accuracy
Accuracy is the percentage of correct predictions on the test set. It is the most intuitive measure, and the one you have used everywhere so far, but it can be misleading. Suppose a disease affects 1 in 10,000 people. A model that always predicts "not sick" has an accuracy of 99.99% and is still completely useless: it does not find a single sick person. Such a skewed distribution is called class imbalance, and it is common: fraud, rare diseases, defective parts. For such problems you need measures that tell the kinds of mistakes apart more precisely.
🚦 False positive vs false negative
Take a spam filter. The label the system is looking for (spam, disease, fraud) we call the positive label; the other one is the negative label.
The word "positive" is confusing here, because it sounds like something good. In a medical test, a "positive" result means that the test found the disease: bad news for the patient. The same goes for a spam filter: "positive" means that the filter detected spam. So "positive" does not mean "good", but "the detector goes off".
If you set every prediction next to the true answer, there are four possible outcomes. Two of them are correct: a true positive (TP) (spam in the spam folder) and a true negative (TN) (an ordinary email in your inbox). The other two are mistakes. With a false positive (FP) the system says "yes", but the true answer is "no": in statistics a type I error. With a false negative (FN) the system says "no", but the true answer is "yes": a type II error.
Which of those two mistakes is worse depends entirely on the application. Choose an application below and see what each outcome means there, and which mistake weighs heaviest:
Spam filterpositive = spam
True positive (TP)
Spam ends up in the spam folder, as it should.
False positive (FP)
Type I error
The invitation to your job interview disappears into the spam folder.
False negative (FN)
Type II error
An advertising email slips through to your inbox.
True negative (TN)
An ordinary email lands in your inbox.
A false positive weighs heaviest here. Better the odd advertisement in your inbox than a missed job interview.
So the same mistake can be harmless in one application and disastrous in another. That is why you need measures that weigh each type of mistake separately.
🗂️ Confusion matrix
If you count the four outcomes on a test set whose correct labels you know, you get four numbers, in the same four cells as above: a confusion matrix. The top row holds everything the model called positive, the left column all the actual positives. From those four numbers you calculate the most important measures:
- 🎯 Accuracy = : what fraction of all predictions was correct?
- 🧪 Precision = : of everything the model called positive, how much was really positive? "Of all the emails in the spam folder, how many were really spam?"
- 📢 Recall = : of all the actual positives, how many did the model find? "Of all the spam, how much was stopped?"
- ⚖️ F1 score = : the harmonic mean of precision and recall, useful when you want one number that keeps both in balance, especially with class imbalance. The model that always says "not sick" has a recall of 0 and therefore also an F1 score of 0.
Drag the green rectangle(s) below to classify points, and watch the confusion matrix and the measures change live. Points inside the rectangle are predicted positive, points outside it negative.
Then click the name of the dataset at the top of the demo and choose Class imbalance. In it, only 1 in 10 points is positive: a small group of pluses among nine times as many minuses.
- 🙈 Calling nothing positive: make the rectangle so small that not a single point is left in it. That is the model that always says "not sick": the recall drops to 0%, and yet the accuracy climbs to 90%.
- 🔍 Finding all the pluses: make the rectangle as small as possible, but with all the pluses in it. The recall climbs to 100%, but there are about as many minuses as pluses in your rectangle, so the precision is only about half. Meanwhile the accuracy stays around 90%, just as with the model that found nothing.
In the first dataset, with as many pluses as minuses, this was hardly noticeable: there you could catch all the pluses with barely a minus along with them. Here a few minuses soon lie around the outermost pluses, because there are so many more of them. The recall does not notice any of that, because it only counts the pluses. The precision, on the other hand, counts everything inside your rectangle, and next to only ten pluses, every minus that comes along weighs heavily. Finally, look for a rectangle that leaves a few pluses out but contains not a single minus: then you trade some recall for a precision of 100%.
If you have more than two classes, such as the three kinds of fruit in the confusion matrix for nearest neighbors, you treat each class in turn as the positive one and all the others together as the negative one: that way every class gets its own precision and recall.
🎚️ Threshold
Many models do not give a label but a probability, and only a threshold turns that into a decision: above the threshold you call something positive, below it negative. With naive Bayes and logistic regression you already saw that this threshold does not have to be 50%. The threshold is the knob with which you set the balance between the two kinds of mistakes:
- ⬇️ Low threshold = more positives. At 10%, almost everything becomes spam: you catch almost all spam (high recall), but you also throw away the email from your grandmother with her many exclamation marks (low precision).
- ⬆️ High threshold = more negatives. At 99%, almost nothing becomes spam: what ends up in the spam folder is almost certainly spam (high precision), but a lot of advertising slips through (low recall).
There is no perfect threshold that brings both mistakes to zero at the same time. It is a trade-off based on the cost of each mistake.
Move the threshold in the demo below and watch the confusion matrix and the four measures move along with it.
In short: every measure highlights a different aspect. Accuracy is misleading with class imbalance, precision punishes false positives, recall punishes false negatives, and the F1 score balances those two in one number.
Which measure fits each scenario best? Sort the AI applications below into the right category.
📈 ROC curves and AUC
A receiver operating characteristic (ROC) curve shows all possible trade-offs between the percentage of true positives and the percentage of false positives as you move the threshold.
- ↔️ X-axis: the false positive rate (FPR) . Of all the actual negatives, what percentage is wrongly predicted as positive?
- ↕️ Y-axis: the true positive rate (TPR), also called recall (or sensitivity), . Of all the actual positives, what percentage is correctly found?
The key question is: "how many extra false alarms do I accept to find more of the real cases?"
A perfect classifier passes through the point (0, 1): 0% false positives and 100% true positives. A random guesser has an ROC curve that forms a diagonal line from (0, 0) to (1, 1): the percentage of false positives is then equal to the percentage of true positives.
Below you can change the threshold for different models and watch the number of true positives and false positives change. In the confusion matrix you see the four key numbers change with this threshold. In the metrics panel you see how the different scores move along.
Try to find thresholds by hand that give a high precision, a high recall or a high F1 score. You can also optimize the metrics at the bottom right by letting the "max" button adjust the threshold automatically.
Interpreting an ROC curve:
- 🟢 Closer to the top left corner = better (high true positive rate, low false positive rate). The top left corner is also called "ROC heaven": you want your model to get as close to it as possible.
- ⚪ On the diagonal = no better than random guessing, because then you have the same rate of false positives as of true positives.
- ⛰️ Area under the curve (AUC) = a summary of the model's performance across all decision thresholds: the larger the area, the better the model (1.0 = perfect, 0.5 = random). A larger AUC means a higher true positive rate at a lower false positive rate.
🎲 How reliable is your score?
You now have a fair test (the test set) and a suitable score (for example the accuracy or the F1 score). Suppose your model scores 87%. How sure are you of that number? The test set is a random sample from your data: had you split differently, it would have held other points, and the score might have been 80% or 92%. With a small dataset that chance weighs heavily, and there is another catch: every point you keep apart for testing is a point the model can no longer learn from.
🔁 K-fold cross-validation
K-fold cross-validation tackles both problems at once. The idea in one sentence: you cut your data into pieces and let each piece play the role of test set in turn, while you train on the other pieces. That way every data point is tested exactly once, and you get not one score but scores, whose average depends much less on chance.
- ✂️ Split the data into pieces of equal size, the folds.
- 🔴 Keep one fold apart as the test fold.
- 🟢 Train on the other folds and measure the accuracy on the fold you kept apart.
- 🔄 Rotate: repeat steps 2 and 3 until every fold has been the test fold exactly once.
- 📊 Average the accuracies into one final score.
See the rotation in action: in the demo below, the strip is the fruit dataset from nearest neighbors (every dot is a piece of fruit) and every block is a fold. Play the rounds: the red test block moves one block along each time, and after every round a bar is added with the accuracy of that round, measured with 3 neighbors. At the end, the average of all rounds appears, followed by a ±: that number (the standard deviation) tells you how much the rounds differ from each other.
Look at the five rounds: the scores range from 33% to 83%, while the model and the data are the same every time. If you split only once, you report any one of those numbers, without knowing whether you were lucky or unlucky. The average with the standard deviation next to it, 63% ± 22%, tells the whole story: on new pieces of fruit this model scores about 63% on average, but with only thirty pieces of fruit that number fluctuates a lot.
The standard deviation indicates how far the values lie from their mean on average: the smaller the standard deviation, the closer together the values lie. For example, 85 and 87 lie closer to their mean of 86 than 76 and 96 do, so they have a smaller standard deviation. A result such as "63% ± 22%" means: 63% on average, but the individual rounds typically deviate from that by about 22 percentage points.
🔟 Number of folds
Common values are and . More folds means a larger training set per round (the model learns from almost all the data), but also more rounds and so more computing time, and smaller test folds whose score per round is more erratic. In the demo above, switch between 3, 5 and 10 folds: with ten folds of three pieces of fruit, a round can only be 0%, 33%, 67% or 100%, and yet the average comes out close to the one with five folds. The extreme case is leave-one-out (): in every round you leave out exactly one data point as the test and train on all the others. That makes the most of the data, but takes as many training rounds as you have data points.
↔️ Calculating the mean and the standard deviation
Call the accuracy of round (with ) . The mean accuracy of the five rounds above is then:
For the standard deviation , you add up the squares of the deviations from that mean, divide by and take the square root:
Dividing by instead of by corrects for the fact that you estimated the mean from the same five numbers; for a large that makes hardly any difference.
🔧 Choosing hyperparameters with cross-validation
Cross-validation is also the standard way to choose hyperparameters without touching the test set: for every setting you compare the average score over the folds, instead of the score on a single validation set. That way it replaces the validation set, and you only have a training part (on which you cross-validate) and a test set (which you leave alone). Below, the k-nearest neighbors algorithm is evaluated on the fruit dataset with cross-validation; with 5 folds and 3 neighbors you see exactly the same rounds as in the demo above. Click the dots or the arrows to see which points serve as the test fold (fruit in a dashed circle) and which as the training set (fruit without a circle), and compare the average accuracy for different numbers of neighbors.
Pay attention to the ± after each average: the differences between the numbers of neighbors are smaller than the spread of the rounds, so with only thirty pieces of fruit you cannot establish which setting is really the best. More data makes both the model and the measurement more reliable.
The k in k-fold cross-validation is not the same as the k in k-nearest neighbors: one is the number of folds you split the data into, the other the number of neighbors that vote on the label. It is pure coincidence that both techniques use the same letter.
🔬 The complete evaluation workflow
Putting it all together, a fair evaluation looks like this:
- ✂️ First split off the test set and put it away. It takes no further part in anything.
- 🔁 Choose hyperparameters with cross-validation on the rest of the data, the training data.
- 🏋️ Train the final model with those settings on all the training data.
- 🏅 Measure once on the test set, and report that score together with the spread you know from the cross-validation.
- Training data: 800 (80%)
- Test set: 200 (20%)
Each dot stands for 40 examples.
Test set aside: First the test set goes aside, under lock: 200 of the 1,000 examples. They take part in nothing else.
Chance is not only in the split, by the way: neural networks start with random weights, so it is best to train several times with other starting values and other splits, and to average over those as well.
👥 Human evaluation
Everything in this chapter assumed an answer key: for every test point you knew the correct label, and the model got a score for how often it hit that label. For generative models, such as diffusion models and large language models, no such key exists. What is the correct answer to "write a poem about Leuven", or the correct image for "a cat on a bicycle"? There are three ways out of this, each with a price.
- 📊 Benchmarks with questions that do have a correct answer, such as multiple-choice questions, arithmetic problems or programming tasks whose code has to pass tests. They are objective and can be scored automatically, but they only measure what is measurable, and they suffer from the data leakage from above: if the questions are on the internet, the model may already have seen them during its training. In the chapter on large language models you saw examples of this.
- 👥 Human preferences. On Arena (external link), users see the answers of two anonymous models and pick the better one; thousands of those pairwise choices add up to a leaderboard. That comes closest to what you really want to know, but it is expensive, slow and subjective: people also prefer smoothly worded answers over correct ones.
- 🎲 Automatic measures such as perplexity, which measures how surprised a language model is by a text. Cheap and precise, but they tell you how predictable a text is, not how useful or correct it is.
Because human judges are scarce, researchers increasingly let a strong language model judge the answers of another model: LLM-as-a-judge. That scales endlessly, but such a jury has preferences of its own: it rewards longer answers and recognizes its own writing style. That is why you regularly calibrate such an automatic jury against human judgments: you also measure the measurement itself.
🧪 Hands-on
In this Jupyter notebook you evaluate models yourself in Python, with the scikit-learn library, on real hotel bookings: will a guest cancel? You run into each of the three pitfalls of this chapter and get out of them again, and for every study of your own model you find a short piece of code there that you can copy: comparing models, choosing a threshold based on what mistakes cost, analyzing errors and more.

🕹️ Demos
Experiment further with the full simulators and demos featured above.








🗣️ Feedback
Just like machine learning algorithms, we also love learning from your feedback to improve the course.
Let us know how informative and how difficult you found this chapter, and where it could be better.