How We Test Machine Learning Code

One unchanged model spans 4.20 accuracy points across 50 splits. This is the protocol we use so a reported machine learning number can be checked.

Dot plot of fifty train and test splits of one logistic regression model, ranging from 0.9580 to 1.0000 with a mean of 0.9778, above a bar for the majority-class baseline at 0.6294.

Fit the same logistic regression model to the same 569 breast cancer records 50 times and change nothing but which rows land in the test set. The accuracy you would report runs from 0.9580 to 1.0000, with a mean of 0.9778. The model, the data, the fitting code and the library version are identical in all 50 runs, and two of them scored a perfect 1.0000 on 143 held-out rows. A reported score therefore carries about four accuracy points of movement that the reader never sees, and a tutorial that reports one split has no way to say where inside that band its number fell.

This page documents the protocol behind every machine learning article on MYCPLUS: how data is split, what counts as a baseline, how a from-scratch implementation is checked against a library, how many repeated splits an improvement claim needs, what is recorded about the machine the code ran on, and what gets reported when a result is negative. Each rule below comes with the measurement that justifies it or the failure it prevents, and the demonstration script is one 193-line Python file that runs in under a minute on one CPU. Every number in the tables and figures here was produced for this page on Windows 11 (build 26300) with Python 3.14.6, NumPy 2.5.5 and scikit-learn 1.9.1, and then reproduced on Ubuntu 24.04.5 under WSL 2 with Python 3.12.3 and the same library versions: the 50 split scores are identical on both systems and the numerical agreement gaps differ in the last two digits, which is shown below. The results quoted from the other articles in the series were run on Ubuntu 24.04 with Python 3.15.2 and the same library versions, then repeated on Windows 11 with Python 3.14.6.

The Short Answer

  • Split before anything else, and fit every transformation on training rows only. A scaler, an imputer or a feature selector fitted on the full dataset leaks test information into training and inflates the score.
  • Report a baseline in the same table as the model. A majority-class classifier scored 0.6294 on the breast cancer test rows while finding no cancer at all.
  • Repeat the split and report the spread, not one score. Fifty splits of one unchanged model spanned 4.20 accuracy points.
  • Compare two models on the same splits, not on two different splits. The paired standard error here is 0.0016, so differences below about 0.3 accuracy points are not established by this experiment.
  • State a tolerance when checking a from-scratch implementation against a library. Agreement to 1e-14 shows the arithmetic matches; it does not show the model is right.
  • Record versions and capture the output. Every number on this page comes from a file the script wrote, not from a console that was retyped.

Why One Split Is Not a Result

A test set is a sample of rows, and the score computed from it is a sample statistic. With 143 test rows, one row is worth 0.7 accuracy points. The 50 splits here have a standard deviation of 0.0114, which is under two rows. Run the same model on a different 143 rows and it is normal for the count of correct predictions to move by a row or two either way, and this is on a dataset where the model is strong and the classes are easy to separate.

The baseline in that experiment never moves. DummyClassifier(strategy="most_frequent") predicts one class for every row, so its accuracy is the majority share of each test set, and stratified splitting keeps that share close to 62.94 percent. Its standard deviation across the 50 splits is 0.0000 to four decimal places. A baseline with no variance is the right shape for the job: it cannot improve because the split changed, so it anchors the comparison.

The useful number is not the model’s mean accuracy. It is the difference between the model and something that makes no decisions, measured on identical rows. That difference averages 0.3484 here, and because the two scores rise and fall together with the difficulty of the split, its standard deviation is 0.0114 rather than the 0.0161 the two separate standard deviations would suggest. Dividing by the square root of 50 gives a standard error of 0.0016, and twice that, 0.0032, is the smallest gap this experiment can call real. Pairing cut the noise from 4.2 accuracy points to 0.3.

