How to Evaluate Machine Learning Models: Accuracy, Precision, Recall and F1 Score
Imagine evaluating a machine learning system that checks 1,000 fictional monitoring records. Only 50 contain the unusual event you want to detect. One classifier simply predicts “no event” for every record. Its accuracy is an impressive-looking 95%, yet it identifies none of the 50 positive examples. Is this an effective classifier? The answer depends on what your system is supposed to accomplish and the consequences of missed cases.
This tutorial explains how to evaluate machine learning models beyond one headline percentage. You will calculate accuracy, precision, recall and F1 from a consistent confusion matrix; interpret how false alarms differ from missed cases; understand class imbalance and classification thresholds; and use Python to compare real model predictions on an entirely synthetic, reproducible dataset. You will also learn to distinguish a final test from a validation experiment, examine precision–recall curves, and write a responsible evaluation report.
The mathematical definitions follow the current scikit-learn model-evaluation guide and Google’s classification lessons. When a chart displays outcomes from fitted models, it comes from an executed Python notebook. Other diagrams and classroom examples are explicitly identified as fictional or conceptual. No results in this article describe a deployed medical or safety system.
Quick answer: Accuracy asks how many predictions are correct overall; precision asks how often positive predictions are correct; recall asks how many real positive cases are found; and F1 summarizes precision and recall with their harmonic mean. The best metric depends on class prevalence, error costs, label quality and the purpose of the model. Always inspect a confusion matrix and compare with a sensible baseline.
What does evaluating a machine learning model mean?
Model evaluation is the process of measuring a model’s predictions against appropriate reference labels using methods suited to the real task. In classification, the labels are categories such as spam/not spam or a scientific specimen’s class. A prediction is the category the model chooses; a ground-truth label is the recorded category used for comparison. Even ground-truth labels can contain error, so their provenance matters. Generalization is the ability to perform well on relevant observations not used to train the model.
Evaluation reveals more than whether code runs. It helps researchers compare algorithms, identify which errors are common, detect overfitting, examine subgroup performance and consider whether a model is suitable for its intended environment. A useful score on a limited historical or synthetic benchmark does not guarantee success on future real data. Data collection, decisions about the positive class, sampling and the costs of an incorrect prediction can all alter how a result should be interpreted.
For example, a spam filter that sends legitimate email to a junk folder imposes a different cost than one that lets an unwanted email through. In an environmental sensor, missing an important alert and flagging an ordinary reading also have different consequences. A single accuracy percentage hides those distinctions. Before choosing a metric, define who would use the prediction and what each mistake would mean.
Training, validation and test sets have different jobs
Training data fit the numerical model parameters. Validation data guide development decisions such as which algorithm, threshold or complexity setting to use. Test data provide a more independent estimate after those choices are settled. If you repeatedly change a model because its final test score looks weak, the test sample silently becomes part of the development process. Its score is then less credible as an independent result.
Cross-validation can divide the development data into several training and validation folds, reporting performance across those splits. A stratified split approximately preserves category proportions and is often helpful for rare-class classification. However, time series may need chronological evaluation, while repeated samples from the same person, location or device can require grouped splits. Randomly shuffling dependent or future observations may produce unrealistic evidence.

Classification metrics are not regression metrics
The four metrics in this guide mainly evaluate predicted categories. Regression predicts numbers—for example a building’s measured energy use—and is evaluated using measures such as mean absolute error (MAE), root mean squared error (RMSE) and R². Applying classification accuracy directly to a continuous numerical prediction would not answer how far the estimate is from the measured value. In this article we focus on binary classification, then explain how to aggregate scores for multiple classes.
What is a confusion matrix?
A confusion matrix counts combinations of actual classes and predicted classes. We use the standard orientation: actual labels on the rows, predicted labels on the columns. For binary labels 0 and 1, scikit-learn’s confusion_matrix(y_true, y_pred, labels=[0,1]) returns the layout [[TN, FP], [FN, TP]]. Reversing the row/column interpretation silently turns false positives into false negatives, so label the axes in every chart.
A true positive (TP) is a correctly identified positive. A false positive (FP) is a negative observation incorrectly flagged positive. A true negative (TN) is a correctly rejected negative, and a false negative (FN) is a positive case the model missed. In a hypothetical plant disease-screening lesson, a false positive is a healthy leaf flagged as diseased, while a false negative is a diseased leaf missed by the classifier. This does not make the model appropriate for agricultural decisions without further testing.

