Model Fit Diagnostics, Skewed Classes, and Missing Features

Easy · Machine Learning · Machine Learning Engineer · Technical Screen

Prompt

In a core machine learning technical screen spanning linear models, decision-tree ensembles, and neural networks across both regression and classification tasks, walk through three foundational diagnostic scenarios as you would aloud with an interviewer—stating exact definitions, empirical detection signals, and practical interventions alongside their trade-offs:

  1. Model fit & error decomposition: Contrast underfitting and overfitting through training and held-out error patterns, explain how capacity sweeps and sample-size plots distinguish them, weigh concrete fixes for each regime, and connect both failure modes to the mathematical decomposition of expected squared test error across capacity, penalty strength, and dataset size.
  2. Skewed label prevalence: After clarifying rare-class frequency, absolute positive count, asymmetric mistake costs, and how downstream consumers use predictions (rankings, binary triggers, or probabilities), explain what breaks under standard training and accuracy scoring, compare data-level resampling, loss reweighting, and cost-optimal thresholding (including effects on probability calibration), and describe leak-free validation splits.
  3. Incomplete feature matrices: After checking whether live production traffic drops fields through the same mechanism as historical logs, classify why entries go blank (MCAR, MAR, MNAR), compare deletion, statistical or model-based fill strategies, explicit missingness flags, and native tree routing, and detail how to prevent fold leakage, avoid train-serve mismatches, and verify empirical lift.

Scope & Expectations

  • Precise diagnostics before remedies: Anchor fit diagnoses against an irreducible noise baseline using validation and learning curves, and verify missingness mechanisms and live-vs-offline parity before choosing transformations.
  • Bias-variance & capacity mechanics: State how expected squared prediction error splits into noise, squared bias, and variance, and trace how model flexibility, regularization penalties, and additional training data move each term.
  • Prevalence-aware evaluation & calibration: Replace misleading accuracy with ranking or cost-aligned metrics, keep validation folds untouched at natural prevalence, and account for how resampling or class weights shift predicted odds.
  • Leak-free missingness pipelines: Match imputation, indicator flags, or native split handling to MCAR/MAR/MNAR assumptions while fitting all fill statistics strictly inside training folds and mirroring exact behavior at serving time.

