Machine Learning Basics for Testers

Machine learning (ML) builds software whose behaviour is learned from data instead of written as rules. A training algorithm fits a model to examples, and the model then predicts outcomes for new inputs. A card-fraud model, for example, is trained on past payments labelled "fraud" or "legitimate"; in production it scores each new payment, and payments at or above a chosen threshold go to manual review.

Building on AI testing fundamentals, this lesson gives you the vocabulary to test such a model: the kinds of learning, how data is split, how a model learns too much or too little, and how to read a confusion matrix and its metrics.

Why it matters

Many ML defects never appear in the code. A model can learn from mislabelled or unrepresentative data, be evaluated on data it has already seen, or be judged by a metric that hides the errors that matter. The evaluation report then looks excellent while real users meet missed fraud, blocked customers, or a group of users served much worse than the rest.

With these basics a tester can question an evaluation instead of accepting its number: where did the test data come from, does it overlap with the training data, which errors are expensive, and how does the model do for each group of users?

Three kinds of learning, one workflow

ML work follows a workflow, which the ISTQB AI Testing (CT-AI) syllabus describes in finer steps: define the objective and acceptance criteria, collect and label data, prepare and split it, train a model, evaluate and tune it on validation data, test the final model once on test data, deploy it, then monitor it and retrain it when the data changes. Each step gives a tester something to review: the objective is a test basis, the dataset a work product, the evaluation a test result.

The kinds of learning differ in what the model learns from, which decides what a test can compare its output against:

  • Supervised learning: the model learns from labelled examples, inputs paired with the correct answer (the label). Classification predicts a category (fraud or legitimate), ML regression a number (a delivery time); this statistical regression has nothing to do with regression testing. Labelled test data serves as the test oracle. The metrics in this lesson are for classification; a regression model is judged by the size of its errors, such as minutes away from the real delivery time.
  • Unsupervised learning: there are no labels; the model finds structure, such as clusters of similar customers or unusual transactions. With no answer key, evaluation relies on expert review of samples, stability checks, or labelling a sample afterwards.
  • Reinforcement learning: an agent learns by acting in an environment and receiving rewards or penalties, such as a robot learning warehouse routes. Tests check that the reward describes the wanted behaviour, since an agent can find unintended ways to earn it, and how the agent behaves in situations it never met in training.

Training, validation and test sets

The labelled data is divided into three sets. The model learns from the training set. The validation set is used during development to compare models, tune settings and choose the threshold. The test set (hold-out set) is kept aside and used once, after every choice is made, to estimate performance on unseen data. Some teams swap the names "validation" and "test", so ask which set a reported number comes from.

Training, validation and test sets have different jobs: the model learns from the training set, choices are made on the validation set, and the test set is used once for the final estimate on unseen data.

Training setModel learns from it

The model fits its parameters to these labelled examples

When it is used:
In every training run
Does the model learn from it?:
Yes: it fits its parameters to it
A score on it shows:
How well the model fits data it has seen; far above validation means overfitting, low on both means underfitting
How it goes wrong:
Shares duplicates, customers or later records with the other sets: leakage

Validation setChoices are made on it

Compare models, tune settings, choose the threshold

When it is used:
Repeatedly during development
Does the model learn from it?:
Not directly, but choices are tuned to it
A score on it shows:
Which option is best; tends to be optimistic, because choices were made on it
How it goes wrong:
Its score is reported as the final result

Test set (hold-out)Used once

One final estimate after every choice is made

When it is used:
Once, at the end
Does the model learn from it?:
No: the model never learns from it
A score on it shows:
Expected performance on new data from the same conditions
How it goes wrong:
Used for tuning, or unlike production data

Proportions vary with the amount of data; some teams swap the names "validation" and "test", and with time-ordered data the test set holds the newest records.