A complete worked confusion matrix using 200 fictional examples
Use one consistent fictional example throughout the calculations: TP=40, FP=10, TN=130 and FN=20. The sample contains 60 actual positives (40+20) and 140 actual negatives (130+10), totaling 200. The model predicts positive for 50 records (40+10) and negative for 150 (130+20). Notice that these counts form one coherent experiment: changing any one number would affect multiple metrics.
| Actual / predicted | Predicted positive | Predicted negative |
|---|---|---|
| Actual positive | 40 (TP) | 20 (FN) |
| Actual negative | 10 (FP) | 130 (TN) |

Accuracy: the percentage of correct predictions
Accuracy = (TP + TN) / (TP + FP + TN + FN). Here it is (40+130)/200 = 170/200 = 0.85 = 85%. The model correctly predicts 170 of 200 records. Accuracy can be informative when the class mixture is relevant and the costs of mistakes are similar, but it can hide poor performance on a small yet important positive class.
Accuracy depends on which population you test. If a deployment environment contains far fewer positive examples than the evaluation set, a model that predicts negatives often can appear more accurate even while missing important events. Always present class counts and compare the result with a majority-class baseline.
Precision: can we trust the positive alerts?
Precision = TP / (TP + FP). Our classifier made 50 positive predictions, and 40 were correct. Precision is therefore 40/50 = 0.80 = 80%. Read this carefully: among predictions called positive, 80% were actual positives in the fictional sample. Precision is not the proportion of all positive cases found; that is recall.
When a false alarm is costly, precision deserves close attention. A spam filter that automatically blocks important mail may need very few false positives. A scientific review queue with expensive manual inspection also cares about incorrect flags. Precision varies with the prevalence of true positives in the evaluated population, so a number from one dataset may not transfer to another.
Recall: how many positive cases did we find?
Recall = TP / (TP + FN). There were 60 actual positive examples. The model recovered 40, so recall is 40/60 = 0.6667 = 66.7%. It missed 20 of the 60 positives. Recall is also known as sensitivity or true positive rate for binary classification, assuming a defined positive label and meaningful reference labels.
A high-recall system is valuable when failing to find a relevant event has important consequences. Document retrieval may prioritize finding all potentially useful papers, accepting additional irrelevant results for review. Fault screening may prioritize catching unusual readings, but follow-up checks still need attention to false alarms. Increasing recall by predicting positive more often is not automatically an improvement if it creates unacceptable downstream costs.
F1 score: combining precision and recall
F1 = 2 × (Precision × Recall) / (Precision + Recall). It is the harmonic mean, which penalizes a very low component more strongly than the ordinary arithmetic average. An equivalent formula is F1 = 2TP / (2TP + FP + FN). For our example this is 80/(80+10+20)=80/110 = 0.7273 = 72.7%.
F1 is useful when both precision and recall matter and we want one summary, especially for imbalanced classification. It does not include true negatives directly in the conventional binary formula, so a high F1 can coexist with weaknesses in specificity or calibration. A good F1 score is not a universal guarantee of safety, fairness or acceptable error costs. When the costs of the two kinds of mistakes differ, an F-beta score or explicit cost analysis may be more appropriate.

Accuracy vs. precision vs. recall vs. F1: side-by-side comparison
| Metric | Question | Formula | Important limitation |
|---|---|---|---|
| Accuracy | How often is the label right overall? | (TP+TN)/all | Can hide rare positive failures |
| Precision | How many flagged cases are true positives? | TP/(TP+FP) | Depends on prevalence and predicted positives |
| Recall | How many actual positives are found? | TP/(TP+FN) | Ignores false-positive burden |
| F1 | How well do precision and recall balance? | 2TP/(2TP+FP+FN) | Does not directly use true negatives |
Think of a classifier that flags laboratory documents requiring careful review. If the review budget is small, a high fraction of correct flags (precision) may matter. If it would be costly to overlook relevant documents, recall becomes important. If both burdens matter, F1 summarizes the pair, but it does not tell the team exactly how many false alarms must be checked. Accuracy should be reported alongside these figures—not substituted for them.