Step-by-step walkthrough

  1. Define underfitting and overfitting through error gaps

    In an interview, start by setting scope in two quick sentences: these principles apply across linear models, tree ensembles, and neural networks; the exact bias-variance split uses regression with squared error, while class imbalance applies to classification.

    We diagnose a supervised model by comparing its error on the training set (data the model learned from) against a validation set (held-out data the model has never seen), anchored against a reference floor—the best achievable error given label noise (often called Bayes error, estimated from human agreement or a strong domain baseline):

    • Underfitting: The model is too rigid or constrained to capture the real signal. Training error is high (well above the noise floor) and validation error is similarly high—a small gap, both bad.
    • Overfitting: The model memorizes random noise and quirks specific to its training sample. Training error is very low (often below the true noise floor!), while validation error is much higher—a large train-to-validation gap.

    Without a reference floor, raw numbers can fool you: 15% train error and 16% validation error is severe underfitting on clean digits, yet near-optimal if 15% of human labels are genuinely ambiguous.

    Here is a concrete numeric example: fitting polynomials of degree 1, 3, and 9 to 20 noisy points from y = sin(2 * pi * x) + noise, where the random noise has standard deviation 0.3 (so the irreducible noise floor for mean squared error, MSE, is 0.3^2 = 0.09):

    Model capacity      Train MSE   Validation MSE*   Gap     Diagnosis (vs 0.09 noise floor)
    ------------------------------------------------------------------------------------------
    Degree 1 (line)       0.314         0.330        0.016    Both far above 0.09 -> Underfitting
    Degree 3 (cubic)      0.078         0.114        0.036    Near floor, modest gap -> Good fit
    Degree 9 (wiggly)     0.045         0.136        0.091    Train BELOW 0.09 floor -> Overfitting
    
    *Averaged across 2,000 simulated training draws of n = 20 points, scored on fresh noisy labels.
    
  2. Diagnose with validation curves and learning curves

    Two diagnostic plots tell you not just what is wrong, but whether adding capacity or adding data will fix it. Compute them on a held-out validation split—or k-fold cross-validation (splitting data into k equal slices, training on k - 1 slices and validating on the remaining slice k times) when data is scarce:

    1. Validation Curve (fix data size n, sweep capacity)    2. Learning Curves (fix capacity, grow data size n)
    
    Error ^          \        / Val error (U-shaped)         Error ^  Val --------=======   (Underfitting:
          |           \      /                                     |  Train ------=======    converge high -> add capacity)
          |  Underfit  \____/  Overfit                             +----------------------> n
          |             ^  \                                 Error ^  Val  \
          |          Sweet  \___ Train error                       |        \____--------   (Overfitting: big gap
          |          spot                                          |  Train /----________    shrinks -> add data!)
          +--------------------------> Capacity                    +----------------------> n
    
    • Validation curve (Error vs. Capacity): Sweep one complexity knob—polynomial degree, tree depth, boosting rounds, or inverse regularization 1 / lambda. Training error drops steadily, while validation error forms a U-shape: left of the valley is underfitting; right of the valley is overfitting.
    • Learning curve (Error vs. Training Size n): Keep model architecture fixed and train on 10%, 25%, 50%, and 100% of training rows:
      • Underfitting plateaus early: In our sine example, increasing n from 20 to 200 leaves the degree-1 line stuck at 0.289 train / 0.291 validation MSE. Collecting more rows will not help a straight line bend into a wave!
      • Overfitting narrows with n: For degree 9, growing n from 20 to 200 shrinks the train-validation gap tenfold, from 0.091 (0.045 vs 0.136) down to 0.009 (0.086 vs 0.094).

    Always match your validation split to production reality: use time-ordered splits when predicting future events, group splits so one user's rows never straddle train and validation, and lock away a untouched test set for one final check so tuning decisions do not overfit the validation split itself.

  3. Choose remedies for underfitting and overfitting (and weigh their costs)

    Every remedy trades away something—bias, compute, latency, money, or interpretability:

    • Fixes for Overfitting (variance is too high):

      • Add training rows (or realistic data augmentation): Lowers variance without adding bias, though labeling costs money and unrealistic augmentations distort the target distribution.
      • Add regularization: Regularization adds a penalty that discourages extreme weights or complex behavior—such as L2 / weight decay (shrinking weights smoothly toward zero), L1 (driving weak weights to exact zero for sparsity), or dropout (randomly zeroing neuron activations during training). Side effects: introduces a small bias, requires feature scaling for L1/L2, and adds a hyperparameter to tune.
      • Reduce model capacity: Prune features, cap max_depth, raise min_samples_leaf, or shrink hidden layers. Push too far and you cause underfitting.
      • Early stopping: Halt iterative training (boosting or gradient descent) when validation loss stops improving. Side effect: validation loss can bounce noisily on small sets.
      • Bagging / ensembling: Bagging averages predictions across models trained on bootstrap resamples (like Random Forests) to cancel out variance, at the cost of higher memory, serving latency, and harder explainability.
    • Fixes for Underfitting (bias is too high):

      • Increase capacity: Deeper trees, more boosting iterations, wider/deeper neural layers, or polynomial interactions. Side effect: raises variance and compute cost.
      • Engineer richer features: Domain ratios, interaction terms, or pretrained embeddings. Side effect: engineering effort and risk of subtle leakage.
      • Relax regularization (lower lambda or dropout rate).
      • Debug optimization first (especially in deep learning): A bad learning rate, vanishing gradients, or too few epochs mimics underfitting on training loss even when model capacity is huge!
    Adjustment Linear models Tree ensembles Neural networks
    Raise capacity (cut bias) Add interactions, splines, polynomials Increase depth, max leaves, or boosting rounds Increase layer width/depth, train longer
    Regularize (cut variance) Raise L1 (Lasso) or L2 (Ridge) penalty Raise min leaf size, subsample rows/columns, shrink learning rate Add weight decay, dropout, data augmentation, early stopping
  4. Unpack the bias-variance trade-off

    Suppose the true relationship is y = f(x) + e, where label noise e has mean 0 and variance sigma^2. Train a model f_hat on a random training set D, and let mu_hat(x) = E_D[f_hat(x)] denote the average model prediction at x across many hypothetical training sets.

    Rewrite the prediction error on a fresh test label y at x by adding and subtracting f(x) and mu_hat(x):

    y - f_hat(x) = [y - f(x)]  +  [f(x) - mu_hat(x)]  +  [mu_hat(x) - f_hat(x)]
                     noise e         average miss             sample jitter
    

    When we square both sides and average over fresh test noise e and random training sets D, every cross-term multiplies a zero-mean independent quantity and averages out to 0, leaving three clean pieces:

    E[(y - f_hat(x))^2] = sigma^2                           <- Irreducible noise (floor no model can beat)
                        + (mu_hat(x) - f(x))^2              <- Bias^2 (how far the average fit sits from truth)
                        + E_D[(f_hat(x) - mu_hat(x))^2]     <- Variance (how wildly fits bounce across datasets)
    

    We can measure all three pieces directly in NumPy and verify the textbook linear-regression rule (variance = sigma^2 * k / n, which for degree 9 with k = 10 coefficients and n = 20 points predicts 0.09 * 10 / 20 = 0.045):

    import numpy as np
    
    NOISE_SD = 0.3
    
    
    def simulate_bias_variance(degree: int, n_train: int, n_repeats: int = 2000) -> tuple[float, float, float, float]:
        """Estimate train MSE, fixed-input test MSE, bias^2, and variance via Monte Carlo."""
        rng = np.random.default_rng(0)
        x = np.linspace(0.0, 1.0, n_train)
        true_f = np.sin(2.0 * np.pi * x)
    
        # Store each trial's fitted curve at x so we can average across training draws
        all_preds = np.empty((n_repeats, n_train))
        train_mses = np.empty(n_repeats)
    
        for trial in range(n_repeats):
            y_noisy = true_f + rng.normal(0.0, NOISE_SD, size=n_train)
            coeffs = np.polyfit(x, y_noisy, degree)
            all_preds[trial] = np.polyval(coeffs, x)
            train_mses[trial] = np.mean((all_preds[trial] - y_noisy) ** 2)
    
        mean_pred = all_preds.mean(axis=0)
        bias_sq = float(np.mean((mean_pred - true_f) ** 2))
        variance = float(np.mean(all_preds.var(axis=0)))
        expected_test_mse = NOISE_SD ** 2 + bias_sq + variance
        return float(train_mses.mean()), expected_test_mse, bias_sq, variance
    
    
    # Degree 1 has high bias^2 (0.231); Degree 9 has near-zero bias^2 (0.000) but ~5x the variance (0.046 vs exact 0.045)
    print("deg 1, n=20:", [round(v, 3) for v in simulate_bias_variance(1, 20)])
    print("deg 9, n=20:", [round(v, 3) for v in simulate_bias_variance(9, 20)])
    

    At fixed data size n, raising capacity pushes bias² down and variance up, while raising regularization pushes bias² up and variance down; adding more data pushes variance down (~ 1 / n) without hurting bias. Note that on brand-new x values between training points, high-degree polynomials swing even more wildly than at the fixed grid inputs above!

  5. Class imbalance: why accuracy lies and which metrics tell the truth

    Suppose only 1% of credit-card transactions are fraudulent (1,000 frauds out of 100,000 transactions). A trivial dummy rule that predicts "never fraud" every single time achieves 99.0% accuracy while catching zero criminals!

    Even when a real model catches 80% of frauds, raw accuracy and the false-positive rate look deceptive:

    100,000 transactions: 1,000 true frauds (1%), 99,000 legitimate (99%)
    Model flags 2,000 transactions -> catches 800 frauds (TP = 800, FP = 1,200, FN = 200, TN = 97,800)
    
    Accuracy            = (800 + 97,800) / 100,000 = 98.6%   <- Looks WORSE than the 99.0% dummy!
    Recall (Sensitivity)= 800 / 1,000              = 80.0%   <- Share of all real frauds caught
    Precision           = 800 / 2,000              = 40.0%   <- Share of flagged alerts that are real fraud
    False Positive Rate = 1,200 / 99,000           =  1.2%   <- Sounds tiny, yet creates 1,200 false alarms!
    F1 Score            = 2 * 0.40 * 0.80 / 1.20   = 0.533   <- Harmonic mean balancing precision and recall
    

    Before picking a metric, clarify how predictions are consumed and how many minority examples exist in absolute count (50 total positives means even validation recall has a huge standard error of sqrt(0.8 * 0.2 / 50) = 5.7%):

    • Yes/no decisions: Track precision, recall, F-beta (which weights recall beta times as heavily as precision), or expected dollar cost at the chosen cutoff.
    • Fixed human review budget k: Track precision at k or recall at a minimum acceptable precision (e.g., recall at 50% precision).
    • Threshold-free ranking: Prefer PR-AUC, whose random-guessing baseline equals the positive rate (0.01 here). ROC-AUC—the probability a random positive ranks above a random negative—is invariant to class ratio, so a 0.98 ROC-AUC can still mask poor precision when negatives outnumber positives 99-to-1.
    • Probability estimates: Track log loss (cross-entropy) and a calibration curve (checking whether events given a 5% score actually happen 5% of the time).
  6. Class imbalance: resampling, class weights, probability correction, and cost thresholds

    A subtle insight that impresses interviewers: a well-specified log-loss model trained on raw imbalanced data already learns calibrated probabilities—the default 0.50 decision cutoff is what fails when true fraud risks sit around 0.01 to 0.15!

    You can intervene at three stages, each with distinct side effects: 1. Data-level resampling: Undersampling drops majority rows (fast for huge datasets, throws away signal); random oversampling duplicates minority rows (risks memorizing exact copies); SMOTE synthesizes points between minority neighbors (can invent implausible combinations in high-dimensional or categorical data). 2. Loss-level weighting: Multiplying minority loss by k (equivalent in expectation to k-fold oversampling without copying rows in RAM) or using focal loss (down-weighting easy negatives). 3. Post-training thresholding (safest default when probabilities matter): Train on the natural distribution, then tune the cutoff for business costs.

    Why resampling distorts probabilities—and the exact algebra to fix it: Define the odds of fraud as p / (1 - p). Duplicating positives k times (or downsampling negatives to 1 / k) multiplies the ratio of positives to negatives everywhere by k:

    odds_model = k * odds_true   =>   p_s / (1 - p_s) = k * (p / (1 - p))
    Solve for true probability p:     p = p_s / (p_s + k * (1 - p_s))
    

    Choosing the threshold from error costs: With a calibrated probability p, leaving a transaction unflagged risks a false negative of expected cost p * C_FN, while flagging it risks a false positive of expected cost (1 - p) * C_FP. Flag whenever not flagging costs more:

    p * C_FN > (1 - p) * C_FP   =>   p * (C_FN + C_FP) > C_FP   =>   threshold t = C_FP / (C_FP + C_FN)
    
    def recalibrate_oversampled_prob(p_resampled: float, oversample_factor: float) -> float:
        """Convert predicted probability p_resampled back to true prevalence after k-x oversampling."""
        return p_resampled / (p_resampled + oversample_factor * (1.0 - p_resampled))
    
    
    def optimal_cost_threshold(cost_fp: float, cost_fn: float) -> float:
        """Return probability cutoff minimizing expected error cost."""
        return cost_fp / (cost_fp + cost_fn)
    
    
    # 10x oversampling: a 0.50 raw score corresponds to only 0.091 true fraud probability!
    print(round(recalibrate_oversampled_prob(0.50, 10.0), 3))  # 0.091
    # Missed fraud costs $200, false-alarm review costs $10 -> optimal cutoff is 0.048, not 0.50!
    print(round(optimal_cost_threshold(10.0, 200.0), 3))       # 0.048
    

    Validation rule: Always use stratified splits (or time splits) so every fold gets positives, resample strictly inside each training fold (oversampling before splitting puts identical duplicate rows in both train and validation, faking high recall!), and score validation/test sets at the true untouched class ratio.

  7. Missing data: match the fix to why values are missing

    Before touching NaNs, diagnose why values are absent—statisticians group missingness into three mechanisms:

    • MCAR (Missing Completely at Random): Whether a cell is blank has nothing to do with any feature or label (e.g., a lab barcode scanner randomly glitches 2% of the time). Dropping incomplete rows wastes sample size but introduces no bias.
    • MAR (Missing at Random): Missingness depends only on other observed columns (e.g., younger users skip an optional income field more often, and age is recorded). Predicting missing values from observed columns removes bias.
    • MNAR (Missing Not at Random): Missingness depends on the unobserved value itself (e.g., ultra-high earners intentionally leave income blank, or sicker patients skip a follow-up test). No imputation formula removes MNAR bias from observed columns alone—preserving a binary is_missing indicator is essential because the blank itself is a strong signal.

    Compare the main engineering remedies and their side effects: - Drop rows / drop column: Dropping rows is biased outside MCAR and impossible at live serving time (you still have to return a prediction when a live user leaves a field blank!). Dropping the entire column makes sense only when it is >80% empty and carries no predictive lift. - Simple imputation (mean / median / mode) + missingness indicator: Imputation means filling blanks with a stand-in value. Filling 30% MCAR blanks (300 of 1,000 rows) with the observed mean sets (x_i - mean)^2 = 0 on all 300 filled rows, shrinking sample variance to 699 / 999 ≈ 70% of truth and weakening a 0.60 correlation with another feature down to 0.60 * sqrt(0.70) ≈ 0.50! Pairing median fill with a 0/1 feature_is_missing column lets linear models and neural nets learn a separate offset for blank rows. - Model-based imputation (k-NN or iterative regression / MICE): Predicts blanks from other columns; more accurate under MAR, but slower and requires shipping the trained imputer inside your live microservice. - Native tree handling: Modern gradient-boosted trees (XGBoost, LightGBM, HistGradientBoosting) learn an optimal default left-or-right branch direction at every split for NaNs automatically—still add explicit is_missing indicators if missingness interacts across multiple features.

  8. Missing data: prevent leakage, align serving, and verify lift

    Three production rules separate textbook answers from real engineering:

    1. Zero leakage across folds: Any fill statistic (median, category mode, iterative regressor) is a learned parameter. Compute it strictly on the training fold, store that exact number, and apply it to validation, test, and live production requests. Computing medians or k-NN neighbors across the full table before splitting leaks validation distributions (and never let the target label y enter an imputer!).
    2. Check training-vs-serving missingness parity: Ask early: "Are features missing for the same reasons online as in historical tables?" Often an offline warehouse table was backfilled overnight (0% missing in training), whereas live checkout requests arrive before the batch job runs (15% missing online)—causing catastrophic training/serving skew. Always log live feature snapshots and train on the exact missingness pattern seen at request time.
    3. Verify lift empirically: Benchmark candidate pipelines (median only, median + indicator, iterative imputer, native GBDT) on identical cross-validation folds using your primary metric, pick the simplest pipeline within noise of the winner, and monitor per-feature NaN rates in production alerting.
    import numpy as np
    
    
    def impute_median_with_indicator(
        x_train: np.ndarray,
        x_eval: np.ndarray,
    ) -> tuple[np.ndarray, np.ndarray]:
        """Fit column medians ONLY on x_train, returning [filled_features, missing_flags] for both splits."""
        # Learn medians strictly from training rows (ignoring NaNs) to prevent leakage
        train_medians = np.nanmedian(x_train, axis=0)
    
        def transform(x: np.ndarray) -> np.ndarray:
            missing_mask = np.isnan(x)
            filled = np.where(missing_mask, train_medians, x)
            # Concatenate 0/1 missing indicators so linear/neural models see informative blanks
            return np.hstack([filled, missing_mask.astype(float)])
    
        return transform(x_train), transform(x_eval)
    
    
    # Mini-trace: x_eval's NaN gets x_train's median (20.0), NOT the combined median!
    tr_raw = np.array([[10.0], [20.0], [30.0], [np.nan]])
    ev_raw = np.array([[100.0], [np.nan]])
    tr_out, ev_out = impute_median_with_indicator(tr_raw, ev_raw)
    print("eval transformed:\n", ev_out)  # [[100.0, 0.0], [20.0, 1.0]]
    

