1. Handling Missing Data
Understanding Missingness Mechanisms and Basic Imputation
In real-world machine learning tasks, data is rarely pristine. Before applying any learning algorithms, you must address missing values. Understanding *why* data is missing dictates the appropriate correction strategy. Statisticians classify missingness into three distinct patterns: Missing Completely at Random (MCAR), Missing at Random (MAR), and Missing Not at Random (MNAR).
MCAR occurs when the probability of an instance being missing is completely independent of both observed and unobserved data. An example of this is a lab tube breaking or a network package dropping randomly. MAR occurs when the missingness systematically depends on another observed variable, but not on the missing value itself (for instance, older study participants being less likely to share their phone numbers, which we can infer from their reported age). MNAR represents cases where the missingness directly depends on the value of the missing variable itself, such as high-income individuals refusing to disclose their wealth.
Univariate imputation represents the simplest way to treat missing data by replacing missing values using single-column statistics. Common univariate options include:
| Method | Best Application Case |
|---|---|
| Mean Imputation | Best suited for symmetric, normally distributed numeric data with no extreme outliers. |
| Median Imputation | Highly recommended for skewed numeric variables because it is robust to outliers. |
| Mode Imputation | Primarily used to fill missing values in categorical or discrete features. |
| Constant Imputation | Used when missingness should be explicitly treated as its own class (e.g., Missing). |
import pandas as pd import numpy as np # Create a mock dataset with missing values df = pd.DataFrame({ 'Age': [23, np.nan, 29, 41, 35, np.nan], 'Income': [50000, 60000, np.nan, 80000, 55000, 120000], 'Category': ['A', 'B', 'A', np.nan, 'B', 'B'] }) # 1. Mean Imputation df['Age_Mean'] = df['Age'].fillna(df['Age'].mean()) # 2. Median Imputation df['Income_Median'] = df['Income'].fillna(df['Income'].median()) # 3. Mode Imputation df['Category_Mode'] = df['Category'].fillna(df['Category'].mode()[0]) print("Original and Imputed DataFrame:") print(df)
Using SimpleImputer and KNNImputer from Scikit-Learn
While Pandas provides convenient methods like fillna(), scikit-learn standardizes the imputation process inside production pipelines using dedicated classes. This is highly beneficial when building complex pipelines that transform unseen data automatically.
The SimpleImputer class provides a highly configurable interface for univariate imputation. By using the strategy parameter, you can specify mean, median, most_frequent, or constant to replace missing indicators.
For complex relationships, univariate methods are often too simplistic. KNNImputer is a multivariate imputor that estimates missing values by finding similar rows (neighbors) based on non-missing features. It uses a modified Euclidean distance metric (nan-euclidean distance) to locate the k-nearest neighbors and averages their values to impute the target cell. This helps preserve multidimensional structures in your datasets.
import numpy as np from sklearn.impute import SimpleImputer, KNNImputer # Construct standard feature matrix X = np.array([ [1.0, 2.0, np.nan], [2.0, np.nan, 3.0], [np.nan, 6.0, 5.0], [8.0, 8.0, 9.0] ]) # Univariate Median Imputation simple_imp = SimpleImputer(strategy='median') X_simple = simple_imp.fit_transform(X) # Multivariate KNN Imputation (k=2 neighbors) knn_imp = KNNImputer(n_neighbors=2) X_knn = knn_imp.fit_transform(X) print("Original Array:") print(X) print("\nSimpleImputer (Median):") print(X_simple) print("\nKNNImputer (k=2):") print(X_knn)
Tracking Missingness Indicators as Distinct Features
Imputing values allows algorithms to process datasets without failing, but it carries a hidden risk: it erases the structural information of why the value was missing in the first place. If missingness is correlated with our target variable, this erasure directly damages predictive accuracy.
To preserve this valuable signal, you should create a binary indicator column for every imputed variable. These flag columns take the value of 1 if the original value was missing, and 0 otherwise. This allows downstream models (especially tree-based algorithms) to easily learn separate behaviors for imputed values.
Scikit-learn automates this process cleanly with the 'add_indicator=True' argument inside SimpleImputer or by explicitly chaining the MissingIndicator utility class.
import numpy as np from sklearn.impute import SimpleImputer # Sample dataset with missing fields X = np.array([ [10.0, np.nan], [20.0, 50.0], [np.nan, 60.0], [40.0, 70.0] ]) # Configure Imputer to track missing flags automatically imputer = SimpleImputer(strategy='mean', add_indicator=True) X_imputed = imputer.fit_transform(X) print("Transformed Array layout: [Feature_1_Imputed, Feature_2_Imputed, Indicator_1, Indicator_2]") print(X_imputed)
Knowledge Check
Ready to test your understanding of 1. Handling Missing Data?