When should precision be the priority?
Prioritize precision when false positives impose relatively high costs. A spam classifier that silently hides important correspondence should be evaluated for the cost of wrongly filtered legitimate messages. A system that sends equipment alerts to an already overloaded team should measure how many alerts were justified. Precision should be paired with recall, since a classifier can achieve high precision by flagging very few events and silently missing many others.
When should recall be the priority?
Prioritize recall when false negatives impose substantial costs. A document search tool may aim to retrieve nearly all relevant papers, letting a researcher filter extras. An initial quality-control screen might favor finding possible faults for later assessment. This does not mean setting recall to 100% regardless of false alarms; the useful threshold depends on the downstream review process. Where mistakes affect health or safety, classroom exercises are not a substitute for expert-designed validation.
When is F1 useful, and what does F-beta change?
F1 is useful when both recall and precision are important and it is sensible to treat them symmetrically. The more general F-beta score lets an evaluator weight recall more heavily when beta exceeds one, or precision more heavily when beta is below one. The selected beta should reflect the operational goal, not a choice made after seeing whichever number looks largest. F1 also needs class labels and a specified positive class, so its meaning differs across binary and multiclass settings.
The class imbalance trap: 95% accuracy, zero positive recall
Return to the fictional example of 1,000 observations: 950 negative and 50 positive. A model that labels everything negative gets 950/1000 = 95% accuracy. Its confusion counts are TN=950, FP=0, FN=50 and TP=0. Positive recall is 0/50 = 0%. Since it predicts no positives, positive precision has an undefined denominator; in teaching code we may explicitly use zero_division=0, but that zero is a reporting convention, not evidence of a meaningful precision measurement.