Fifty train and test splits, the same model each time 0.60 0.65 0.70 0.75 0.80 0.85 0.90 0.95 1.00 accuracy on the 143 held-out rows Logistic regression Most frequent class split 0: 0.9580 mean 0.9778 range 4.20 points 1.0000 0.6294 on all 50 splits predicting the majority class every time
Figure 1: Every point is one stratified 75/25 split of the 569 breast cancer rows, fitted and scored again from scratch. The model averaged 0.9778 with a standard deviation of 0.0114, but the individual splits run from 0.9580 to 1.0000, 4.20 accuracy points apart, and 2 of the 50 splits produced a perfect score. The baseline never moves: it scores the test set’s majority share on every split. A single split, which is what most tutorials report, lands anywhere in that range.

The Protocol, in Order

  1. Split first, then fit the preprocessing. The scaler, imputer, encoder and any feature selection go inside a pipeline and see training rows only. Fitting a scaler on all rows before splitting is the most common leak in introductory tutorials, because it changes nothing visible in the code and improves the score by an amount nobody checks.
  2. Divide three ways when a choice has to be made. Training data fits the model, validation data chooses hyperparameters or the decision threshold, and the test set is opened once, at the end, to report a number. Tuning on the test set and reporting the tuned score is the second most common leak.
  3. Always train a baseline that could have been written in three lines. The training mean for regression, the majority class for classification, the prior probabilities for a probabilistic classifier. The linear regression article’s baseline scored R² −0.012 against the model’s 0.453, and the logistic regression article’s baseline scored 0.632 accuracy with a recall of zero. The first would look like a broken model and the second like a working one in a summary that reported a single number; both are what a model has to beat.
  4. Repeat the split and report mean, standard deviation and range. Fifty splits in this page’s demonstration, 100 in the linear regression article, 50 cross-validation fits for the k in the KNN article. Where randomness affects the result, the number of repetitions is part of the result.
  5. Compare models on the same splits. The paired difference and its standard error, not two independent means and two independent standard deviations. This is what makes a 0.0032 threshold possible instead of the 0.0046 that two independent samples of this size would give.
  6. Check from-scratch code against a reference with a stated tolerance. The rule for this series is 1e-10 relative on fitted weights and predictions, chosen because it is far tighter than any modelling difference and still loose enough not to fail on floating-point reassociation. The demonstration script’s least-squares fit agrees with scikit-learn to 1.066e-14 relative, which is 4 orders of magnitude inside the tolerance. State which reference, which split and which quantity is being compared.
  7. Record the environment, not the intention. Python version, every library version, the operating system and its build, and the CPU for anything timed. Two machines can disagree about singular matrix behaviour in the same library, as the linear regression article found: np.linalg.solve on collinear columns returned weights in the trillions on one machine, raised LinAlgError on another and returned plausible-looking weights on a third.
  8. Capture output to a file and quote the file. A score pasted from a console into prose drifts from the code the first time the code changes. Every output block in this series comes from a file that a script wrote, and the file is committed next to the script.
  9. Run it on a second operating system. The demonstration on this page was run on Windows 11 and on Ubuntu 24.04.5 under WSL 2 with the same library versions. Every one of the 50 scores matched to the last printed digit; the two numerical agreement gaps moved in the last two digits, and one collinear solve() elsewhere in the series returned weights in the trillions on Linux while raising LinAlgError on Windows with the same NumPy version. Identical scores are the expected result; a stated tolerance is what makes the comparison meaningful instead of a hunt for bit equality.
  10. Apply deliberate bugs and confirm each one fails a test. 11 in the linear regression article, 11 in logistic regression, 16 in KNN, 17 in decision trees. The first attempt at this usually leaves a survivor: in linear regression, a mutant that removed the division by n from the mean squared error passed every test until a test was added that compared the reported loss with the definition.
  11. Benchmark as a measurement, not a demonstration. One machine, identical work, warm-up, repeated runs, medians and ranges, and separate names for pure Python, NumPy and C++ whenever native code is involved. The KNN article reports five implementations and five separate ranges rather than one flattering ratio.

A Worked Run of the Protocol

The script takes one dataset, one model and one baseline and reports what the protocol produces. The dataset ships with scikit-learn, so the script needs no network access and no download step.