Separate sets exist because a model can fit its training data too closely. Overfitting means it has learned the noise and accidents of its sample, for example that a few merchant IDs happened to appear in fraud cases: it scores high on training data and clearly lower on validation data. Underfitting is the opposite: the model is too simple, or its inputs carry too little information, and it scores poorly on both.

A test score is honest only if the test data influenced neither training nor any choice made during development. Otherwise it is data leakage, and the score overstates what users will get. Typical forms:

  • Duplicates and near-duplicates across sets: the same email forwarded twice, the same photo resized.
  • The same customer on both sides, so the model recognises the customer instead of learning fraud.
  • A random split of time-ordered data, which lets the model learn from the future; train on older records, test on newer ones.
  • A feature (an input field the model learns from) that contains the answer, such as a chargeback date filled in only after fraud is confirmed.
  • Choices made with the test set: preparation computed on all records before splitting, such as filling missing values with an average taken over every record, or tuning until the test score looks good.

Representative, clean and correctly labelled data

A model learns whatever is in its data, so reviewing the data is a test activity, like reviewing requirements. First ask whether the data represents the operating environment, the conditions the model will meet in production. Data from one region, device type, season or language, or from before a product change, may differ from what users send: this is distribution shift. After release it continues as data drift, when the inputs change (a new payment method), and concept drift, when the link between inputs and the correct answer changes (fraudsters change tactics). Ask how and when the test data was sampled, compare it with production data, and make sure the model will be monitored after release.

Then read a random sample of records yourself, not only summary statistics, and look for three kinds of defect:

  • Data quality: missing values, duplicates, wrong units or formats, out-of-range values, and inconsistent categories such as "KSA", "Saudi Arabia" and "SA" in one column. Convert a CSV sample with CSV to JSON with type inference on, so that numbers stay numbers, then paste the result into the API Response Analyzer to list empty and null fields, fields whose type changes between records, and duplicate records.
  • Labelling errors: wrong labels, labellers who disagree, unclear guidelines. A wrong training label teaches wrong behaviour; a wrong test label makes the metric itself wrong. Ask how disagreements were resolved, and re-check a sample.
  • Data bias: under-represented groups (few Arabic-language reviews in a review classifier) or labels that repeat past human decisions (past loan approvals). The model then works worse, or unfairly, for those groups; a later lesson covers bias in depth.

Try it: CSV to JSON Try it: API Response Analyzer

The confusion matrix and its metrics

To evaluate a classifier, compare each prediction on held-out data with its label. With two classes, the class you look for is called positive (fraud) and the other negative (legitimate). Each prediction is then a true positive (TP, fraud flagged), a false negative (FN, fraud missed), a false positive (FP, legitimate payment flagged) or a true negative (TN, legitimate payment passed). The table of these four counts is the confusion matrix.

Accuracy is the share of all predictions that are correct. Precision is the share of flagged cases that are really positive: when the model raises an alarm, how often is it right? Recall is the share of real positives the model catches: how much of the problem does it find? F1, the harmonic mean of the two, is high only when both are.

Accuracy has a trap. When one class is rare, a model that always answers "legitimate" scores high accuracy and catches nothing. Below, 95% of payments are legitimate, so that useless model reaches 95%, and the real model’s 96.5% is only 1.5 percentage points better. On imbalanced data, ask for the class balance, the confusion matrix and a baseline.

Fraud model on 2,000 validation payments at threshold 0.5: accuracy is 96.5%, but precision is 66.7% and recall only 60.0%, and always answering “legitimate” would already score 95.0%.
Actual class (the label)Model prediction
Predicted: fraudprecision = 60 / 90 = 66.7%Predicted: legitimate
Actual: fraud (100)recall = 60 / 100 = 60.0%TP = 60fraud flaggedPassFN = 40fraud missedFail
Actual: legitimate (1,900)FP = 30legitimate payment flaggedFailTN = 1,870legitimate payment passedPass
  • PassCorrect prediction: matches the label
  • FailError: the prediction differs from the label
