Skip to content
AI.info

ML data engineering

Missingness, Outliers, Corruption, and Repair

Diagnose missing and extreme values, choose repair or quarantine, and keep preprocessing inside the learning protocol.

By the end you can

Key idea

Fitting an imputer on the whole dataset has a catalogue number: L1.2

Means, medians, category frequencies and learned imputers are all estimated from data. Compute them over the full dataset and training has already seen the validation and test rows. This is not a stylistic preference. It is a catalogued error, with a number.

Leakage of this kind has been counted. A 2022 survey of machine-learning-based science by Kapoor and Narayanan found leakage errors in 17 fields, affecting 329 papers between them. Their taxonomy of data leakage gives this exact mistake its number: “[L1.2] Pre-processing on training and test set. Using the entire dataset for any pre-processing steps such as imputation or over/under sampling.” Imputation is named in the definition itself.

The library most teams reach for says the same thing in its own words. The scikit-learn documentation, in its section on data leakage, instructs: “Always split the data into train and test subsets first, particularly before any preprocessing steps.”

So fit imputation statistics on the training partition. Then apply the frozen transformation to validation, test and serving data. Cross-validation means fitting inside each fold. Time-dependent systems may need rolling or versioned statistics, because a global historical median can be built from rows the model has not reached yet. The correct boundary is the one your evaluation and deployment protocol already draws.

Any transformation that learns from data must respect split and time boundaries.

Steps

Investigate before transforming

Sample records and trace them through the pipeline before reaching for a statistical fix. The five steps run in order because each one produces the evidence the next one needs. A rate without a provenance trace cannot be classified. A classification without a downstream check cannot be defended when the number moves again six months later.

The artefact the process leaves behind matters as much as the fix. A cleaning rule a reviewer can trace back to a diagnosed cause is a rule that can be revisited. A rule sitting in the code with no record of what it was answering is one nobody will dare to remove.

FigureProcess · 5 steps
  1. 1. Quantify the pattern

    Measure missingness and extremes by field, source, entity, slice, and time.

  2. 2. Trace provenance

    Inspect raw payloads, join matches, parser logs, units, and source versions.

  3. 3. Classify the mechanism

    Separate valid rarity, non-applicability, delay, suppression, and system failure.

  4. 4. Choose a response

    Repair, represent, impute, transform, quarantine, or exclude with documented rationale.

  5. 5. Validate downstream behavior

    Check slice coverage, feature distributions, model effects, and serving parity.

Cleaning decisions should have a cause, a policy, a version, and a test.

Case

The 15,841 COVID cases an old spreadsheet template dropped

England lost cases to a silent truncation in the first days of October 2020. Public Health England's statement of 4 October 2020 recorded the size of the loss: “15,841 cases between 25 September and 2 October were not included in the reported daily COVID-19 cases.”

The mechanism, established by technical reporting at the time, was a container that ran out of room. Laboratory CSVs were appended into the legacy .XLS format, which caps a sheet at 65,536 rows. Each test result occupied several rows, so the practical ceiling was roughly 1,400 cases per sheet.

Nothing failed. No error was raised when the ceiling was passed. The file simply filled, and the rows past the end were never written. That is why the loss was measured in a press statement nine days later, rather than caught by the job that produced it.

Analogy

Restoring an old map without inventing coastline

Restoring an old map means working around stains, torn sections, handwritten notes and unusually shaped coastlines. Some marks are damage. Others are what the mapmaker recorded. Imputation resembles reconstructing a missing section from nearby patterns. Clipping resembles trimming an ink blot. A missingness indicator preserves the fact that someone repaired the sheet.

No restorer's hand shows up in what a reader takes from the map. Model training reads the repair itself. If one group's records are repaired more often, the missingness pattern may become a proxy for that group.

A correction should preserve uncertainty and provenance rather than pretending the original observation was complete.

Silent coercion, measured: 19.6% of papers, then 30.9%

