~/qa-guides

~/qa-guides/metamorphic-testing-for-machine-learning

>_ Metamorphic Testing for Machine Learning: A Worked Classifier Example

Move four training points, swap their labels, and trace each prediction back to its neighbors. See how a classifier using the wrong number of neighbors can still pass both checks.

Metamorphic testingMachine learning testingk-nearest neighborsTest design

Published

Short answer

Metamorphic testing for machine learning checks how a prediction should respond to a specified change in the training data, the input being classified, or both. The expected relationship between the two outputs is a metamorphic relation. For a nearest-neighbor classifier on a number line, adding the same offset to every point and the query preserves their relative positions. Swapping the names of two classes has a different expected result. With a unique majority, the winning class should take its new name.

A classifier using the wrong number of neighbors can pass both label checks. The example below starts with four labeled points, works out the predictions by hand, and finds a query that exposes that mistake. For the underlying method and examples with ordinary software functions, see the practical guide to metamorphic testing.

Build a classifier you can check by hand

A k-nearest neighbors classifier, or k-NN, assigns a label to a new observation by looking at nearby labeled observations. Here each training row has one numerical feature, x, and a class named A or B. The row ID lets a tester follow the same observation across runs. Only x enters the distance calculation.

The test contract uses exact nearest-neighbor search, distance abs(x - q) from the query coordinate q, and one vote per selected row. Start with k = 3. There is no feature scaling, clipping, or rounding in this fixture. If class votes tie, this example returns the alphabetically first tied label. Other classifiers can define their own tie policy.

The source query is q = 5. The last column gives the distance from each training row to that query.

RowxClassDistance
P11A4
P24A1
P38B3
P414B9

Fit the classifier on all four rows and run the source query. In order of increasing distance, the rows are P2, P3, P1, P4. The first three supply votes from A, B, and A. The expected prediction is A, with vote shares of 2/3 for A and 1/3 for B. P4 belongs to the training set but contributes zero votes to this query.

Keep that calculation as an independent check on the source run. Save the training rows, fitted model identifier, query, and returned class. Record neighbor IDs or class scores if your interface exposes them. With a label-only interface, the hand calculation still gives an expected answer.

Test case 1. Shift the training points and the query together

Add 10 to each training coordinate to obtain 11, 14, 18, 24, keeping the row IDs and labels attached. Fit a second classifier with the original settings. Send it q = 15, the translated version of the original query.

For P2, the original distance was abs(4 - 5) = 1. The new distance is abs(14 - 15) = 1. The offset cancels for each row, so P2, P3, and P1 remain the selected neighbors. The translated model must return A. If it also returns vote shares, both named classes should retain their original shares. The same argument works for another common offset as long as the effective feature values preserve those distances.

Use a control that changes only one side. Send q = 15 to the original classifier. P4 is now one unit away, P3 is seven away, and P2 is eleven away. Those neighbors vote B, B, A. The correct result for this control is B.

RunqNeighborsClass
Source5P2, P3, P1A
Both +1015P2, P3, P1A
Query +1015P4, P3, P2B

That last row helps investigate a failed test. If the translated run returns B, check which fitted model served the request. The control gives you the exact neighbor sequence to look for if an old model received the new query.

Also check where preprocessing happens. Suppose a serving pipeline caps every feature at 10. All four translated coordinates and the translated query would reach the classifier as 10. The proof about distinct distances applies to the raw inputs, and the cap has changed them. Capture the features reaching the classifier before using this relation for that pipeline.

Test case 2. Swap the class names and compare the named scores

Start again from the original coordinates. Replace A with B and B with A in every training label, fit a fresh model, and keep the query at 5. Labels for P1 through P4 are now B, B, A, A. This transformation leaves every distance unchanged.

Read the new labels in neighbor order. P2 now votes B, P3 votes A, and P1 votes B. The expected class is B. The source A votes became follow-up B votes, so compare the source score for A with the follow-up score for B. Make the reciprocal comparison for the other class.

ModelA shareB share
Original2/31/3
Swapped1/32/3

A serving API might return an array of scores alongside a list of class names. A source response with names [A, B] and scores [2/3, 1/3] can validly become names [A, B] with scores [1/3, 2/3]. A response listing the follow-up names as [B, A] would instead display [2/3, 1/3]. Pair each score with its reported class before checking the mapping.

If the follow-up model selects the expected rows and gives B the larger share but the API still emits label A, inspect the step that converts an internal class index back into a public label. If the scores themselves still favor A, first confirm which training labels were fitted. Those observations narrow the investigation to different parts of the prediction path.

