smartyfy.mrindigi.com

AI & Machine Learning Master Course — 033. Missing data and missingness mechanisms

Smartyfy AI & Machine Learning Master Course

Course ID: smartyfy-ai-ml-master-200

Lesson 033: Missing data and missingness mechanisms

Prerequisites: Lesson 032. Learning outcome: Diagnose missingness and compare appropriate imputation strategies.

1. A blank cell has a collection history

Missing data is an observation-process problem before it is a software problem. A parcel’s mass might be missing because a scale lost power, because a warehouse never installed scales, or because unusually heavy parcels bypassed the usual station. All three produce the same blank value but imply different risks for analysis and prediction.

Preserve a distinct representation for missingness, such as a numeric NaN, rather than replacing blanks with zero during ingestion. Zero can be a meaningful observation and may violate the physical range of mass. Also distinguish “not applicable,” “not measured,” “refused,” and “temporarily unavailable” when the collection system records those reasons. Combining them can erase useful context.

Audit rates by time, source, and relevant groups using development data. Check whether the target is missing, whether labels arrive late, and whether feature missingness itself occurs only after the prediction timestamp. An imputed input cannot repair an unobserved outcome or make future information available in the past.

2. Understand three missingness mechanisms

Missing completely at random, or MCAR, means the missingness process is independent of both observed and unobserved values in the analysis. A genuinely random, value-independent sensor transmission failure is a possible example. It is a strong assumption, not a synonym for an unpredictable blank. Under MCAR, complete cases can remain representative for some analyses, but discarding rows still loses information.

Missing at random, or MAR, means that after conditioning on observed information, missingness does not further depend on the missing values. Suppose recorded warehouse identity explains scale availability and, within each warehouse, missingness does not depend on parcel mass. MAR could then be plausible relative to that observed information. “At random” here does not mean all rows are equally likely to be missing.

Missing not at random, or MNAR, means missingness still depends on the unobserved value after accounting for observed information. If heavier parcels are less likely to be weighed even within the same warehouse and service level, the missing masses may systematically exceed the observed ones. A global median can then be badly misleading.

These mechanisms concern a proposed data-generating process. Observed data alone generally cannot distinguish all MAR and MNAR explanations. Collection knowledge, audits, supplemental measurements, and sensitivity analysis matter. An association between missingness and an observed field can contradict simple MCAR assumptions without proving that a particular MAR model is correct.

3. Compare strategies according to the task

Complete-case deletion is simple but can waste scarce data and change the represented population. Constant imputation can be useful when a value such as “unknown” is an explicit category; for numeric features an arbitrary sentinel may create artificial distances. Mean or median imputation is a baseline, with the median less sensitive to extreme observed values.

Single-value imputation compresses variation and alters relationships among features. It is not a reconstruction of the actual missing measurement. Neighbor-based or model-based imputation can use other features, but adds fitted complexity and assumptions. Multiple imputation creates several plausible completed datasets and combines analyses under an appropriate framework; simply averaging several predictions is not the whole inferential procedure.

A missingness indicator records whether the original value was absent. It may help a predictive model distinguish an imputed median from a measured median. However, it can encode a temporary collection process or an undesirable proxy. If scales are repaired after deployment, a relationship learned from missingness may disappear. Evaluate the strategy under plausible future collection conditions.

Target values require separate care. Training a supervised model usually requires observed labels, but deleting missing-label cases may bias evaluation if difficult outcomes are less likely to be recorded. Do not fill unknown labels with the majority class and then report accuracy as though those labels were observed. Define label availability and investigate why outcomes are absent.

4. Keep learned imputation inside training

Suppose training masses are [1, 2, missing, 4, 5, 6]. Their observed median is 4. Validation masses [100, missing] must use that same learned median, giving [100, 4]. Refitting the imputer on validation data would replace its missing value with 100 and would evaluate a different, contaminated preprocessing procedure.

Cross-validation adds an inner boundary. Put the imputer and estimator in a pipeline so each fold learns its median only from that fold’s training rows. Fitting imputation once on all training-plus-validation data before cross-validation lets each validation fold influence the values used to fit its model. A pipeline prevents this specific leakage when the split design itself is appropriate.

All-missing columns need an explicit policy. Some imputer configurations drop them, affecting feature dimensions; others retain them with a constant. Record the behavior and test inference-time schemas. A column that first becomes missing in production also deserves attention because a training-fitted automatic indicator may not include that new missingness pattern.

