Classifying Imbalanced Clinical Outcomes Under Heavy Missing Data
Machine LearningModel answerLast updated
Architect an end-to-end binary classification pipeline for readmissions with missing data, extreme class imbalance, metrics choice, and feature-engineered logistic regression.
You are tasked with designing a production-grade binary classifier to predict 30-day hospital readmissions using combined electronic health records (EHR) and insurance claims data.
The dataset presents two primary technical challenges:
- Missing Data: Approximately 30% of total values are missing across the feature space, with non-uniform distribution across rows and columns.
- Class Imbalance: Only 6% of historical admissions result in a 30-day readmission (positive class rate = 0.06).
Provide a structured engineering and modeling strategy covering the following four areas:
-
Missingness Architecture & Validation:
- How to diagnose the underlying missingness mechanisms: Missing Completely at Random (MCAR), Missing at Random (MAR), and Missing Not at Random (MNAR).
- Rules for deciding whether to drop versus impute specific rows or columns.
- Design of at least two concrete imputation strategies (e.g., deterministic/simple, model-based, or indicator-augmented).
- How to validate missingness handling inside a cross-validation framework to prevent data leakage.
-
Metrics & Threshold Optimization:
- Define key performance metrics: Accuracy, Precision, Recall, Specificity, F1-score, ROC-AUC, PR-AUC, and Probability Calibration.
- Provide two distinct clinical use cases: one where Recall is prioritized and one where Precision is prioritized, justifying the tradeoff in each context.
- Explain how threshold selection, business/clinical cost matrices, or utility curves dictate operational decision boundaries.
-
Imbalance Handling & Evaluation Protocols:
- Detail at least three distinct strategies for addressing the 6% positive rate (e.g., cost-sensitive weighting, resampling schemes, threshold-moving, or specialized loss functions).
- Detail the exact evaluation setup (e.g., stratified and grouped cross-validation, temporal split) required to eliminate leakage and optimistic metric inflation.
-
Enhancing Generalized Linear Models (Logistic Regression):
- Outline specific feature engineering, regularization, non-linear transformations (such as splines), interaction detection, and calibration post-processing (e.g., Platt scaling or Isotonic regression) to optimize a logistic regression model.
- Describe a systematic ablation protocol to quantify performance lift against a baseline model.
Hints
Hint 1
Ensure data splitting accounts for multi-visit patients to prevent identity leakage across folds.
Hint 2
Pay close attention to how re-sampling or probability-shifting methods alter final probability calibration.
Hint 3
Evaluate metric selection specifically under low-prevalence regimes (6% positive rate).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Leakage Guardrails & Preprocessing Pipeline Structure
Before diagnosing missingness or fitting models, the data splitting and pipeline infrastructure must be strictly defined to avoid leakage.
+-------------------------------------------------------------------------------+
| Full Historical Dataset |
+-------------------------------------------------------------------------------+
|
Temporal Split (e.g., Hold out final 6 months)
|
+---------------------------------+---------------------------------+
| |
+----v----------------------------------+ +------------------v------------------+
| Development / Training Dataset | | Temporal Out-of-Time Test Set |
+---------------------------------------+ +-------------------------------------+
| |
GroupKFold (Grouped by Patient ID) |
| |
v v
+------------------+ +------------------+ Unseen Data: Only transform
| Train Fold | --> | Validation Fold | using fitted parameters from
+------------------+ +------------------+ the best-performing pipeline.
1. Fit Imputer 1. Apply Imputer
2. Fit Scaler 2. Apply Scaler
3. Resample Train Only 3. Score Unsampled Val
- Temporal Cutoff & Claims Lag: All feature extractions must strictly use data timestamped prior to or at the exact moment of discharge ($t_0$). Information arriving post-discharge (such as adjudicated claims or late discharge summaries) must be purged. To simulate true deployment, add an artificial lag parameter matching the median delay in claims processing.
- Grouping Strategy: A single patient may account for multiple admissions. To prevent patient-identity leakage between folds, use Patient-Level Grouping combined with Stratification (
StratifiedGroupKFold) so that all records from a given patient reside exclusively within either the training or validation split. - Holdout Evaluation: Retain the final 3–6 months of chronological data as a strict out-of-time (OOT) test set to assess robustness against clinical drift.
- Leakage-Free Execution Pipeline: All transformations—imputation, scaling, feature engineering, synthetic resampling, and probability calibration—must be contained within an ensemble or sequence pipeline (e.g.,
imblearn.pipeline.Pipeline). Fit steps occur solely on the training fold; validation and test splits are strictly transformed using the parameters estimated from training.
2. Missing Data Diagnosis and Imputation Strategy
Diagnosing Missingness Mechanisms
- Exploratory Profiling:
- Measure missingness rates per column and per row. Compute a missingness correlation matrix to identify co-missing patterns (e.g., if blood gas labs are missing together).
- Evaluate structural missingness (e.g., claims-only records missing EHR clinical vitals due to data source differences).
- Statistical and Empirical Tests:
- MCAR Check: Apply Little’s MCAR test or fit an auxiliary classifier trained to predict feature missingness indicators ($M_j = 1$) from other observed features ($X_{obs}$). An auxiliary model AUC near 0.5 indicates MCAR.
- MAR Check: If the auxiliary model achieves high prediction performance (AUC > 0.70), missingness depends on observed features, indicating MAR.
- MNAR Check: MNAR cannot be fully verified from observed data alone. Validate MNAR via domain experts (e.g., troponin levels are selectively ordered when cardiac symptoms are present) and by checking if the missingness indicator $M_j$ significantly correlates with the 30-day readmission label $Y$ conditional on $X_{obs}$.
Dropping vs. Imputing Guidelines
- Drop Columns: Exclude columns if missingness exceeds 70–80%, unless the presence of the test itself carries strong predictive signal or the feature is clinically mandatory.
- Drop Rows: Never drop rows based on feature missingness in MAR/MNAR scenarios, as this skews the underlying patient population (e.g., selectively dropping lower-acuity clinic patients). Only drop rows if the target label $Y$ is missing or if $>95%$ of all patient attributes are unobserved.
- Impute: Apply imputation to all remaining features.
Imputation Strategies
- Simple Median/Mode + Missing Indicator Augmentation:
- Replace missing values in numeric fields with the training fold median, and categorical fields with a separate
"MISSING"category. - Append binary indicators ($M_{i,j} \in {0, 1}$) for columns with $>5%$ missing values. This allows linear models and trees to explicitly learn the diagnostic signal associated with missingness (handling MNAR patterns).
- Replace missing values in numeric fields with the training fold median, and categorical fields with a separate
- Model-Based Multivariate Imputation (MICE / KNN):
- Use Chained Equations (e.g.,
IterativeImputerwith Bayesian Ridge or Random Forest estimators) or $K$-Nearest Neighbors on scaled data to estimate missing values conditional on all observed predictors. Include missingness indicators alongside MICE outputs.
- Use Chained Equations (e.g.,
- Domain-Specific Structural Fills:
- Distinguish missing clinical data from structural zeroes (e.g., missing count of prior admissions implies
0, not unknown).
- Distinguish missing clinical data from structural zeroes (e.g., missing count of prior admissions implies
Validation of Imputation Choice
- Validate imputation configurations based on downstream task performance (PR-AUC, Brier score) within the
StratifiedGroupKFoldcross-validation loop. - Perform mask-and-recover experiments (randomly blanking 10% of known values to evaluate Mean Squared Error of recovery) as a secondary diagnostic, while prioritizing target predictive performance as the ground-truth selector.
3. Metric Selection and Decision Thresholding
Metric Definitions & Tradeoffs (at 6% Positive Base Rate)
| Metric | Formula / Description | Utility in Imbalanced Readmission Context |
|---|---|---|
| Accuracy | $\frac{TP + TN}{TP + TN + FP + FN}$ | Misleading. A naive model predicting all zeros yields 94% accuracy while catching 0 readmissions. |
| Precision (PPV) | $\frac{TP}{TP + FP}$ | Fraction of flagged high-risk patients who are actually readmitted. Crucial when interventions are limited or high-cost. |
| Recall (Sensitivity) | $\frac{TP}{TP + FN}$ | Fraction of true readmissions correctly flagged. Crucial when missing a readmission carries high penalties. |
| Specificity | $\frac{TN}{TN + FP}$ | Fraction of stable patients correctly identified as low-risk. |
| F1-Score | $2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}$ | Harmonic mean of Precision and Recall. Assumes equal weight between Precision and Recall. |
| ROC-AUC | Area under $TPR$ vs $FPR$ curve | Measures ranking quality across all thresholds. Insensitive to prevalence, making it overly optimistic for rare classes. |
| PR-AUC | Area under Precision vs Recall curve | Evaluates model capability specifically on the minority class. The baseline baseline random performance equals the 0.06 prevalence. |
| Calibration | Reliability curve, Brier Score ($BS = \frac{1}{N}\sum (\hat{p}_i - y_i)^2$) | Measures whether predicted probability $\hat{p} = 0.20$ reflects an actual 20% readmission rate. Critical for cost-benefit thresholding. |
Prioritization Scenarios
- Recall-Prioritized Use Case (Automated Low-Cost Outreach):
- Scenario: Post-discharge automated text reminders, phone follow-ups, or mailers.
- Justification: Interventions carry negligible cost per patient ($1–$5) and zero risk of harm. The cost of a false negative (unplanned readmission causing patient harm and financial penalties) far outweighs the cost of a false positive. High recall ensures the vast majority of at-risk patients receive guidance.
- Precision-Prioritized Use Case (Resource-Constrained Intensive Care):
- Scenario: Enrolling patients in an intensive transitional home-nurse visit program with a hard cap of 50 capacity slots per month.
- Justification: Nurse home visits are expensive ($500 per visit) and capacity-constrained. False positives waste finite clinical resources and displace actual high-risk patients. The operational metric must be Precision@K (e.g., Precision at $K=50$).
Operational Thresholding & Decision Theory
Given calibrated output probabilities $\hat{p} = P(Y=1|X)$, the decision threshold $t^*$ can be determined mathematically using a cost matrix:
$$t^* = \frac{C_{FP} - C_{TN}}{(C_{FP} - C_{TN}) + (C_{FN} - C_{TP})}$$
Assuming correct classification yields zero incremental cost ($C_{TN} = 0, C_{TP} = 0$), the formula simplifies to:
$$t^* = \frac{C_{FP}}{C_{FP} + C_{FN}}$$
- If a false negative costs $$10,000$ (hospital penalty + bed loss) and a false positive intervention costs $$500$, the optimal operational threshold is $t^* = \frac{500}{500 + 10000} \approx 0.0476$.
- Any patient with predicted probability $\hat{p} \ge 4.76%$ should receive intervention. Threshold selection should be determined via validation-fold utility optimization, never on the holdout test set.
4. Class Imbalance Strategies
- Cost-Sensitive Weighting:
- Adjust the loss function by scaling positive samples by $w_1 = \frac{1 - \pi}{\pi} \approx \frac{0.94}{0.06} \approx 15.67$.
- Trade-off: Directly optimizes the decision boundary without discarding data or generating synthetic artifacts. However, it shifts output raw scores away from true posterior probabilities, requiring post-hoc probability recalibration.
- Resampling Techniques (SMOTE-NC / Random Undersampling):
- Apply SMOTE-NC (Synthetic Minority Over-sampling Technique for Nominal and Continuous features) strictly on training folds to synthesize positive cases, or perform random undersampling of the majority class to reach a balanced ratio (e.g., 1:4).
- Trade-off: Undersampling drastically speeds up computation but discards data. SMOTE can generate uncalibrated probabilities and synthetic samples in empty feature space. Resampling must strictly occur inside cross-validation steps.
- Threshold-Moving Post Unweighted Training:
- Fit the classifier on the original 6% unweighted dataset using proper scoring rules (Log Loss) to preserve true risk probability calibration.
- Afterwards, shift the classification decision threshold $t$ based on the Precision-Recall curve or clinical cost matrix.
- Trade-off: Best practice for maintaining probability calibration, but standard gradient solvers may require more epochs or continuous loss adjustments to converge on sparse positive signals.
5. Advanced Feature Engineering & Optimization for Logistic Regression
To maximize performance from a generalized linear model (Logistic Regression), incorporate explicit non-linear terms, feature interactions, and post-processing calibration:
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import StandardScaler, SplineTransformer, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import CalibratedClassifierCV
from sklearn.pipeline import Pipeline
from imblearn.pipeline import Pipeline as ImbPipeline
from imblearn.over_sampling import SMOTENC
# 1. Custom Non-Linear & Interaction Transformer
class ClinicalFeatureEngineer(BaseEstimator, TransformerMixin):
def __init__(self):
pass
def fit(self, X, y=None):
return self
def transform(self, X):
X_out = X.copy()
# Interaction terms: Age x Prior Admissions
if 'age' in X_out.columns and 'prior_admissions' in X_out.columns:
X_out['age_x_admissions'] = X_out['age'] * X_out['prior_admissions']
# Interaction terms: Comorbidity Count x Length of Stay
if 'charlson_index' in X_out.columns and 'length_of_stay' in X_out.columns:
X_out['charlson_x_los'] = X_out['charlson_index'] * X_out['length_of_stay']
return X_out
# 2. Pipeline Construction
numeric_features = ['age', 'prior_admissions', 'length_of_stay', 'charlson_index']
categorical_features = ['primary_diagnosis_grp', 'discharge_disposition']
numeric_transformer = Pipeline(steps=[
('spline', SplineTransformer(n_knots=4, degree=3, include_bias=False)),
('scaler', StandardScaler())
])
categorical_transformer = OneHotEncoder(handle_unknown='ignore', sparse_output=False)
preprocessor = ColumnTransformer(
transformers=[
('num', numeric_transformer, numeric_features),
('cat', categorical_transformer, categorical_features)
]
)
# Combine into an end-to-end model pipeline with ElasticNet regularization
base_model = LogisticRegression(
penalty='elasticnet',
solver='saga',
l1_ratio=0.5, # Mixed L1/L2 regularization
max_iter=2000,
class_weight='balanced',
random_state=42
)
full_pipeline = Pipeline(steps=[
('feature_engineering', ClinicalFeatureEngineer()),
('preprocessor', preprocessor),
('model', base_model)
])
# 3. Probability Calibration Post-Processing Wrapper
# Fits Platt Scaling (sigmoid) on out-of-fold predictions to output reliable probabilities
calibrated_pipeline = CalibratedClassifierCV(
estimator=full_pipeline,
method='sigmoid', # Platt Scaling (use 'isotonic' for >10k samples)
cv=5
)
Systematic Ablation Protocol
To measure the marginal gain of each enhancement, conduct an ablation study using identical StratifiedGroupKFold splits:
- Baseline Model: Vanilla Logistic Regression (L2 penalty) on raw imputed numerical/categorical features.
- Ablation Step 1 (Regularization): Evaluate ElasticNet ($L_1 + L_2$ tuning over grid $l1_ratio \in [0.1, 0.5, 0.9]$) to automatically zero out collinear/redundant features.
- Ablation Step 2 (Non-linearity): Add Natural Cubic Splines (
SplineTransformer) to continuous predictors (e.g., age, lab values) to capture non-monotonic risk curves. - Ablation Step 3 (Interactions): Add domain-specific clinical interaction terms.
- Ablation Step 4 (Calibration): Apply Platt Scaling / Isotonic Regression post-processing. Compare Brier Score and Expected Calibration Error (ECE) against pre-calibrated output.
Reporting Ablation Results to Stakeholders
| Iteration / Experiment Step | PR-AUC (CV Mean ± SD) | ROC-AUC | Brier Score | Rec@Prec=0.30 |
|---|---|---|---|---|
| 0. Baseline Logistic Reg | $0.18 \pm 0.02$ | 0.71 | 0.058 | 22% |
| 1. + ElasticNet Tuning | $0.21 \pm 0.02$ | 0.73 | 0.055 | 28% |
| 2. + Splines & Interactions | $0.26 \pm 0.01$ | 0.77 | 0.051 | 37% |
| 3. + Platt Recalibration | $0.26 \pm 0.01$ | 0.77 | 0.044 | 38% |
| 4. Benchmark: LightGBM | $0.29 \pm 0.01$ | 0.80 | 0.045 | 44% |
Presenting the ablation table alongside clinical utility curves demonstrates to non-technical leaders the exact incremental impact of each modeling decision, contrasting interpretable GLM enhancements directly against non-linear tree models.