Dataset cardValue
NameBreast Cancer Wisconsin (Diagnostic)
Accesssklearn.datasets.load_breast_cancer, bundled since the package’s first release
LicenseDistributed inside scikit-learn, whose licence is BSD-3-Clause
Rows and features569 rows, 30 numeric features
Classes212 malignant (37.3%), 357 benign (62.7%)
Split75/25, stratified, random_state=0 to 49, 143 test rows per split
PreprocessingStandardScaler inside the pipeline, fitted on training rows only
ModelLogisticRegression, max_iter=5000, solver="lbfgs", default C=1
BaselineDummyClassifier, strategy="most_frequent"

The whole experiment is a loop over split seeds. Nothing outside the loop changes, and the scaler lives inside the pipeline so it cannot see the test rows:

def make_model() -> object:
    # Scaling lives inside the pipeline, so it is fitted on training rows only.
    return make_pipeline(
        StandardScaler(),
        LogisticRegression(max_iter=5000, solver="lbfgs"),
    )


def split_scores(X: np.ndarray, y: np.ndarray) -> dict[str, list[float]]:
    model_scores: list[float] = []
    baseline_scores: list[float] = []
    for seed in range(SPLITS):
        X_train, X_test, y_train, y_test = train_test_split(
            X, y, test_size=TEST_SIZE, random_state=seed, stratify=y
        )
        model = make_model().fit(X_train, y_train)
        baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
        model_scores.append(float(model.score(X_test, y_test)))
        baseline_scores.append(float(baseline.score(X_test, y_test)))
    return {"model": model_scores, "baseline": baseline_scores}

The agreement check is separate because it asks a different question. It fits least squares two ways on one split, once by solving the normal equations in the least-squares sense with an intercept column appended by hand, and once with scikit-learn, then compares the fitted values:

def tolerance_check(X: np.ndarray, y: np.ndarray, seed: int = 0) -> dict[str, float]:
    """From-scratch least squares against scikit-learn on the same split."""

    X_train, _, y_train, _ = train_test_split(
        X, y, test_size=TEST_SIZE, random_state=seed, stratify=y
    )
    scaler = StandardScaler().fit(X_train)
    X_train_scaled = scaler.transform(X_train)

    # From scratch: add an intercept column and solve in the least-squares sense.
    design = np.column_stack([X_train_scaled, np.ones(len(X_train_scaled))])
    weights, *_ = np.linalg.lstsq(design, y_train.astype(float), rcond=None)
    scratch = design @ weights

    library = LinearRegression().fit(X_train_scaled, y_train.astype(float))
    reference = library.predict(X_train_scaled)

    prediction_scale = max(float(np.abs(reference).max()), 1e-12)
    prediction_gap = float(np.abs(scratch - reference).max())
    weight_gap = float(np.abs(weights[:-1] - library.coef_).max())
    weight_scale = max(float(np.abs(library.coef_).max()), 1e-12)
    return {
        "prediction_gap": prediction_gap,
        "prediction_relative": prediction_gap / prediction_scale,
        "weight_gap": weight_gap,
        "weight_relative": weight_gap / weight_scale,
    }

Running both gives the page’s measurements:

MYCPLUS testing protocol: split variance and baseline, measured
dataset        breast_cancer: 569 rows, 30 features
class balance  0: 212 (37.3%), 1: 357 (62.7%)
protocol       50 stratified splits, test_size=0.25, random_state=0..49
model          StandardScaler then LogisticRegression (default C=1)
baseline       DummyClassifier, most frequent class

model accuracy      mean 0.9778  sd 0.0114  min 0.9580  max 1.0000
baseline accuracy   mean 0.6294  sd 0.0000  min 0.6294  max 0.6294
spread of one model's score across splits   4.20 accuracy points
splits where the model scored 1.0000        2 of 50

paired difference model - baseline   mean 0.3484  sd 0.0114
standard error of that difference    0.0016
smallest difference worth reporting  0.0032 (two standard errors)
splits where the model beats the baseline   50 of 50

score if only split 0 had been run       0.9580
highest-scoring split: 37  1.0000  (+2.22 points from the mean)
lowest-scoring split:  0   0.9580  (-1.97 points from the mean)
gap between the highest and lowest split     4.20 points