A majority-class baseline predicts whichever class is common in the training data. If your new classifier fails to improve on this naive approach for the outcome that matters, it may be unsuitable despite sophisticated code. Balanced accuracy averages recall across the classes, so a binary all-negative classifier with both classes present receives 50% balanced accuracy rather than 95%. It is still only one complementary metric, not an automatic decision rule.
Sensitivity, specificity and false positive rate
Sensitivity is another name for positive recall: TP/(TP+FN). Specificity is true negative rate: TN/(TN+FP). False positive rate is FP/(FP+TN) = 1 − specificity when actual negatives exist. For our 200-case example, sensitivity is 66.67%, specificity is 130/140 = 92.86%, and FPR is 10/140 = 7.14%. Do not mistake FPR’s denominator for all observations.
Understanding classification thresholds
Many binary classifiers produce a continuous score or an estimated probability for the positive class. The system converts that score into a label by applying a threshold. At threshold 0.50, a score of 0.62 becomes positive and one of 0.27 becomes negative. If the threshold is reduced to 0.20, both are positive. Scores should not automatically be assumed to be well-calibrated probabilities: even a method called predict_proba may require calibration and testing.
Changing the threshold changes false positives, false negatives and the number of flagged observations. Raising it usually reduces the number of positive predictions and cannot increase true positives for a fixed ranked score list, but precision need not rise monotonically in every finite sample. Lowering it generally increases positive coverage and recall but can create extra false alarms. The goal is not to maximize one score without regard to practical constraints.
An illustrative threshold comparison students can compute
Imagine five entirely fictional records with actual labels [1,0,1,0,1] and positive scores [0.90,0.65,0.40,0.30,0.15]. With threshold 0.50, the predicted positives are the first two records: TP=1, FP=1, FN=2 and TN=1. Precision = 1/2 = 50% and recall = 1/3 = 33.33%. With threshold 0.30, the first four are flagged: TP=2, FP=2, FN=1 and TN=0. Precision remains 50%, while recall increases to 66.67%.
At 0.10, all five records become positive: TP=3, FP=2 and FN=0. Precision is 3/5 = 60% while recall is 100%. This small example also proves that precision need not decline monotonically as a threshold is lowered. The values are invented only for understanding; the later Python charts are based on a genuinely executed classifier.
| Threshold | TP / FP / TN / FN | Precision | Recall |
|---|---|---|---|
| 0.50 | 1 / 1 / 1 / 2 | 50.0% | 33.3% |
| 0.30 | 2 / 2 / 0 / 1 | 50.0% | 66.7% |
| 0.10 | 3 / 2 / 0 / 0 | 60.0% | 100.0% |
What is a precision–recall curve?
A precision–recall (PR) curve plots precision vertically and recall horizontally as the classification threshold varies. Different points summarize different tradeoffs. A useful curve helps answer questions such as how much precision might be lost to find more positive cases. It is particularly informative in rare-positive settings where the prevalence of the positive class affects the usefulness of alerts.
Average precision (AP), computed by scikit-learn’s average_precision_score, summarizes the sequence of precision values with recall increments. It should not be confused automatically with a trapezoidal area under a PR curve; they can give different numbers. A naive positive-prevalence baseline helps contextualize the graph, but a higher AP on one fixed dataset does not guarantee portability to another population.
ROC curves and ROC AUC
A receiver operating characteristic (ROC) curve plots the true positive rate against the false positive rate over thresholds. Its area (ROC AUC) indicates how often a model ranks a randomly selected positive above a randomly selected negative, with half credit for tied scores. ROC AUC is threshold-independent but does not directly show how many alerts will be false in a population with very few positives. PR curves may offer more operational clarity in rare-event settings; ROC remains valuable rather than inherently incorrect.
Why test sets and threshold selection should stay separate
It is tempting to calculate F1 at dozens of thresholds on the final test data and announce the best. That turns the supposedly independent test into a training or development resource. Instead, use a validation sample or training-only cross-validation to select the threshold and document the criterion used. Then evaluate the selected procedure once on a held-out test. Repeatedly inspecting the same test results for model improvement eventually produces optimistic scores.
The full project below follows that discipline: thresholds are considered on 320 validation records; the best among five specified candidates is chosen by validation F1; and only then are logistic models, a tree and a majority baseline compared on 320 separate test records. The scores and charts are actual recorded outputs—not estimates chosen to illustrate a preferred conclusion.
Macro, micro and weighted averages for multiclass models
A three-class flower or handwritten-digit classifier cannot be summarized using just one unqualified binary precision calculation. Scikit-learn can calculate a precision, recall and F1 for each class by treating it as positive against the other classes, then combine the results through different averages. The word support in classification_report() means the number of actual evaluation examples belonging to that class; it is not a prediction-confidence value.
Macro averaging calculates the arithmetic mean of the per-class metrics and gives each class equal weight. Weighted averaging uses the number of true examples in each class as weights, which means larger classes influence the result more. Micro averaging adds true positives, false positives and false negatives across classes before computing the measure. For ordinary single-label multiclass classification evaluated over all classes, micro precision, micro recall and micro F1 are equal to accuracy.
Consider a fictional three-class test set. Class A has 80 actual examples and F1 0.95, Class B has 15 and F1 0.60, and Class C has five and F1 0.20. The macro F1 is (0.95+0.60+0.20)/3 ≈ 0.583. The support-weighted F1 is (80×0.95+15×0.60+5×0.20)/100 = 0.86. These numbers are an illustrative averaging calculation, not the report of a fitted classifier; in a real model the per-class F1 values and supports come from its actual predictions. The example shows how a large class can dominate one summary while smaller classes remain weak.
Understanding a scikit-learn classification report
A classification_report displays per-class precision, recall, F1 and support, followed by aggregate rows. Look at the row for the positive class to understand detection success; do not assume a high negative-class F1 makes missed positives unimportant. The macro average can reveal weaknesses hidden by the support-weighted figure. The report’s accuracy row summarizes correct predictions, but it does not contain the full confusion matrix or the exact nature of misclassifications.
In a binary classifier, pos_label=1 is the default for several metric functions. However, a dataset’s label 1 does not always represent the event a student intuitively calls “positive.” Before calculating any metric, inspect the target names and the fitted model’s classes_ order. If class 0 is the event of interest in some benchmark, either configure an explicit positive label or recode carefully, and explain the decision.
What if precision or recall is mathematically undefined?
Precision is undefined when there are zero predicted positives, because the denominator TP+FP is zero. Recall is undefined if the test set contains no actual positives, because TP+FN is zero. Rare small groups may have both problems. In scikit-learn, zero_division='warn' is the usual default for affected functions, and an explicit zero_division=0 or zero_division=np.nan can control the numerical convention in supported versions. Report why a rate was undefined; printing zero without context is not a scientifically adequate answer.
Responsible evaluation includes subgroup performance
An average model score can hide errors affecting particular languages, devices, regions or populations. Where it is legal, appropriate and supported by reliable labels, review group-specific confusion matrices, positive recall, false positive rates and sample sizes. A performance difference deserves investigation but is not itself proof of discrimination or causation. Avoid collecting private student data simply to practise these concepts: the exercises and executable project here use synthetic numbers.
For a deeper discussion, see our verified AI Bias in Machine Learning guide. The key lesson is that technical evaluation, data validity, error costs and affected people all matter. High accuracy, equal error rates or an attractive performance plot cannot certify that an automated system is safe or fair.
Complete Python project — evaluating an artificial rare-event classifier
Research question: Can a simple numerical classifier detect relatively rare, fictional monitoring alerts, and how do different metrics change our judgment? We generate 1,600 artificial observations with eight numerical sensor-like features and a binary outcome. Class 1 is an invented alert; Class 0 is a normal fictional record. There are no real sensor measurements, school records, patient details or safety decisions in this dataset.
Rather than repeating the end-to-end model-training lesson from Topic 56, we spend most of this practical activity evaluating the predictions. The complete notebook and standalone Python script execute locally with scikit-learn 1.8.0; the code blocks below show the central steps while the downloads include the full reproducible workflow.
Step 1 — Install the supported libraries
Use a compatible Python environment or a classroom Jupyter notebook. Install NumPy, Pandas, Matplotlib and scikit-learn using python -m pip install numpy pandas matplotlib scikit-learn. Package versions and default settings can change, so keep the experiment’s version record in your report. The provided resources were tested with Python 3.13.5 and scikit-learn 1.8.0.
Step 2 — Generate a reproducible artificial dataset
from sklearn.datasets import make_classification
X, y = make_classification(
n_samples=1600, n_features=8, n_informative=5,
n_redundant=1, n_clusters_per_class=2,
weights=[.91, .09], flip_y=.035,
class_sep=1.0, random_state=63
)
print(X.shape, dict(zip(*__import__('numpy').unique(y, return_counts=True))))
The executed generator produced 1,600 rows and eight features, with 1,438 negatives and 162 positives. The label noise parameter deliberately introduces some uncertainty. These class proportions are outcomes of the fixed synthetic generator, not empirical rates for real monitoring devices. Before selecting metrics, note that a naive negative-only predictor will appear strong under ordinary accuracy.
Step 3 — Reserve training, validation and final test examples
import numpy as np
from sklearn.model_selection import train_test_split
ids = np.arange(len(y))
development, test = train_test_split(ids, test_size=.20,
stratify=y, random_state=42)
train, valid = train_test_split(development, test_size=.25,
stratify=y[development], random_state=42)
print(len(train), len(valid), len(test))
The split is 960 training, 320 validation and 320 test records, with no overlap. Stratification maintains representation of the rare class; the final test has 288 negatives and 32 positives. We use validation data to select a threshold and leave the locked test set untouched until model development is complete. If this were a real stream of sensor records, chronological splitting or grouping by device might be more suitable.
Step 4 — Fit a logistic classifier and useful baselines
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.dummy import DummyClassifier
logistic = make_pipeline(StandardScaler(),
LogisticRegression(max_iter=2000, random_state=42)).fit(X[train],y[train])
tree = DecisionTreeClassifier(max_depth=5,min_samples_leaf=8,
random_state=42).fit(X[train],y[train])
majority = DummyClassifier(strategy='most_frequent').fit(X[train],y[train])
The scaling transformation learns only from training records because it is fitted inside a pipeline. The logistic classifier estimates positive scores, the decision tree provides an alternative set of decision rules, and the majority-class dummy supplies a baseline that requires almost no understanding of the features. They are not tuned using the final test scores. It would be scientifically weak to compare a tuned model with a deliberately poor baseline and declare automatic deployment readiness.
Step 5 — Inspect class balance and actual predictions
Use np.unique(y, return_counts=True) to inspect prevalence, then inspect model predictions on validation records for development. The held-out positive class represents only 10% of the final 320-case sample. When results are scarce, one additional correctly detected alert can change positive recall by about 3.13 percentage points, emphasizing the uncertainty of small positive groups.
Step 6 — Choose a threshold on validation data
The logistic model provides predict_proba(). We checked that the fitted estimator’s classes_ are [0,1], so the probability column for class 1 is the second column. The notebook evaluated predefined thresholds 0.20, 0.35, 0.50, 0.65 and 0.80 using the validation set. Choosing the highest validation F1 among these candidates selected 0.20. This is a model-development choice, not a threshold chosen for its final test accuracy.
| Threshold on validation | Precision | Recall | F1 |
|---|---|---|---|
| 0.20 | 33.33% | 34.38% | 33.85% |
| 0.35 | 66.67% | 18.75% | 29.27% |
| 0.50 | 50.00% | 6.25% | 11.11% |
| 0.65 | 0.00%* | 0.00% | 0.00%* |
| 0.80 | 0.00%* | 0.00% | 0.00%* |
*The 0.65 and 0.80 thresholds produced no positive predictions on this validation set. Precision was undefined and displayed as zero only because the Python example explicitly used the zero_division=0 reporting convention. The absence of positive predictions should never be silently presented as a measured zero precision.