When a record violates a critical invariant, send it to a quarantine path. That preserves the evidence and protects the published dataset, and the system can then classify, repair, replay or discard the record explicitly. The alternative is silent coercion. Its cost is not theoretical, and it has been counted twice.

Excel converts some gene names to dates by default. A 2016 screen of 35,175 supplementary Excel files, from 18 genomics journals published between 2005 and 2015, measured what that default does to the literature. Of the 3,597 papers carrying supplementary Excel gene lists, 704 contained gene-name errors — 19.6%, about one in five. Ziemann and colleagues stated the mechanism plainly in their abstract, in Genome Biology: “The spreadsheet software Microsoft Excel, when used with default settings, is known to convert gene names to dates and floating-point numbers.”

Five years later a larger rescan, with Ziemann again among the authors, covered articles published between 2014 and 2020. It found errors in 30.9% of those with supplementary Excel gene lists: 3,436 of 11,117. The rate went up, not down. A published warning did not stop a default from firing.

That is what a plausible-but-false value costs at scale, and the same failure is available in any pipeline. Parse an invalid date as epoch zero, or convert an unknown category to a common class, and you get a value that is well-formed, prints cleanly, and is wrong. Track quarantine rate, age, source, reason and resolution instead. A growing backlog is an operational failure even when the main pipeline stays green.

Decide in advance whether downstream datasets are provisional while quarantined records are unresolved. Late repairs may require a new snapshot, a label revision, or a note to consumers.

A visible unresolved record is often safer than a silently fabricated value.

Case

SQS and Pub/Sub keep the message they could not deliver

Quarantine-on-failure is not an unusual design. It is the documented default in production messaging, with named thresholds.

Amazon SQS moves a message aside after a set number of failed reads. Its developer guide defines the trigger: “The maxReceiveCount is the number of times a consumer can receive a message from a source queue before it is moved to a dead-letter queue.” The queue's redrive policy sets that value, so an operator chooses the threshold rather than inheriting a silent one.

Google Cloud Pub/Sub does the same, with published bounds. An undeliverable message is forwarded to a dead-letter topic after a configured maximum delivery attempts value whose minimum is 5, maximum is 100 and default is 5. In both systems the payload is wrapped and kept, not dropped.

A quarantine table is the same idea applied to rows. A named threshold, a destination that preserves the original, and someone who has to decide what happens next.

Example

Five extreme values with five different meanings

Two points equally far from the median can require opposite actions. The most dangerous extreme value is the one that is perfectly well-formed.

The Mars Climate Orbiter's carrier signal was last seen at approximately 09:04:52 UTC on 23 September 1999. The mishap investigation board's Phase I report of 10 November 1999 put the cause in one sentence: “The MCO MIB has determined that the root cause for the loss of the MCO spacecraft was the failure to use metric units in the coding of a ground software file, “Small Forces,” used in trajectory models.” The thruster performance data inside the SM_FORCES file was expressed in English rather than metric units. Every number in that file was numerically plausible. None of them tripped a check. The trajectory came in about 170 kilometres lower than planned at Mars orbit insertion. The board also recorded why the defect survived: “the root cause was not caught by the processes in-place in the MCO project.”

A wrong unit does not look extreme in the column that carries it. It surfaces as an outlier — or as nothing at all — several transformations downstream. That is why an extreme value is judged by tracing it to its source, not by its distance from the median.

  • Payment amount: a genuine corporate purchase is rare but valid and should remain represented in fraud decisions.
  • Patient age: 999 is a sentinel from a legacy system and should become explicit missingness, not an elderly patient.
  • Sensor temperature: a constant maximum indicates saturation and should trigger device-health handling.
  • Session duration: an app left open for a week needs a product-specific timeout rule rather than generic clipping.
  • Order total: an extreme value results from joining each line to every discount row and requires fixing cardinality.

Unusual data is often a message from the system