agreement between the from-scratch fit and scikit-learn, split 0
max prediction gap        4.330e-15  (relative 3.194e-15)
max coefficient gap       1.066e-14  (relative 1.062e-14)
tolerance used in this series   1e-10 relative for fitted weights
verdict                         within tolerance

wrote split_scores.json

Three things in that output are worth separating. The model’s mean is 0.9778, but the individual splits run from 0.9580 to 1.0000, and the gap between the best and worst split is 4.20 points on code that did not change. Split 0 happens to be the worst of the 50 and split 37 the best, so a first attempt and a lucky rerun can differ by 4.2 points on identical code. The baseline sits at 0.6294 on every split, and the paired difference against it has a standard error of 0.0016, which is what makes a 0.3-point claim defensible and a 0.1-point claim not.

The agreement output reads 4.330e-15 for predictions and 1.066e-14 for coefficients on Windows, and 2.554e-15 and 4.774e-15 on Ubuntu, on the same split with the same library versions. Both are at the level where double-precision arithmetic stops discriminating, which is the expected result for two implementations of the same least-squares problem. The gap between the two systems is not a bug in either: adding the same products in a different order moves the last digit or two, and the linear algebra libraries are built differently on the two platforms. A line-by-line diff of the two captures has exactly two differing lines, the two agreement gaps, and nothing else. That is the reason the series states a tolerance of 1e-10 instead of claiming bit-identical output. The check is evidence that the from-scratch code computes what scikit-learn computes. It is not evidence that the fit is a good model of anything, and the page does not claim that.

Agreement check, split 0Windows 11, Python 3.14.6Ubuntu 24.04.5, Python 3.12.3
Maximum prediction gap4.330e-152.554e-15
Relative prediction gap3.194e-151.883e-15
Maximum coefficient gap1.066e-144.774e-15
Relative coefficient gap1.062e-144.759e-15
Against the 1e-10 toleranceInside, by about four ordersInside, by about four orders
The 50 split scoresMean 0.9778, sd 0.0114, range 0.9580 to 1.0000Identical to the last printed digit

The Same Protocol, Already Applied

Four articles in the series have been through it. The counts are from their own claims audits, and each article’s “What I Verified” table is the record.

ArticleDataSplitUnit testsDeliberate bugs caught
Linear regression442 diabetes records, 10 features353/892211 of 11
Logistic regression569 breast cancer records, 30 features455/1142011 of 11
K-nearest neighbors178 wine records, 13 features133/452016 of 16
Decision trees569 breast cancer records, 30 features455/1141917 of 17

Three findings from those runs show why the protocol is not paperwork. The linear regression article ran 100 splits and found test R² anywhere from 0.258 to 0.658 around a mean of 0.467, so a single split in that range can understate or overstate the model by 0.2 of R². The decision tree article grew 20 trees with nothing changed but random_state and got trees that classified between 103 and 109 of the same 114 tumours correctly. And the collinear-matrix finding above came from a deliberate bug hunt, not from reading documentation.

What the Protocol Cannot Do

It cannot make a weak model good, and it cannot tell you whether the task matters. A perfect score on a dataset with a leaking feature is still a broken result, and no number of splits detects it.

It also assumes something about the rows. Repeated random splits treat observations as exchangeable, which is wrong for time series, where the split has to respect chronology, and for grouped data such as several images of one patient, where a group-aware split is needed to keep the test set independent. Neither case appears in the pilot articles, and both would need the protocol extended before it applied.

Finally, agreement and mutation checks are not correctness. Two implementations of the same wrong formula agree to 1e-14. A test suite that catches every mutant you thought of says nothing about the bug you did not think of. These checks raise the floor; they do not certify the ceiling.

Common Ways a Result Misleads

Scoring on the rows the model was fitted on. A model always looks better on its training data, and the gap between training and test scores is itself diagnostic. Report both, and treat a small gap with suspicion when the model is flexible.

Fitting the scaler on everything. The leak is invisible in the code and costs a fraction of a point, which is exactly why it survives review. Put the scaler in a pipeline.

Reporting a difference smaller than the paired noise. The number to compare against is the standard error of the paired difference, not a rule of thumb about percentage points. Here that threshold is 0.0032.