Step 7 — Open the final test set and compute metrics once
from sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score
positive_index = list(logistic[-1].classes_).index(1)
positive_scores = logistic.predict_proba(X[test])[:,positive_index]
preds_default = (positive_scores >= .50).astype(int)
preds_selected = (positive_scores >= .20).astype(int)
for name, pred in [('default',preds_default),('selected',preds_selected)]:
print(name, accuracy_score(y[test],pred),
precision_score(y[test],pred,zero_division=0),
recall_score(y[test],pred,zero_division=0),
f1_score(y[test],pred,zero_division=0))
These values were calculated by actually running the notebook and script. At the standard 0.50 threshold, logistic regression achieved 90.94% accuracy, 100% precision, 9.38% recall and 17.14% F1. It flagged only three cases and all three were truly positive, but it missed 29 of the 32 positive examples. This is a striking illustration of why a very high precision value may coexist with disappointing detection.
Step 8 — Read the fitted model’s confusion matrix
The default logistic model’s held-out confusion matrix contains TN=288, FP=0, FN=29 and TP=3. The sum is 320, matching the test set. Because it issued only three positive alerts, its perfect precision is based on very little evidence. If a threshold creates zero predictions, precision is undefined; if it creates just three, the estimate can be highly variable on new samples. Report both its denominator and its score.