A null can mean “not applicable,” “not measured,” “not yet available,” “redacted,” “source failed,” or “join did not match.” Replace every null with one value and those distinctions are gone. An extreme value can be a genuine rare case, a different unit, a duplicated aggregate, a broken sensor or a parsing error. Remove it automatically and you may be deleting the very events the model exists to recognize.

Cleaning is a diagnostic and semantic task before it is a statistical transformation. Trace the unusual value to the behavior of its source, then decide what each state means for the consumer.

Whatever the offline job repairs, the serving path has to repair the same way. A training-only imputation rule or clipping threshold is one more form of training–serving skew.

Do not clean away evidence about how the measurement process failed.

Visual

Missing values arise through different mechanisms

The operational response depends on why the value is absent. That question has a formal literature, and a date on it.

Ignoring the process that removed a value is only safe under stated conditions. Rubin named those conditions in 1976, in Biometrika, and his abstract says exactly what they buy: “These conditions are the weakest general conditions under which ignoring the process that causes missing data always leads to correct inferences.” Where they do not hold, the process that removed the value is part of the model whether or not anyone modelled it.

The same three states were restated in operational form in 2010, by a National Research Council panel report on missing data in clinical trials, which attributes them to “Rubin (1976) and Little and Rubin (2002)”. Data are MCAR when “missingness does not depend on values of the covariates, auxiliary and outcome variables”. They are MAR when missingness is independent of the missing responses conditional on the observed ones. They are MNAR when MAR fails.

The five states below are the engineering form of the same question. They are what a pipeline can actually observe about a null. They are also the evidence from which the MCAR/MAR/MNAR judgement has to be argued.

FigureHierarchy · 5 levels
  • Not applicable

    The field has no meaningful value for this example by design.

    • Not observed

      The value exists but the process did not measure or collect it.

      • Not yet available

        The value may arrive after a delay or outcome horizon.

        • Suppressed or redacted

          Policy, privacy, or access controls intentionally remove the value.

          • Pipeline failure

            A source, join, parser, or transformation failed to produce the expected value.

A missingness code or indicator can preserve mechanism when one null representation cannot.

Comparison

Deletion, imputation, modeling, and correction

No strategy is universally best. Each one changes the population or the meaning of a feature.

The objection to filling a hole with a single number is not a matter of taste. It is written down, and two bodies published it independently in the same year. The EMA's guideline on missing data in confirmatory clinical trials, dated 2 July 2010 and in effect from 1 January 2011, states it in section 6.3.1: “A potential disadvantage of single imputation methods is that these methods risk biasing the standard error downwards by ignoring the uncertainty of imputed values.” The National Research Council panel of that same year made it Recommendation 10: single imputation methods such as LOCF and BOCF “should not be used as the primary approach to the treatment of missing data unless the assumptions that underlie them are scientifically justified.”

The cost is not in the imputed value. It is in what the column stops showing. A filled cell and an observed cell are indistinguishable downstream, so the uncertainty the fill introduced disappears from every interval computed after it. That is the argument for pairing any imputation with an indicator, and for treating the choice as a documented assumption rather than a default.

FigureComparison · 4 columns

Delete examples or fields

Remove incomplete data from the learning table.

  • Simple but can change population coverage
  • Reasonable for corrupted records with no recovery path
  • Dangerous when missingness is systematic
  • Example: drop a tiny set of unreadable files after investigation

Impute a value

Fill missing entries using a constant, statistic, or model.

  • Keeps examples and supports fixed-size inputs
  • Can shrink variance or invent precision
  • Needs fit-on-train and serving parity
  • Example: median plus a missingness indicator

Model absence explicitly

Represent missingness as a meaningful state or feature.

  • Preserves signal in the observation process
  • Can learn undesirable process bias
  • Needs interpretation and policy review
  • Example: “test not ordered” as a separate category

Repair from source

Correct units, parsing, duplicate aggregation, or instrumentation.

  • Addresses the cause instead of masking symptoms
  • May require backfill and version changes
  • Best for deterministic pipeline defects
  • Example: divide values after a cents-to-euros migration bug

Key takeaways