Intuition & how it works

Think of training a supervised machine learning model like preparing a student for a final exam using practice worksheets: - Underfitting vs. overfitting (bias-variance): A student who only reads the chapter titles fails both the practice worksheet and the real exam (underfitting / high bias), while a student who memorizes the exact letter sequence B, A, D, C... of the practice answer key scores 100% on the worksheet but bombs new exam questions (overfitting / high variance). - Class imbalance: If 99 out of 100 exam questions are True/False with answer "False", writing "False" blindly gets an A+ (99% accuracy) while understanding zero "True" cases. - Missing data: If a question has a smudged number, guessing the page average works differently depending on whether coffee spilled randomly (MCAR) or whether every smudged problem was intentionally the hardest bonus question (MNAR, where the smudge itself warns you!).

Naive workflows fail across all three areas in predictable ways: judging models by training loss or raw accuracy hides memorization and rare-class blindness; duplicating minority rows before splitting data leaks identical copies into validation; and computing fill-in averages across the entire dataset leaks future information and distorts variance.

Three compact numeric anchors tie the whole interview round together: 1. Bias-variance: Fitting polynomials to 20 noisy sine-wave points (noise floor 0.3^2 = 0.09 MSE) gives train/validation MSE of 0.314 / 0.330 for a straight line (underfitting), 0.078 / 0.114 for degree 3 (balanced), and 0.045 / 0.136 for degree 9 (overfitting—train MSE dips below the 0.09 noise floor!). 2. Class imbalance: With 1% fraud (1,000 of 100,000 rows), catching 800 frauds out of 2,000 alerts yields 98.6% accuracy (lower than a useless 99.0% "never fraud" rule!) yet delivers 80% recall and 40% precision; if missed fraud costs USD 200 and false-alarm review costs USD 10, the optimal cutoff is 10 / (10 + 200) = 0.048, far below 0.50. 3. Missing data: Filling 30% random blanks (300 of 1,000 rows) with the observed mean sets squared deviations on all 300 filled rows to zero, shrinking sample variance to 699 / 999 ≈ 70% and diluting a 0.60 correlation down to ~0.50.