Step 9 — Compare the validation-selected threshold
At threshold 0.20, logistic regression flagged 38 held-out records, including 13 true positives and 25 false positives. It missed 19 positive cases and correctly labeled 263 negatives. Its resulting accuracy was 86.25%, precision 34.21%, recall 40.63% and F1 37.14%. Lowering the threshold reduced overall accuracy while increasing positive recall and F1. That is not a contradiction: the metrics emphasize different events.
Step 10 — Generate a classification report
from sklearn.metrics import classification_report,confusion_matrix
print(confusion_matrix(y[test],preds_default,labels=[0,1]))
print(classification_report(y[test],preds_default,
target_names=['No alert','Alert'],zero_division=0))
The report shows both the common negative class and rare alert class, with class support of 288 and 32 respectively. A large support-weighted score can be dominated by the negative category; therefore, inspect the positive-class row, its sample count and the confusion matrix. For multiclass projects, explain macro and weighted averaging choices explicitly rather than simply copying a library output table.
Step 11 — Plot a genuine precision–recall curve
from sklearn.metrics import precision_recall_curve,average_precision_score
p, r, thresholds_pr = precision_recall_curve(y[test],positive_scores)
ap = average_precision_score(y[test],positive_scores)
print('Average precision:',round(ap,4))
The held-out synthetic scores produced average precision = 0.4159 (approximately 41.59%). This summarizes how precision changes as recall increases when ranking all 320 observations. Since positives account for 32/320 = 10% of the test set, the positive prevalence is a useful reference, but it is not a replacement for a proper baseline analysis. The curve evaluates ranking across thresholds, not whether predicted probabilities are calibrated.

Step 12 — Interpret the ROC curve alongside the PR curve
The ROC AUC for the same test scores was approximately 0.6962. This rank-based measure can be helpful for comparing models across potential thresholds. The PR curve emphasizes the proportion of flagged examples that are truly positive, often especially meaningful when alerts are rare. Present both when useful and explain how prevalence, label noise and the intended use affect interpretation.

Step 13 — Compare a majority baseline, logistic model and tree
| Held-out model | Accuracy | Precision | Recall | F1 |
|---|---|---|---|---|
| Majority baseline | 90.00% | 0.00%* | 0.00% | 0.00% |
| Logistic, threshold 0.50 | 90.94% | 100.00% | 9.38% | 17.14% |
| Logistic, selected 0.20 | 86.25% | 34.21% | 40.63% | 37.14% |
| Decision tree, fixed settings | 89.69% | 48.00% | 37.50% | 42.11% |
*The majority baseline predicted no positives, so its precision denominator is zero and the printed 0% reflects the explicitly chosen zero_division=0 convention. The tree had TN=275, FP=13, FN=20 and TP=12. Its F1 was higher than the selected logistic variant on this particular small test set, but we did not select the tree based on those final results. Claiming it is definitively superior would require more independent evaluation or properly nested development.

