Python + AI/ML · Tutorial 10 of 12
Model Evaluation: accuracy, precision and recall
By the FUTEAC Team · 24 November 2026 · 15 min read · Beginner
In short
A model is only as good as its test score, and one score can lie. Accuracy counts correct predictions, but on unbalanced data a lazy model scores 75 percent while catching nothing. Precision and recall score each category separately, and the gap between training and test scores shows overfitting. This tutorial measures all of them on the same twelve students.
- Accuracy is a starting point, never a verdict. It counts correct predictions and says nothing about which ones were wrong.
- The confusion matrix shows the shape of the mistakes. Four counts, and a lazy model is exposed at once.
- Precision and recall score each category separately. Precision asks, of the students the model called pass, how many really passed? Recall asks, of the students who really passed, how many did the model catch?
- A threshold trades precision against recall. Moving it catches more of one category and misses more of the other. There is no free move.
- The train/test gap is the overfitting check. A model that scores 1.0 on training data and 0.957 on test data memorised the training rows.
- Cross-validation repeats the test on different splits. One split can flatter a model, and three folds show how much the score wobbles.
- This tutorial feeds the AI & Machine Learning: First Steps course (/course/ai-ml-first-steps) and the Model Evaluation (/skill/model-evaluation) skill.
What does "good" mean?
"Good" depends on the job. A teacher who wants to find failing students early needs a model that catches fails. A spam filter needs a model that rarely bins real mail. Both models can be 90 percent accurate and still fail at their job, because accuracy counts all correct predictions together and never asks which ones were wrong.
Think of marking an exam. A student who scores 75 percent has answered three quarters of the questions right. That sounds solid. But if the exam had nine easy questions and three hard ones, and the student answered only the easy nine, the 75 percent hides a real gap: zero hard questions right. Accuracy does the same thing to a model. It reports the easy nine and stays quiet about the hard three.
The models and the data, one more time
The data is the same twelve students from items 67 and 68: hours studied, practice tests taken, and the exam score out of 100. Pass means a score of 50 or more. Nine students pass, three fail. The split is the same too, random_state=42, so the three test students are the same three: (9 hours, 4 tests, pass), (5 hours, 1 test, pass) and (1 hour, 0 tests, fail).
import numpy as np
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.model_selection import train_test_split
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8, 2, 5, 9, 10], dtype=float)
tests = np.array([0, 1, 1, 2, 2, 3, 3, 4, 0, 1, 4, 5], dtype=float)
score = np.array([38, 45, 52, 58, 63, 71, 76, 82, 41, 66, 88, 93], dtype=float)
passed = (score >= 50).astype(int)
X = np.column_stack([hours, tests])
X_train, X_test, y_train, y_test = train_test_split(
X, passed, test_size=0.25, random_state=42)
_, _, yr_train, yr_test = train_test_split(
X, score, test_size=0.25, random_state=42)
clf = LogisticRegression(max_iter=1000).fit(X_train, y_train)
reg = LinearRegression().fit(X_train, yr_train)Both models are already trained. The classifier sorts students into pass and fail. The regression model predicts the score. Everything from here on is measurement, not training.
Accuracy, and the lazy model that scores 75 percent
Accuracy is the share of correct predictions. For the classifier on the three test students, it is 1.0: three out of three right.
from sklearn.metrics import accuracy_score
print("Accuracy:", round(accuracy_score(y_test, clf.predict(X_test)), 3))Expected behaviour: the code prints Accuracy: 1.0. Now the lazy model from item 68, the one that predicts "pass" for every student, with no training at all:
lazy_test = np.ones_like(y_test)
lazy_all = np.ones_like(passed)
print("Lazy accuracy, test students:",
round(accuracy_score(y_test, lazy_test), 3))
print("Lazy accuracy, all twelve:",
round(accuracy_score(passed, lazy_all), 3))Expected behaviour: the code prints Lazy accuracy, test students: 0.667 and Lazy accuracy, all twelve: 0.75. The lazy model is right two times out of three on the test set, and nine times out of twelve on the full class. It learned nothing. It cannot tell a passing student from a failing one. But its accuracy is 75 percent, because nine of the twelve students pass and it guessed the majority answer every time.
That is the trap in one paragraph. Whenever one category outnumbers the other, accuracy rewards the lazy answer, and the more unbalanced the data, the better the lazy model looks. A spam filter that calls everything "not spam" is 95 percent accurate on an inbox that is 95 percent genuine mail, and it catches no spam at all. Accuracy is the first number you check and the last number you trust on its own.
The confusion matrix: four boxes that expose the lazy model
The confusion matrix splits the result into four counts. Rows are the truth, columns are the prediction. It is the check you should reach for first with any classifier, and it exposes the lazy model at once.
from sklearn.metrics import confusion_matrix
print("Real model:")
print(confusion_matrix(y_test, clf.predict(X_test)))
print("Lazy model, all twelve:")
print(confusion_matrix(passed, lazy_all))Expected behaviour: the code prints the two matrices below.
Real model:
[[1 0]
[0 2]]
Lazy model, all twelve:
[[0 3]
[0 9]]Read the real model first. Top left, 1: one failing student correctly called fail. Bottom right, 2: two passing students correctly called pass. The two off-diagonal cells are both 0: no mistakes at all. A perfect matrix has zeros off the diagonal, and this one does, on three students.
Now the lazy model. Top left, 0: no failing student caught. Top right, 3: all three failing students called pass. Bottom left, 0, and bottom right, 9: every passing student called pass, which is the only thing the model can do. The matrix says in numbers what accuracy hid: the model catches zero of the three students a teacher would most want to find. The four cells have names you will meet everywhere: top left is a true negative, bottom right a true positive, top right a false positive, bottom left a false negative. This tutorial uses the plain words, fail caught, fail missed, pass caught, pass missed, because the plain words are harder to mix up.
, [0, 2]] labelled "real model: the fail was caught" and the lazy model [[0, 3], [0, 9]]` labelled "always predict pass: 75 percent accurate, zero fails caught", with the three missed fails circled.]
Precision and recall, one category at a time
Precision and recall score one category at a time, and they ask two different questions about it. Take the pass category. Precision asks: of the students the model called pass, how many really passed? Recall asks: of the students who really passed, how many did the model catch? One is about the model's promises, the other about its coverage.
from sklearn.metrics import precision_score, recall_score, f1_score
print("Real model, pass: precision",
round(precision_score(y_test, clf.predict(X_test), pos_label=1), 3),
"recall",
round(recall_score(y_test, clf.predict(X_test), pos_label=1), 3))
print("Lazy model, pass: precision",
round(precision_score(passed, lazy_all, pos_label=1), 3),
"recall",
round(recall_score(passed, lazy_all, pos_label=1), 3))
print("Lazy model, fail: precision",
round(precision_score(passed, lazy_all, pos_label=0, zero_division=0), 3),
"recall",
round(recall_score(passed, lazy_all, pos_label=0, zero_division=0), 3))Expected behaviour: the code prints Real model, pass: precision 1.0 recall 1.0, Lazy model, pass: precision 0.75 recall 1.0 and Lazy model, fail: precision 0.0 recall 0.0.
Read the lazy model's numbers slowly, because they are the whole lesson. For the pass category, its recall is 1.0: it caught every passing student, because it called everyone pass. Its precision is 0.75: of the twelve students it called pass, only nine really passed, and three were fails it missed. For the fail category, both numbers are 0.0: it never predicted fail, so it caught no failing student and its precision for fail is not even defined (more on that warning in the wrong-turn section).
The real model scores 1.0 on all four numbers, but only on three test students, so this is a demonstration, not proof. The habit is the point: quote precision and recall per category, not one accuracy for the whole model. A model can be excellent at the common category and useless at the rare one, and only the per-category numbers show it.
Moving the threshold: the trade-off you cannot avoid
The classifier does not really output "pass" or "fail". It outputs a probability, and 0.5 is the line: above it means pass, below it means fail. Move the line and the predictions change. The three test students have pass probabilities 1.00, 0.91 and 0.12. At the usual line of 0.5, all three are called correctly. Raise the line to 0.95, so only very confident passes count:
proba = clf.predict_proba(X_test)[:, 1]
print("Probabilities:", np.round(proba, 2))
pred_strict = (proba >= 0.95).astype(int)
print("Predictions at 0.95:", pred_strict, " Actual:", y_test)
print("Accuracy:", round(accuracy_score(y_test, pred_strict), 3))
print("Precision, pass:",
round(precision_score(y_test, pred_strict, pos_label=1), 3))
print("Recall, pass:",
round(recall_score(y_test, pred_strict, pos_label=1), 3))
print("F1, pass:", round(f1_score(y_test, pred_strict, pos_label=1), 3))
print(confusion_matrix(y_test, pred_strict))Expected behaviour: the code prints Probabilities: [1. 0.91 0.12], Predictions at 0.95: [1 0 0], Accuracy: 0.667, Precision, pass: 1.0, Recall, pass: 0.5 and F1, pass: 0.667, with the matrix [[1, 0], [1, 1]].
The 5-hour student, probability 0.91, drops from pass to fail. Precision for pass rises to 1.0, because the one student still called pass really did pass. Recall for pass falls to 0.5, because only one of the two real passes was caught. Accuracy falls to 0.667. Nothing was gained for free: the stricter line bought certainty about its passes by missing a real one.
Which setting is right depends on the cost of each mistake. A spam filter wants high precision: binning real mail is expensive, so it only acts when sure. A medical screen wants high recall: missing a real case is expensive, so it flags anything doubtful and lets a human check. The threshold is a policy choice, not a maths fact. We use the default 0.5 in this series because it is the honest middle.
F1: one number for when you must have one
Sometimes one number is needed, for a dashboard or a comparison. The F1 score is the balance of precision and recall for one category, and it punishes a model that is good at one and bad at the other. The lazy model's F1 for the fail category is 0.0, which matches the truth: it caught nothing. Its F1 for pass is 0.857, from precision 0.75 and recall 1.0, which is a fair summary of a model that catches every pass and three fails along the way.
from sklearn.metrics import classification_report
print("Lazy model, F1 fail:",
round(f1_score(passed, lazy_all, pos_label=0, zero_division=0), 3))
print("Lazy model, F1 pass:",
round(f1_score(passed, lazy_all, pos_label=1), 3))
print(classification_report(y_test, clf.predict(X_test),
target_names=["fail", "pass"], digits=2))Expected behaviour: the code prints Lazy model, F1 fail: 0.0 and Lazy model, F1 pass: 0.857, then the full report below.
precision recall f1-score support
fail 1.00 1.00 1.00 1
pass 1.00 1.00 1.00 2
accuracy 1.00 3
macro avg 1.00 1.00 1.00 3
weighted avg 1.00 1.00 1.00 3The classification_report is the single most useful printout in scikit-learn for a classifier: precision, recall and F1 per category, plus the support, which is how many real examples of each category the test set held. Read the support column first. Here it says 1 fail and 2 passes, which is why this perfect report is still only a demonstration. A report built on three students is a smoke test. On real data, the same printout is the whole evaluation, and the support column is what tells you whether to believe it.
Regression checks: R-squared, mean error and root mean squared error
Regression predicts numbers, so its checks are about the size of the errors, not about categories. Item 67 already measured two of them on the same split. R-squared was 0.964 on the three test students, and the mean absolute error was 2.68 marks. One more measure belongs next to them: the root mean squared error, which punishes big mistakes more than small ones.
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
rp = reg.predict(X_test)
print("R-squared, test:", round(r2_score(yr_test, rp), 3))
print("R-squared, train:", round(r2_score(yr_train, reg.predict(X_train)), 3))
print("Mean absolute error, test:",
round(mean_absolute_error(yr_test, rp), 2))
print("Mean absolute error, train:",
round(mean_absolute_error(yr_train, reg.predict(X_train)), 2))
print("Root mean squared error, test:",
round(float(np.sqrt(mean_squared_error(yr_test, rp))), 2))Expected behaviour: the code prints R-squared, test: 0.964, R-squared, train: 0.995, Mean absolute error, test: 2.68, Mean absolute error, train: 0.96 and Root mean squared error, test: 3.88.
Read the three test numbers together. R-squared, 0.964, says the model explains 96.4 percent of why the unseen scores differ. Mean absolute error, 2.68, says predictions are off by 2.68 marks on average, in marks, the units of the answer. Root mean squared error, 3.88, is bigger than the mean error, and that gap is informative: squaring the errors before averaging gives the big misses extra weight, so a root mean squared error clearly above the mean error means at least one prediction was off by much more than the average. Here the three errors are 1.2, 6.6 and 0.2 marks, and the 6.6 is the one doing the work.
The train numbers tell the second half. On the nine students it trained on, the model scores R-squared 0.995 and a mean error of 0.96 marks. On unseen students, 0.964 and 2.68. The model looks almost three times more accurate on data it has seen, and that gap is the subject of the next section.
Train versus test: the overfitting gap, with a tree that memorised
Overfitting is a model learning the training rows instead of the pattern behind them. The symptom is a gap: great on training data, worse on new data. The regression model above has a small, honest gap. A decision tree shows the gap at full size. A tree with no depth limit can keep splitting until every training row sits alone in its own leaf, and then it stops learning and starts memorising.
from sklearn.tree import DecisionTreeRegressor
tree = DecisionTreeRegressor(random_state=42).fit(X_train, yr_train)
print("Tree, R-squared train:", round(r2_score(yr_train, tree.predict(X_train)), 3))
print("Tree, R-squared test:", round(r2_score(yr_test, tree.predict(X_test)), 3))
print("Tree, mean error test:",
round(mean_absolute_error(yr_test, tree.predict(X_test)), 2))
print("Tree predictions:", np.round(tree.predict(X_test), 1))
print("Actual: ", yr_test)Expected behaviour: the code prints Tree, R-squared train: 1.0, Tree, R-squared test: 0.957, Tree, mean error test: 4.0, Tree predictions: [82. 63. 41.] and Actual: [88. 66. 38.].
A training R-squared of 1.0 is not a triumph. It means the tree reproduced every training score exactly, which is what memorising looks like. And the proof is in the predictions: 82, 63 and 41 are not computed answers. They are scores of training students, repeated back. The tree's answer to a new student is the score of the training student nearest to them. On the test set that gives a mean error of 4.0 marks, worse than the straight line's 2.68, even though the tree was perfect on the data it trained on.
That is overfitting in one sentence: perfect on the rows it saw, worse on the rows it did not. The cure is the discipline this tutorial is built on: keep a test set the model never trains on, report the test number, and distrust a model whose training score is far above its test score. A small gap is normal. A gap from 1.0 to 0.957 is the model telling you it memorised.
Cross-validation: test three times, not once
One split can flatter a model, especially with twelve rows. The test set here is three students, and one unusual student moves every score. Cross-validation repeats the split: divide the data into three folds, train on two, test on the third, and rotate, so every student is tested once and the score is the average of three runs.
from sklearn.model_selection import cross_val_score, StratifiedKFold, KFold
cv_clf = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)
clf_scores = cross_val_score(LogisticRegression(max_iter=1000), X, passed, cv=cv_clf)
print("Classifier, 3-fold accuracy:", np.round(clf_scores, 3),
"mean:", round(float(clf_scores.mean()), 3))
cv_reg = KFold(n_splits=3, shuffle=True, random_state=42)
r2_scores = cross_val_score(LinearRegression(), X, score, cv=cv_reg, scoring="r2")
mae_scores = cross_val_score(LinearRegression(), X, score, cv=cv_reg,
scoring="neg_mean_absolute_error")
print("Regression, 3-fold R-squared:", np.round(r2_scores, 3),
"mean:", round(float(r2_scores.mean()), 3))
print("Regression, 3-fold mean error:", np.round(-mae_scores, 2),
"mean:", round(float(-mae_scores.mean()), 2))Expected behaviour: the code prints Classifier, 3-fold accuracy: [1. 1. 1.] mean: 1.0, Regression, 3-fold R-squared: [0.982 0.991 0.996] mean: 0.989 and Regression, 3-fold mean error: [2.28 1.79 0.42] mean: 1.5.
Two honest readings. The classifier scores 1.0 on all three folds, which tells you more about this dataset than about the model: the two groups separate cleanly, so any sensible boundary gets them right. The regression fold errors, 2.28, 1.79 and 0.42, show the wobble: the same model scores very differently depending on which four students land in the test fold. With twelve rows, a single split is a coin toss dressed as a measurement, and the average of three folds, mean error 1.5 marks, is a steadier claim than any one fold's number. On real datasets, five or ten folds is the usual choice, and the same code runs them.
The wrong turn: a precision score that does not exist
Here is the warning every beginner meets when they score a model that never predicts one category. Score the lazy model's precision for the fail category without the zero_division argument:
precision_score(passed, lazy_all, pos_label=0)Expected behaviour: the code prints 0.0 and raises a warning worth reading in full:
UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.What it means: precision divides correct predictions by all predictions of that category. The lazy model predicted fail zero times, so the division is 0 divided by 0, which has no answer. scikit-learn sets it to 0.0 and warns you, rather than crashing, because a silent 0.0 would look like a measured score. The fix is to say what you want in that case: pass zero_division=0 to record it as 0, or zero_division=1 if your rules count it as 1, and always say which you chose. The deeper fix is the one from the confusion matrix section: if a category is never predicted, the problem is the model, not the metric, and no parameter makes the 0.0 into a good result.
Try it yourself
1. Change the threshold to 0.9 instead of 0.95 and recompute accuracy, precision and recall for the pass category. Which student changes sides, and does the trade-off look better or worse than at 0.95? 2. Score the lazy model with classification_report on all twelve students. Compare its fail row, all zeros, with the real model's report. Which single line in the report exposes the lazy model fastest? 3. Fit the decision tree classifier from the overfitting section on the same split and print its confusion matrix. It scores 1.0 on the test students, so ask the harder question: is its training accuracy also 1.0, and what does that tell you about what it learned? 4. Run the regression cross-validation with five folds instead of three. Does the mean error move much? If one fold's error is far from the others, look at which students landed in that fold. 5. Take the regression tree's predictions, 82, 63 and 41, and find the training students with those exact scores. Write one sentence explaining why a model that repeats training answers is not predicting.
Continue in the free course: AI & Machine Learning: First Steps →
Common mistakes
- Quoting accuracy on unbalanced data. The lazy model scores 0.75 on twelve students while catching zero fails. Always check the confusion matrix and the per-category numbers before quoting accuracy.
- Measuring the model on the data it trained on. The regression model scores R-squared 0.995 on training rows and 0.964 on unseen rows. Report the test number, and say how many test rows it came from.
- Reading precision and recall as one number. The lazy model's recall for pass is 1.0 and its precision is 0.75. One without the other hides the three fails it called pass. Quote both, per category.
- Treating a training score of 1.0 as success. The decision tree scores R-squared 1.0 on training data and 0.957 on test data, with a mean error of 4.0 marks against the line's 2.68. A perfect training score is a warning, not a result.
- Moving the threshold without saying so. Raising it to 0.95 lifts precision for pass to 1.0 and drops recall to 0.5. The threshold is a policy choice, and hiding it makes the model look better than it is.
- Trusting one split on a small dataset. The regression fold errors are 2.28, 1.79 and 0.42 marks. One split is a coin toss dressed as a measurement; cross-validation steadies the claim.
- Ignoring the warning when a metric is undefined. Precision for a category the model never predicts is 0 divided by 0. Set
zero_divisionexplicitly, and fix the model rather than the metric.
Frequently asked questions
Which metric should I use for my model?
Start from the job. If the answer is a category, print the confusion matrix and the classification report, then read precision and recall per category. If the answer is a number, read R-squared with the mean absolute error, and the root mean squared error when big misses matter more than small ones. Accuracy alone is never the whole answer.
Is 75 percent accuracy good?
It depends on the data. On twelve students where nine pass, a model that predicts pass for everyone scores 75 percent and catches nothing. Compare every accuracy against the lazy baseline: the score of predicting the majority category every time. A model has to beat that baseline on the category that matters, not just overall.
What is a good R-squared?
There is no universal good value. Ours is 0.964 on three unseen students, which is high and also fragile, because three rows is a tiny test. On real data, a lower R-squared measured honestly on a large test set is worth more than a high one measured on the training rows. Report the test number and the test size together.
Can a model be too good on training data?
Yes, and that is overfitting. The decision tree scores R-squared 1.0 on the nine training students and 0.957 on the three test students, and its predictions are training scores repeated back. When the training score is far above the test score, the model memorised. Simpler models, more data, and cross-validation are the usual cures.
How many folds should cross-validation use?
Five or ten on real data. Three is the honest minimum for a teaching dataset of twelve rows, and even three shows the wobble: our fold errors run from 0.42 to 2.28 marks. More folds steady the average, but each fold still needs enough test rows to mean something, so the choice depends on the size of the dataset.
Follow the Python + AI/ML Beginner Roadmap
Learn Python from zero and take your first steps into AI and machine learning. Free, step by step, at your pace.
View the Roadmap