Metrics at threshold 0.5
Accuracy (TP + TN) / all = 1,930 / 2,000 = 96.5%
Precision TP / (TP + FP) = 60 / 90 = 66.7%
Recall TP / (TP + FN) = 60 / 100 = 60.0%
F1 2 × P × R / (P + R) = 63.2%
Baseline Always “legitimate”: accuracy 95.0%, recall 0.0%
Text version
Validation set: 2,000 card payments, 100 of them fraud (5%). Threshold 0.5.

                            Predicted: fraud   Predicted: legitimate
Actual: fraud (100)              TP = 60             FN = 40
Actual: legitimate (1,900)       FP = 30             TN = 1,870

Accuracy  = (TP + TN) / all     = 1,930 / 2,000 = 96.5%
Precision = TP / (TP + FP)      =    60 / 90    = 66.7%
Recall    = TP / (TP + FN)      =    60 / 100   = 60.0%
F1        = 2 x P x R / (P + R)                 = 63.2%

Baseline that always answers "legitimate": accuracy 95.0%, recall 0.0%

Try it: Percentage Calculator

Worked example: choose a threshold by cost, check each segment

The fraud model scores every payment from 0 to 1 and flags it at or above the threshold. Lowering the threshold flags more payments: recall rises or stays the same, and precision usually falls. The right threshold is a business decision based on the cost of each error type. Here the product owner estimates that a missed fraud costs 400 SAR on average and a false alarm 25 SAR in review time and customer friction.

At 0.3 the model raises four times as many false alarms as at 0.5, yet the cost of errors falls from 16,750 to 9,000 SAR, so 0.3 wins under these costs, provided the review team can handle 205 flagged payments per 2,000 instead of 90. If a false alarm blocked the payment outright, its cost would rise and the answer could change. Record the costs and the reasoning, then measure the chosen threshold once on the test set.

Then break the result down, at every threshold you compare. At 0.5, overall recall is 60%, but 40% for accounts less than 30 days old (10 of 25 fraud cases) against 66.7% for older ones: one number hid the weakest group. Compute the metrics for each segment that matters, such as language, region, device or new users, with the sample size: 25 cases is a small sample, so 40% is a signal to investigate, not a precise value.

Validation set: 2,000 payments, 100 fraud. Cost: FN = 400 SAR, FP = 25 SAR.

Threshold  TP  FN   FP     TN  Precision  Recall  Cost of errors (SAR)
0.5        60  40   30  1,870      66.7%   60.0%  40 x 400 +  30 x 25 = 16,750
0.3        85  15  120  1,780      41.5%   85.0%  15 x 400 + 120 x 25 =  9,000

Recall by segment at 0.5   Fraud cases  TP  FN  Recall
Accounts < 30 days old              25  10  15   40.0%
Accounts >= 30 days old             75  50  25   66.7%

Common mistakes

  • Accepting one accuracy figure when a class is rare, without the confusion matrix, the class balance and a baseline.
  • Reporting the validation score as the final result, or tuning on the test set until it looks good.
  • Splitting at random when records are linked by duplicates, by customer or by time.
  • Assuming the test set represents production without asking where, when and how it was collected.
  • Treating labels as ground truth: wrong test labels make the metrics wrong.
  • Reporting only overall metrics, or comparing models measured at different thresholds or on different test sets.

The QA perspective

A tester rarely trains models but often reviews how they are evaluated. Before evaluation, work with the data scientist and the product owner to turn "the model should be good" into acceptance criteria per error type and per segment, for example a minimum fraud recall on new accounts at a precision the review team can handle. Treat the test dataset as a test basis: ask for its source, time period, class balance, labelling process and how overlap with the training data was prevented.

In the test report, record the model and dataset versions, the threshold, the confusion matrix and per-segment metrics with sample sizes. And keep testing the system around the model as usual: input validation, behaviour when the model service is slow or down, how flagged cases reach the review screen, and whether monitoring would notice drift.