Test case 3. Work out a tied vote before reporting a failure

Form a separate pair of runs with k = 4 in both models. Use the original labels for the source and swapped labels for the follow-up, with q = 5 for each. All four rows now vote. Both runs give each named class two votes and a share of 1/2.

Under the example's alphabetical tie policy, the source returns A and the follow-up also returns A. A test expecting the renamed source winner B would report a false failure. The class names changed, the same two classes still share the lead, and the final decision again favors the name A.

Suppose instead that the product breaks a vote tie in favor of the class of the closest neighbor. P2 is uniquely closest to this query. Its original label is A and its renamed label is B, so this policy gives A followed by B. Both policies see the same two-to-two votes. The expected final labels depend on which decision rule the product promises.

Xie and colleagues describe how resolving equal class scores can affect a label-permutation test for k-NN. If the product leaves the winner of a tie unspecified, check the vote counts and membership in the set of tied winners. Record the chosen label as an observation. Application of Metamorphic Testing to Supervised Classifiers

Test case 4. Two rows compete for the last neighbor slot

A second kind of tie occurs earlier, while choosing which rows get to vote. Restore k = 3 and the original labels. Move the query to 7.5. P3 is 0.5 away and P2 is 3.5 away. P1 and P4 are each 6.5 away, with one slot left to fill.

Third rowVotersVotesWinner
P1P3, P2, P12 A, 1 BA
P4P3, P2, P41 A, 2 BB

Each possible selection has a clear majority. An alphabetical rule for tied votes never takes effect here. To decide whether reversing the training rows should preserve the label, you need the rule for selecting among equally distant rows.

For a policy that prefers the lowest stable row ID, P1 wins the slot in either training order. If equal distances are resolved by the first row encountered, fitting P1, P2, P3, P4 selects P1, while fitting the reversed order selects P4. Keep the IDs attached when reordering. If the product has no specified selection policy, use q = 5 for a strict row-order invariance test and keep q = 7.5 as a probe for order dependence.

This distinction matters in real libraries. Scikit-learn documents that training order can affect a prediction when the two rows on opposite sides of the neighbor cutoff are equally distant and carry different labels. KNeighborsClassifier documentation

Catch a wrong classifier that passes the relations

Imagine the serving code silently uses just the closest row. At q = 5 that row is P2, class A. After the coordinate shift it is still P2. After the name swap it is P2 with label B. A test suite that checks only the three predicted labels would see exactly the expected A, A, B sequence.

Use a second query, q = 7, with the original four points and the required k = 3. P3 is closest at distance 1 and votes B. P2 is next at distance 3 and votes A. P1 is third at distance 6 and also votes A. P4 is outside the neighborhood at distance 7. The correct majority is A. A one-neighbor implementation would return B.

Keep the query at 7 as a regression case even for a service that exposes only a final label. In a failure report, attach the four training rows, identify the model that served the query, state the configured neighbor count, and give the three independently calculated voters. If the service reports only P3, investigate neighbor selection. If it reports all three expected voters and returns B, inspect weighting and label decoding. The same observed label can arise at either stage.

FAQ

The translation and label-swap cases need two known fitted models. A QA engineer can use a prediction endpoint if the team supplies those model versions and a way to select them. With a single fixed model, changing just the query exercises the input-only control. For the original model in this example, the expected prediction at 15 is B.

Compare named scores at the precision the API promises. A uniform vote share of two out of three displays as 0.67 under rounding to the nearest hundredth. Equal displayed scores can hide different underlying values in a larger model. Use unrounded scores or the selected votes when deciding whether the tie policy applied.

Suppose the service emits a class only when its winning vote share reaches 0.70. The two-to-one majority at q = 5 falls below that threshold. The original and label-swapped runs should both abstain, while their named scores still swap. Test the classifier's vote and the service's threshold as two observable decisions when both outputs are available.

Recalculate the expected winner under the product's weight function. At q = 7, weighting each of the three neighbors by inverse distance gives B a weight of 1/1 = 1. The two A neighbors contribute 1/3 + 1/6 = 1/2 together. A distance-weighted model would correctly return B on the very case that requires A under uniform voting. Record the weight setting with the test data.

Accuracy requires reference labels for an evaluation set representing the task. These tests check specific relationships and, for the four-point dataset, exact predictions under a known rule. For a model used in a real product, a labeled evaluation set answers how often its predictions are correct. A retained source and follow-up pair helps explain which behavior changed when a version regresses.

Ready to turn this guide into a working QA project with statuses, comments, and CSV export?