Steps 14–16 — Interpret limits and write your evaluation report
A defensible report begins with the research question, the class label representing the event, dataset origin, sample size and prevalence, and the exact split design. Then state each model’s settings, the validation rule used for threshold selection, confusion counts, accuracy, precision, recall, F1, AP where relevant, and the consequences of false positives and missed positives. Distinguish descriptive performance from a decision about whether deployment is acceptable.
Our synthetic results illustrate tradeoffs but do not establish real sensor reliability. The dataset was generated by a known statistical function with fixed settings; it does not include changing weather, hardware faults, shifting language patterns, privacy-sensitive populations or ground-truth disputes. A real project would require independently collected representative samples, confidence intervals or repeated evaluation, clear error budgets and human accountability. Record unexpected weaknesses honestly rather than optimizing for a single impressive percentage.
Students who are new to training can revisit Topic 61’s decision-tree tutorial; this lesson concentrates instead on deciding whether the predictions deserve trust. Run the downloadable notebook, change only validation settings, explain why the selected threshold differs from the default, and write a short conclusion comparing both benefits and costs.
Practical model evaluation checklist
Before trusting a model, record what the positive class means, check class counts, establish a baseline, fit preprocessing using only training data, select hyperparameters and thresholds on validation data, then report the final confusion matrix and its denominators. Review whether a group, device, time period or environment is missing from evaluation. Explain uncertainty, privacy considerations, and why new data might invalidate the result. The printable checklist and code are provided in the learning package.
Fifteen mistakes to avoid when reporting model performance
Common mistakes 1–5: reporting only accuracy; forgetting rare-class prevalence; swapping precision with recall; leaving the positive class undefined; and reading confusion matrix rows as predictions when they represent actual labels. All five errors can make a correct library output misleading. Include the exact orientation and label names with every matrix.
Mistakes 6–10: evaluating on training records; selecting thresholds using the final test set; fitting normalization on the complete dataset; comparing performance from different datasets without considering their populations; and treating undefined precision as an observed zero without explanation. Proper split design and clear metric conventions prevent these problems.
Mistakes 11–15: declaring a winner from a tiny score difference; ignoring subgroup errors; confusing F1 with overall accuracy; claiming a good benchmark proves deployment readiness; and describing cross-validation results as if they came from an independent final test. The solution is straightforward in principle but requires discipline: state exactly what was measured, which data were used and what remains unknown.
Four-week learning roadmap
| Week | Focus | Student deliverable |
|---|---|---|
| Week 1 | Confusion matrix and accuracy | Calculate TP, FP, TN, FN, accuracy, specificity |
| Week 2 | Precision, recall and F1 | Explain each denominator and the false-positive/false-negative tradeoff |
| Week 3 | Python evaluation and curves | Reproduce the real model confusion matrix and PR/ROC plots |
| Week 4 | Complete model assessment | Compare baseline, models and validation-selected threshold; write a limitations report |
Four weeks provides a useful introduction, not certification as a machine learning evaluator. Students can repeat the manual calculations before looking at the answers, then study the notebook outputs and practise explaining why the most impressive-looking accuracy number may not solve the intended problem.
Ten student exercises with explained answers
Attempt each exercise before expanding its solution. These questions use the verified fictional 200-case confusion matrix and the actual synthetic project where identified.
1. Define accuracy in a classification task.
Accuracy is the proportion of all observations classified correctly: (TP+TN)/(TP+FP+TN+FN).
2. Identify TP, FP, TN and FN in a confusion matrix.
TP is actual positive/predicted positive; FP is actual negative/predicted positive; TN is actual negative/predicted negative; FN is actual positive/predicted negative.
3. Calculate accuracy when TP=40, FP=10, TN=130 and FN=20.
(40+130)/200 = 0.85 = 85%. There are 200 observations and 170 correct labels.
4. Calculate precision from the same counts.
40/(40+10)=40/50=0.80=80%. Only positive predictions are in the denominator.
5. Calculate recall from the same counts.
40/(40+20)=40/60≈0.6667=66.67%. Only actual positives are in the denominator.
6. Calculate the F1 score in two equivalent ways.
2×0.80×(2/3)/(0.80+2/3)=8/11≈72.73%. Also 2TP/(2TP+FP+FN)=80/110.
7. Why is 95% accuracy misleading for a negative-only model?
If 950 of 1000 are negative, predicting all negative gives 95% accuracy but 0/50=0% recall for the positive class. Positive precision is undefined.
8. What should you inspect in a classification report?
Per-class precision, recall, F1 and support, plus accuracy and macro/weighted averages. Check the minority class rather than trusting only weighted F1.
9. Explain how lowering the threshold affected our real model.
It increased test positive recall from 9.38% to 40.63%, but reduced precision from 100% to 34.21%. The threshold was chosen on validation, not selected using test outcomes.
10. Which metrics matter for fictional rare-fault screening?
Positive recall and false negatives help assess missed alerts; precision and false positives describe unnecessary investigations. Include prevalence, baseline, uncertainty, and the cost of errors.
Downloadable Topic 63 learning resources
The following printable files are hosted in this WordPress media library: Accuracy, Precision, Recall and F1 Formula Sheet (PDF), Student Practice Worksheet (PDF), Worked Solutions (PDF), and Model Evaluation Checklist (PDF). A fully executed Jupyter notebook, a standalone script, synthetic CSV and all original figures are available in the downloadable learning ZIP linked in the completion report for this article.
Optional Coursera and Udemy courses
These are optional study resources that follow the free lesson. Disclosure: the course destinations have been verified, but approved affiliate tracking information was unavailable. These are ordinary official course links, not fabricated affiliate URLs or promises of discounts or certificates. Check current course prerequisites, terms and availability before enrolling.

