Core ML Fundamentals: Generalization, Imbalance, and Missingness
Machine LearningModel answerLast updated
A foundational machine learning assessment covering model capacity trade-offs, handling heavily skewed class distributions, and processing incomplete data features.
In a machine learning technical round, candidates are evaluated on their ability to reason through core concepts, diagnose practical failure modes, and apply targeted remedies.
Answer the following three modules clearly and concisely:
Module 1: Generalization, Capacity, and Bias-Variance
- Formally define overfitting and underfitting using performance metrics on train vs. validation splits.
- Explain how to diagnose which issue is present using training history and validation curves.
- State the bias-variance decomposition of expected prediction error, detailing how model complexity, regularization, and dataset size affect both terms.
- List concrete remedies for both overfitting and underfitting, noting the operational trade-offs of each action.
Module 2: Skewed Label Distributions (Class Imbalance)
- Explain why standard evaluation metrics (like raw accuracy) become deceptive when one class is extremely rare (e.g., 0.1% positive).
- Detail appropriate evaluation strategies and metrics (e.g., PR-AUC, ROC-AUC, F-beta) based on task goals (ranking vs. probability estimation vs. hard decisions).
- Compare techniques for handling imbalance during modeling (class weighting, resampling methods like SMOTE or undersampling) and explain their impact on model probability calibration.
- Describe how cross-validation splitting strategies should be configured to prevent optimistic bias.
Module 3: Incomplete Feature Sets (Missing Data)
- Define the primary mechanisms of missingness: Missing Completely at Random (MCAR), Missing at Random (MAR), and Missing Not at Random (MNAR).
- Outline practical strategies for handling missing attributes (deletion, baseline imputation, model-based imputation, indicator variables, and native tree-based handling).
- Explain how to implement imputation pipelines correctly to prevent data leakage between training and inference environments.
Hints
Hint 1
Focus on how train and validation loss curves diverge over time or complexity.
Hint 2
Consider how metric choices differ when business costs for false positives and false negatives are asymmetric.
Hint 3
Ensure feature imputation parameters are fit strictly on the training partition and transformed on test/inference sets.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Module 1: Generalization, Capacity, and Bias-Variance
1. Definitions
- Underfitting: Occurs when a model lacks sufficient capacity or training time to capture the underlying structure of the data. Both training error and validation error remain high.
- Overfitting: Occurs when a model learns training data noise, artifacts, or sample-specific patterns that fail to generalize. Training error drops to low levels while validation error increases or plateaus significantly higher than training error.
2. Diagnosis
- Learning Curves: Plot train loss and validation loss as a function of training steps (or dataset size).
- Underfitting is indicated when train and validation curves converge early at an unacceptably high error rate.
- Overfitting is indicated when the training loss steadily declines while the validation loss begins to rise, widening the generalization gap.
- Validation Curves: Plot performance against hyperparameter complexity (e.g., tree depth, polynomial degree). Underfitting appears on the low-complexity side; overfitting appears on the high-complexity side.
3. Bias-Variance Decomposition
For a target $y = f(x) + \epsilon$ with noise variance $\sigma^2$, the expected squared prediction error at a point $x$ decomposes as:
$$\mathbb{E}\left[(y - \hat{f}(x))^2\right] = \text{Bias}[\hat{f}(x)]^2 + \text{Var}[\hat{f}(x)] + \sigma^2$$
- Bias: Systematic error introduced by approximating a real-world problem with a simplified model. High bias leads to underfitting.
- Variance: Sensitivity of the model to minor fluctuations in the training set. High variance leads to overfitting.
- Irreducible Error ($\sigma^2$): Inherent noise in the problem domain that cannot be removed by any model.
| Factor | Effect on Bias | Effect on Variance |
|---|---|---|
| Increasing Capacity (e.g., deeper trees, more parameters) | Decreases | Increases |
| Adding Regularization (e.g., $L_1/L_2$, dropout, pruning) | Increases | Decreases |
| Increasing Dataset Size ($N$) | Constant / Minimal change | Decreases |
4. Remedies and Trade-offs
-
Remedies for Underfitting:
- Increase model capacity: Use deeper models or complex architectures. Trade-off: Higher compute demands and risk of swinging into overfitting.
- Feature engineering: Add domain-specific signals or non-linear interaction terms. Trade-off: Requires domain expertise and increases pipeline maintenance overhead.
- Reduce regularization: Lower penalty coefficients. Trade-off: Moves model closer to high-variance regime.
-
Remedies for Overfitting:
- Regularization: Apply $L_1$ (Lasso), $L_2$ (Ridge), or structural constraints like max depth. Trade-off: Slightly increases bias.
- Early stopping: Terminate training when validation metrics degrade. Trade-off: Requires a dedicated validation split and tuning patience parameters.
- Data augmentation / Collect more data: Expand training volume. Trade-off: Higher collection, storage, and processing costs.
- Ensembling: Bagging reduces variance without increasing bias. Trade-off: Increases inference latency and memory requirements.
Module 2: Skewed Label Distributions (Class Imbalance)
1. Why Accuracy Fails
In a dataset where $0.1%$ of instances are positive (e.g., fraud detection), a trivial classifier that predicts the majority class for every instance achieves $99.9%$ accuracy. However, the model provides zero predictive utility for detecting the target event.
2. Evaluation Metrics & Selection Criteria
Metric choice depends on the model's operational role:
- Probability Calibration & Scoring: Log-loss / Binary Cross-Entropy measures score fidelity across the spectrum.
- Ranking Tasks:
- ROC-AUC: Evaluates global ranking performance across all operational points. Note: Can present an overly optimistic view when negative instances vastly outnumber positive instances because False Positive Rate grows slowly.
- PR-AUC (Precision-Recall AUC): Focuses heavily on the positive minority class, making it superior for extreme imbalance settings.
- Hard Decision Output:
- $F_\beta$-Score: Combines Precision and Recall via a weighted harmonic mean: $$F_\beta = (1 + \beta^2) \frac{\text{Precision} \cdot \text{Recall}}{(\beta^2 \cdot \text{Precision}) + \text{Recall}}$$ Set $\beta > 1$ to prioritize recall (e.g., disease detection) or $\beta < 1$ to prioritize precision (e.g., spam filtering).
3. Modeling Techniques & Calibration Impacts
- Class Weighting: Scales the loss function so errors on minority samples incur a higher penalty inversely proportional to their class frequency.
- Impact: Retains all data; shifts the internal optimization objective without discarding information.
- Random Undersampling: Drops instances from the majority class.
- Impact: Dramatically reduces training time, but discards potentially useful information.
- Oversampling / Synthetic Generation (SMOTE): Duplicates minority samples or interpolates synthetic examples.
- Impact: Increases training duration and risks over-parameterizing noise if synthetic samples are generated near ambiguous boundaries.
- Probability Calibration Considerations:
- Resampling alters the base rate of the training sample. Post-processing (such as Platt Scaling or Isotonic Regression fit on a calibrated validation set) or mathematical adjustment of predictions via Bayes' rule is required to restore true posterior probability estimation: $$P(y=1|x) = \frac{P_s(y=1|x) \cdot \frac{P(y=1)}{P_s(y=1)}}{P_s(y=1|x) \cdot \frac{P(y=1)}{P_s(y=1)} + (1 - P_s(y=1|x)) \cdot \frac{P(y=0)}{P_s(y=0)}}$$ where $P_s$ is the probability under the sampled distribution.
4. Validation Strategy
Use Stratified $K$-Fold Cross-Validation to ensure every fold retains the exact proportion of minority-to-majority samples as the full dataset. Never apply resampling techniques (like SMOTE) to the entire dataset prior to splitting; resampling must occur strictly within each training fold to prevent data leakage into the validation folds.
Module 3: Incomplete Feature Sets (Missing Data)
1. Missingness Mechanisms
- Missing Completely at Random (MCAR): Missingness probability is unrelated to any observed or unobserved data (e.g., a sensor battery randomly dying). Deletion does not introduce systematic bias.
- Missing at Random (MAR): Missingness probability depends on observed feature values, but not on the missing value itself (e.g., older patients in a medical survey being less likely to record income). Imputation using observed features removes bias.
- Missing Not at Random (MNAR): Missingness probability depends directly on the unobserved missing value itself (e.g., high-income individuals deliberately skipping an income question). Imputation requires explicit modeling of the missingness process or indicator flags.
2. Strategies for Handling Missing Values
| Strategy | Description | Pros | Cons / Side Effects |
|---|---|---|---|
| Row Deletion | Drop samples with missing values. | Simple; unbiased under MCAR. | Reduces sample size; introduces heavy bias under MAR/MNAR. |
| Mean / Median / Mode Imputation | Replace missing values with statistical aggregates. | Fast, simple, easy to deploy. | Reduces feature variance, distorts correlations with other features. |
| Model-Based Imputation | Predict missing values using KNN or iterative regression (MICE). | Preserves complex pairwise interactions. | Computationally expensive; can introduce secondary noise into predictions. |
| Missingness Indicator Flag | Add a binary indicator column ($1$ if missing, $0$ otherwise). | Captures non-random signals (MNAR). | Doubles feature count for sparse matrices. |
| Native Tree Support | Algorithm handles missing values directly (e.g., XGBoost, LightGBM). | Retains maximum data, learns optimal split directions for missing entries. | Specific to gradient boosted trees/tree ensembles; unavailable for linear models. |
3. Preventing Data Leakage
Imputation parameters (e.g., feature means, medians, or trained MICE models) must be computed only on the training split.
- Train Pipeline: Fit the imputer on
X_train, transformX_train. - Validation / Production Pipeline: Transform
X_testor real-time inference payloads using the already fitted parameters fromX_train. Never fit imputers on the full dataset or re-calculate missingness metrics dynamically on test splits.