Practice exercise

Evaluate a spam filter for a support inbox

Your task

A support inbox uses an ML spam filter. The data scientist shares the test results below: the test set was drawn at random six months ago from the same pool of emails as the training data, after removing exact duplicates. The support manager says that a real customer email lost in the spam folder is much worse than some spam getting through.

Evaluate the model as a tester. Pen and paper or the Percentage Calculator is enough.

Material
Spam filter, test set of 1,000 emails (200 spam), threshold 0.5

                         Predicted: spam   Predicted: not spam
Actual: spam (200)            TP = 180          FN = 20
Actual: not spam (800)        FP = 40           TN = 760

By segment           Emails  Spam   TP  FN  FP   TN
Arabic-language         150    40   24  16  12   98
All other emails        850   160  156   4  28  662
Steps
  1. Compute accuracy, precision, recall and F1, and the accuracy of a filter that never marks anything as spam.
  2. Compute precision and recall for Arabic-language emails and for all other emails.
  3. Decide which error is more expensive, which metric to watch and which way to move the threshold.
  4. Write three questions about the test data.
Show the model answer
Model answer

Accuracy = (180 + 760) / 1,000 = 94.0%; precision = 180 / 220 = 81.8%; recall = 180 / 200 = 90.0%; F1 = 2 × 0.818 × 0.900 / (0.818 + 0.900) = 85.7%. Never marking spam scores 800 / 1,000 = 80.0%, so accuracy alone says little.

Arabic emails: precision 24 / 36 = 66.7%, recall 24 / 40 = 60.0%. Other emails: precision 156 / 184 = 84.8%, recall 156 / 160 = 97.5%. 10.9% of real Arabic emails go to spam (12 of 110) against 4.1% of the others (28 of 690). With only 150 Arabic emails (40 spam, 110 not spam), confirm this on a larger sample.

False positives are the expensive error, so watch precision and the false-positive count, and raise the threshold: fewer emails are flagged and recall usually drops, which the manager accepts. Tune the threshold on the validation set, not the test set, and check the Arabic segment on its own; it may need more and better-labelled Arabic training data rather than a new threshold.

Possible questions (any three): Were near-duplicates (the same campaign slightly changed, forwarded chains) removed across the sets? Does a six-month-old test set still represent today’s emails? Who labelled the emails, and with which guideline? How many Arabic emails were in the training set?

Frequently asked questions

Do I need to be able to train models to test ML systems?

No. You need to understand how the data was split and labelled, how the model was evaluated and what the metrics mean, so that you can question the evaluation and design tests around it. Reading data and computing metrics in a spreadsheet or a short script helps, but training models is the data scientist’s job.

What is a good accuracy, precision or recall?

There is no universal value. It depends on the cost of each error type, on how rare the positive class is and on the baseline the model must beat. Agree the target values per segment with the product owner before evaluation, and write them down as acceptance criteria.

What is the difference between the validation set and the test set?

The validation set is used repeatedly during development to compare models, tune settings and choose the threshold, so its score tends to be optimistic. The test set is used once at the end, after every choice is made, to estimate performance on unseen data. Some teams swap the two names, so check which set a number came from.

Can I use a confusion matrix for an unsupervised model?

Only if you have labels for at least a sample. In anomaly detection, for example, domain experts can label a random sample of flagged and unflagged cases, and you estimate precision and recall from that sample. Without labels, you rely on expert review of samples and on checks that the results are stable and plausible.

References

Practise with Mutqan tools

Calculate percentages, percentage change, increase/decrease and what percent X is of Y.

Utilities

Convert CSV or TSV data to a JSON array of objects.

JSON & Data

Analyze an API response: structure, field types, nulls, duplicates, sizes and potential data-quality issues.

API Testing

Go deeper

Your progress on this topic

Part of the QA Roadmap