Supervised Machine Learning: Regression and Classification
Coursera / DeepLearning.AI: develop supervised model and binary classification foundations, useful before advanced evaluation.

Python for Data Science and Machine Learning Bootcamp
Udemy: hands-on Python, numerical analysis, visualization and traditional machine learning practice.
Frequently asked questions about classification metrics
What does model evaluation mean in machine learning?
Measuring model outputs against relevant reference labels on suitable data, using metrics that reflect the task and its error costs.
What is classification accuracy?
The fraction of all predictions that match their labels: (TP+TN)/(TP+TN+FP+FN).
What is precision?
The fraction of predicted positive examples that are actually positive: TP/(TP+FP), when defined.
What is recall?
The proportion of actual positive examples correctly identified: TP/(TP+FN), when defined.
What is F1 score?
The harmonic mean of precision and recall: 2PR/(P+R), equivalently 2TP/(2TP+FP+FN) when defined.
What is a confusion matrix?
A table of actual and predicted categories; for binary labels [0,1], scikit-learn returns [[TN,FP],[FN,TP]].
Why is accuracy misleading with imbalanced data?
A classifier can predict the dominant class and achieve high accuracy while finding few or none of the rare positives.
When should precision or recall receive more weight?
Prioritize based on the relative costs of false positives and false negatives, while reporting both and checking the task context.
What is macro F1?
The unweighted mean of per-class F1 values. It differs from support-weighted F1 when classes have unequal counts.
How do I calculate these metrics in Python?
Use scikit-learn accuracy_score, precision_score, recall_score, f1_score, confusion_matrix and classification_report with explicit label meaning and zero-division handling.
Related reading and authoritative source documentation
Continue with verified Notes for SHS lessons: Machine Learning for High School Students, Supervised vs. Unsupervised Learning, Build Your First ML Model, Decision Tree Training, AI Bias in Machine Learning and 15 Beginner ML Projects. These links point to confirmed published posts on the connected staging site.
Primary technical sources: scikit-learn model evaluation guide, confusion matrix API, classification report, PR curve API, average precision and Google classification metrics. Interpret current software versions and parameter defaults using these original references.
Conclusion: a good score is only the start of evaluation
The purpose of evaluation is not to find the largest number on a dashboard. Accuracy describes correct classifications overall, precision measures the reliability of positive flags, recall reveals missed positive examples, and F1 combines precision and recall. Confusion matrices and class supports show what those scores hide. Thresholds, baselines, label quality and representative test sets determine whether the summary fits the actual question.
In our executed synthetic project, a 90% accurate negative-only baseline missed every positive case, while a validation-selected lower threshold increased recall at the cost of extra false alarms. Reproduce the notebook, calculate the fictional 200-case example by hand and explain the error tradeoff in your own words. That ability to interpret evidence responsibly is more useful than claiming any one model or metric always wins.
1 response to “How to Evaluate Machine Learning Models: Accuracy, Precision, Recall and F1 Score”