Training masses 1, 2, missing, 4, 5, 6 yield an observed median of 4 kilograms. Applying that frozen rule to validation values 100 and missing gives filled masses 100 and 4, with missing flags 0 and 1. Each cross-validation training fold must fit its own imputer.
A fitted median supplies a substitute, while an indicator preserves the original absence. Validation mass 100 does not alter the training-fitted imputer. Open full-size diagram

5. Run a fold-safe baseline

This CPU example requires Python 3.10 or later, NumPy 1.24 or later, and scikit-learn 1.2 or later. No API key, paid service, or external dataset is needed. The median imputer appends one indicator for the training feature that contains missing values. A ridge regressor and shuffled cross-validation illustrate plumbing for independent synthetic observations, not a recommendation for time-dependent parcels.

The program prints the full-training median, the transformed validation rows, and confirms that every fold produced a finite score. It also inspects each fitted fold imputer against that fold’s observed training median. The final test set is absent. Compare alternative imputation strategies through this same development process before freezing a final evaluation plan.

import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import KFold, cross_validate

X = np.array([[1.], [2.], [np.nan], [4.], [5.], [6.]])
y = np.array([2., 4., 6., 8., 10., 12.])
validation = np.array([[100.], [np.nan]])
pipe = make_pipeline(SimpleImputer(strategy="median", add_indicator=True), Ridge(alpha=1))
splits = list(KFold(3, shuffle=True, random_state=33).split(X))
cv = cross_validate(pipe, X, y, cv=splits, scoring="neg_mean_absolute_error", return_estimator=True)
for (train, _), fitted in zip(splits, cv["estimator"]):
    assert np.isclose(fitted["simpleimputer"].statistics_[0], np.nanmedian(X[train]))
pipe.fit(X, y)
transformed = pipe["simpleimputer"].transform(validation)
assert np.allclose(transformed, [[100., 0.], [4., 1.]])
assert np.all(np.isfinite(cv["test_score"]))
print("training median:", pipe["simpleimputer"].statistics_[0])
print("validation value and indicator:", transformed.tolist())
print("fold checks passed:", len(cv["estimator"]))

Practice: four questions with worked answers

1. Training values are [2, 4, missing, 8]. What fills a missing validation value with median imputation?

Answer: The observed training median is 4, so use 4. Do not recalculate it from validation observations or include their values when fitting the imputer.

2. Missingness depends on recorded warehouse, but not on mass within warehouse. Which mechanism may fit?

Answer: MAR may be plausible conditional on warehouse. Missingness need not be equally likely everywhere. This is a collection-process assumption to investigate, not something proved by the blank pattern alone.

3. Unrecorded high values are more likely to be missing even after conditioning on observed fields. What concern arises?

Answer: This is an MNAR scenario. Observed medians may underestimate missing values; investigate collection procedures and test sensitivity to plausible alternatives rather than assuming ordinary imputation recovers them.

4. Why add an indicator alongside median imputation?

Answer: It lets the model distinguish a measured median from a substituted one. Evaluate whether that distinction is useful and stable, since it may encode a collection artifact that changes after deployment.

Knowledge check: five explained MCQs

1. MCAR requires missingness to be independent of: A. Observed and unobserved analysis values. B. Observed analysis values alone. C. Unobserved analysis values alone.

Correct: A. It is stronger than simply failing to explain the missing values.

2. MAR means: A. Every row has equal missingness probability. B. Conditional on observed information, missingness does not further depend on missing values. C. Missing values are zero.

Correct: B. The conditioning information is central to the definition.

3. Fit imputation during cross-validation: A. Once before all folds. B. On test data. C. Within each fold’s training partition.

Correct: C. The validation fold must not influence learned preprocessing.

4. Median imputation reconstructs the true missing value: A. No. B. Always. C. Yes, when the median is learned without leakage.

Correct: A. It supplies a practical substitute and can distort variance and relationships.

5. Unknown targets should automatically become the majority label: A. Yes. B. No. C. Only for evaluation.

Correct: B. That invents outcomes and can create misleading performance estimates.

Common pitfalls

Do not convert missingness to a real zero unintentionally, infer a mechanism solely from observed correlations, or fit imputation across evaluation boundaries. Inspect all-missing columns, new production missingness, and missing labels. More elaborate imputation does not automatically reduce bias or improve prediction.

Summary

Missing values reflect how information was collected. Diagnose that process, compare simple and justified alternatives, preserve useful missingness information, and fit every learned imputer inside training partitions. Predictive validation and sensitivity analysis answer different parts of the missing-data problem.

Primary sources and further reading