Key points

  • Diagnose fit with two error curves plus a noise-floor baseline. Compare training and validation error against Bayes error (the lowest error achievable given label noise). Sweep capacity on a validation curve to locate the U-shaped validation minimum, and plot learning curves against sample size n to decide whether more data helps (overfitting's gap narrows as n grows; underfitting plateaus high and needs richer capacity or features).
  • Bias-variance decomposition is exact for squared error. Expected test MSE equals sigma^2 + bias^2 + variance, where bias measures systematic miss of the average model and variance measures sensitivity to random training draws (sigma^2 * k / n in ordinary least squares). Regularization trades a tiny rise in bias^2 for a larger drop in variance—for example, shrinking a noisy 10-sample mean (mu = 1, sigma^2 = 4, raw variance 0.400) by 0.8x adds 0.040 in bias^2 (0.2^2) while cutting variance to 0.256 (0.64 * 0.4), lowering total MSE from 0.400 to 0.296.
  • Replace accuracy with prevalence-aware metrics and cost-based thresholds. On rare classes, evaluate rankings with PR-AUC (Area Under the Precision-Recall Curve, whose random baseline equals positive prevalence) and decisions with precision, recall, F-beta, or expected cost. Train on natural prevalence when calibrated probabilities matter, setting the decision threshold to C_FP / (C_FP + C_FN) or selecting the top k scores matching human review capacity.
  • Resampling shifts predicted odds by the resampling factor k. Oversampling positives k-fold (or weighting positive loss by k) multiplies predicted odds p / (1 - p) by k; undo the shift analytically via p = p_s / (p_s + k * (1 - p_s)) or empirically via Platt scaling (logistic recalibration) or isotonic regression (monotonic step-function recalibration) on an untouched validation split. Always resample inside training folds only.
  • Treat missingness according to MCAR, MAR, or MNAR—and lock train/serve parity. Distinguish MCAR (completely random blanks), MAR (blanks explained by observed features), and MNAR (blanks driven by the hidden value itself). Pair simple or iterative imputation (filling blanks from training-fold statistics) with 0/1 missingness indicators or native tree splits, fit imputers strictly on training folds, and verify live serving NaN rates match training tables.

Common mistakes

  • Calling any train-validation gap "overfitting": A modest gap is normal whenever parameters are estimated from finite data; check whether validation error is actually rising with capacity or whether training error has dipped below the noise floor.
  • Throwing more training data at an underfit model: Once train and validation learning curves have converged at a high error plateau, doubling row count changes almost nothing—you need features, non-linearity, or less regularization.
  • Computing scalers, imputers, or SMOTE before splitting folds: Fitting preprocessing or oversampling across the full dataset leaks validation rows (or exact minority duplicates) across the split and produces wildly optimistic validation scores.
  • Feeding class-weighted or oversampled scores directly into dollar-cost formulas: Raw outputs from a 10x oversampled model overestimate true event probabilities dramatically unless recalibrated back to the natural base rate.
  • Dropping incomplete rows during training without a serving fallback: Production APIs cannot refuse to score a live user just because an optional profile field is NaN.
  • Imputing away a missingness leak (or signal): If a field is populated after the outcome happens (like a cancellation survey timestamp), both its value and its missingness leak the label and must be dropped or reconstructed point-in-time.

Follow-up questions

  • As you gradually dial up a regularization penalty, validation loss drops at first before climbing again—how do bias and variance explain each region? At very weak regularization, the model sits in the variance-dominated (overfitting) regime: each step up in penalty lambda dampens wild weight swings across training draws far faster than it pulls the average fit away from truth, so variance drops more than bias^2 rises and validation loss falls. Once lambda passes the sweet-spot minimum, little variance remains left to squeeze out while heavy shrinkage pulls predictions aggressively toward zero (or a flat constant), making bias^2 surge and pushing the model into underfitting. You can see both phases in shrinking a sample mean m = x_bar / (1 + lambda) when mu = 1 and sigma^2 / n = 0.400: total MSE falls from 0.400 (lambda = 0) to 0.286 (lambda = 0.4, where bias^2 = 0.082 and variance = 0.204), then climbs to 0.588 at lambda = 3 (bias^2 = 0.563, variance = 0.025).
  • Why does duplicating rare-class training rows inflate predicted class probabilities, and how can you restore calibrated estimates? Oversampling minority examples k times inflates the base prevalence inside the training set, multiplying the prior odds—and therefore a well-fit classifier's posterior odds p_s / (1 - p_s)—by k (for instance, at 1% true prevalence with k = 10, a 0.50 model output corresponds to only 0.091 true probability). You can correct the shift analytically by dividing the odds by k using p = p_s / (p_s + k * (1 - p_s)), or fit a lightweight post-hoc calibrator (Platt scaling or isotonic regression) on a held-out validation set at the natural class ratio, which also repairs extra overconfidence from memorizing duplicated minority rows. Even simpler, when data fits in memory, train directly on the natural distribution with log loss and lower the decision threshold instead of resampling.
  • Suppose a column has far more blank entries for positive examples than negative ones—when is that informative signal versus a data bug, and how should you handle each? It depends entirely on whether the exact same missingness mechanism operates before prediction time in live production. If fraudsters genuinely skip an optional phone field 40% of the time at checkout versus 5% for legitimate buyers, missingness is a real causal/behavioral signal (8x likelihood ratio, lifting a 1% prior to ~7.5%), so you should preserve it via an explicit is_missing binary indicator or native tree missing-branch routing rather than smoothing it away. Conversely, if blanks happen because positive and negative rows were stitched from two different logging pipelines—or because a column gets backfilled after an account churns—it is data leakage, and you must drop the column or rebuild it strictly as recorded at prediction time.
  • Modern overparameterized deep networks can reach zero training loss while still scoring well on unseen test sets—how do you reconcile this with classical bias-variance intuition? The mathematical identity expected squared error = sigma^2 + bias^2 + variance still holds, but raw parameter count stops being a good proxy for effective model complexity once parameters exceed training samples (the interpolation threshold, where test error can briefly spike before falling again in a double descent curve). Out of infinitely many weight settings that achieve zero training error, stochastic gradient descent started from small weights carries an implicit regularization bias toward smooth, minimum-norm interpolating functions, reinforced by weight decay, dropout, and data augmentation. As a result, adding width beyond the interpolation threshold can actually reduce prediction variance across datasets by smoothing decision boundaries rather than making them wigglier.

Follow-up questions

Similar questions

More Yahoo interview questions

All 8 Yahoo questions →