Choosing the metric after seeing the results. Accuracy on a 62.7/37.3 split scored 0.6294 with a recall of zero. A metric chosen before the run, and reported with the confusion matrix, is harder to fit to a story after the fact.

Quoting a benchmark without its range. The KNN article’s C++ implementation measured between 268.7 and 291.5 microseconds per query across five runs on one machine. One of those numbers alone is a claim about a machine’s mood, not about an implementation.

Key Takeaways

  • A single train/test split is one sample. A 4.20-point range on identical code is normal, so the split is part of the result and belongs in the report.
  • A baseline is not optional. It is the only number that says whether a model learned anything, and it is usually three lines of code.
  • Pair the comparison. Two models compared on the same splits give a 0.3-point threshold; on different splits, the 4.2-point range between splits is the noise they are arguing over.
  • State a tolerance for from-scratch against library. Agreement to 1e-10 relative or better is the series’ rule, and the direction of the check matters: it validates arithmetic, not modelling.
  • Repeat and disclose. Fifty splits, 100 splits, 50 cross-validation fits; the count is a property of the claim.
  • Capture the output, record the environment, run it twice on two systems. The second system here matched every score and moved the agreement gaps in the last two digits, which is what a stated tolerance is for; the one genuine platform disagreement in this series so far showed up only on the second system.

Conclusion

The protocol is not complicated: split first, fit preprocessing inside the split, keep a baseline, repeat, pair, state a tolerance, record versions, capture output, break the code on purpose, and run it somewhere else. What makes it work is that each step produces a number that can be checked, and the numbers here are small enough to fit on one page.

Every article in this series carries a “What I Verified” table at the end for exactly this reason, and the pages that use this protocol are collected in the artificial intelligence section. For the same protocol applied to a scored classifier with an unbalanced test set, see logistic regression, where the majority-class baseline scores 0.632 accuracy and finds no malignant tumour at all.

Source Code and Tests

The demonstration is one file, protocol_check.py, and it is in the machine-learning/testing-protocol directory of the MYCPLUS Python examples repository, together with the Windows and Ubuntu captures this page quotes. It has no test suite of its own because it asserts nothing, it reports; the numbers it prints are the numbers this page quotes, and rerunning it reproduces them exactly on the same library versions.

Run it:

python -m pip install -r requirements.txt
python protocol_check.py

It writes results/split_scores.json next to itself and prints the captured output block above. The figure is drawn from that JSON file, so no number in the figure is typed by hand.

The four algorithm articles cited in the table have their own directories, tests and CI workflows in the MYCPLUS Python examples repository: linear-regression, logistic-regression, k-nearest-neighbors and decision-tree.

What I Verified

CheckWindows 11Ubuntu 24.04.5 (WSL 2)
EnvironmentBuild 26300, Python 3.14.6, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1WSL 2 kernel 5.15.146.1, Python 3.12.3, NumPy 2.5.5, scikit-learn 1.9.1, SciPy 1.18.1
ProcessorIntel Core i7-8700K, 3.70 GHzSame processor, 12 vCPU visible
Demonstration scriptRan to completion; output in results/protocol_check.txt; rerun produced identical numbersRan to completion in a virtual environment; output in results/protocol_check-ubuntu.txt
50 splits, model and baselineMean 0.9778, sd 0.0114, range 4.20 points; baseline 0.6294 on every splitIdentical to the last printed digit, all 50 scores
Paired differenceMean 0.3484, standard error 0.0016, two standard errors 0.0032, model above baseline on 50 of 50 splitsIdentical
Agreement with scikit-learn4.330e-15 on predictions, 1.066e-14 on coefficients2.554e-15 on predictions, 4.774e-15 on coefficients
Against the 1e-10 relative toleranceInsideInside
FigureDrawn from results/split_scores.json, values match both capturesSame
Quoted article resultsTaken from the four live articles’ own claims auditsNot re-run here

Not covered: macOS, ARM processors, other Python or library versions, GPU or multi-threaded BLAS settings, and the script has been run on the two systems above only. The protocol rules that the four algorithm articles exercised on Ubuntu 24.04 with Python 3.15.2 are recorded in those articles, not re-run for this page.

Scroll to Top