Tag: Data Eng

  • ML0114 Categorical Feature Encoding

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0113 Missing Data Handling

    How do you handle missing data: what do MCAR, MAR, and MNAR mean, when is dropping vs imputing wrong, and how do missing-indicator features fit in?

    Consider a credit-approval model for a card issuer such as Capital One. Self-reported income is blank on 14% of historical applications, several other fields have gaps, and the deployed model must still score every live application, including the ones with blanks.

    Line-art scene: on the left, a training table of six loan applications with columns id, age, income, tenure, balance and default, where several cells are blank and marked with a question mark; an arrow labeled train points to a credit model box; on the right, a live application card with income left blank points to the same model with an arrow labeled score; below the model, the questions why is each value blank, drop the row, fill it in, or tell the model it was blank

    The Problem: A credit model is trained on historical applications with blank cells in several columns, and it must also score live applications whose fields can be blank. Before choosing between dropping, filling, or flagging, you need to know why each value is missing.

    Answer

    Handling missing data starts with asking why a value is missing, because the right fix depends on the missingness mechanism rather than on the missing rate. In Rubin’s taxonomy, MCAR means blanks are independent of all data, MAR means they depend only on observed features, and MNAR means they depend on the missing value itself. Dropping rows is unbiased only under MCAR, still wastes data, and is impossible at serving, where every request must be scored. Mean or median filling keeps the center but shrinks variance and correlations under every mechanism, while conditional imputers such as KNN or MICE are valid under MAR. Under MNAR the blank itself carries signal, so a missing-indicator feature or native NaN routing in boosted trees captures what no fill value can. Every imputer is fit on the training fold only and replayed identically at serving.

    (1) Diagnose Before Fixing: Predict each column’s missingness flag from the other observed columns, and an AUC near 0.5 is consistent with MCAR. MAR versus MNAR cannot be tested from the data alone and needs domain evidence.
    (2) Dropping Compounds: With 10 features each 5% MCAR-missing, listwise deletion keeps only 0.95^{10} \approx 0.60 of rows. Under MAR or MNAR the surviving rows are also a biased sample.
    (3) Mean Filling Distorts: Filling a fraction p with one value scales variance by about (1-p) and correlations by about \sqrt{1-p}. It also creates an artificial spike that trees will happily split on.
    (4) Conditional Imputation For MAR: KNN, MICE (chained equations), or a per-column model predict the blank from observed features. Use multiple imputation when you need honest standard errors.
    (5) Indicators Carry MNAR Signal: A binary is-missing column, or the learned default direction in XGBoost and LightGBM, lets the model treat a blank as information rather than noise.
    (6) Fit On Train, Replay At Serving: Imputation statistics are model parameters. Fitting them on all rows leaks test information, and recomputing them at serving causes training-serving skew.

    Mathematical Formulation:
    \mathrm{MCAR}:\ P(R \mid Y_{obs}, Y_{mis}) = P(R)
    \mathrm{MAR}:\ P(R \mid Y_{obs}, Y_{mis}) = P(R \mid Y_{obs})
    \mathrm{MNAR}:\ P(R \mid Y_{obs}, Y_{mis}) \neq P(R \mid Y_{obs})
    \mathrm{Var}(\tilde{x}) \approx (1-p)\,\sigma_x^2
    \rho(\tilde{x}, y) \approx \sqrt{1-p}\;\rho(x, y)

    Where:

    • R is the missingness indicator matrix, with R_{ij} = 1 when feature j of row i is blank; Y_{obs} and Y_{mis} are the observed and missing parts of the data.
    • Under MCAR the pattern ignores all values, under MAR it depends only on what you can see, and under MNAR it still depends on Y_{mis} after conditioning on Y_{obs}, which is why MNAR cannot be verified from observed data alone.
    • \tilde{x} is the mean-imputed column, p the fraction of rows filled, \sigma_x^2 the true variance, and \rho the Pearson correlation with any other variable y; both approximations hold under MCAR for large samples.
    • At p = 0.3, variance falls to 70% of its true value and a true correlation of 0.60 is reported as about 0.60 \times 0.837 \approx 0.50.

    Worked Example:
    Suppose 80% of applicants earn about 60k and 20% earn about 200k. High earners leave income blank 50% of the time, everyone else 5% of the time, which is an MNAR pattern. The true mean, the observed share, and the mean of the observed rows are:

    \mu_{true} = 0.8(60) + 0.2(200) = 88
    P(\mathrm{obs}) = 0.8(0.95) + 0.2(0.5) = 0.86
    \mu_{obs} = (45.6 + 20) / 0.86 \approx 76.3

    Complete-case analysis and mean filling both anchor on 76.3k, about 13% below the truth. Worse, 0.10 / 0.14 \approx 0.71 of the blank rows are actually high earners, so filling them with 76.3k is wrong in a systematic direction. A missing indicator lets the model learn that a blank income usually means a high income, which is exactly the signal an imputer fitted on observed rows cannot fully recover.


    Login to view more content
  • ML0111 Conditional Random Fields

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0110 LDA & QDA

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0109 Expectation-Maximization

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • ML0107 Time-Series Cross-Validation

    Why does random k-fold cross-validation leak on temporal data such as daily returns at a quantitative trading firm, and how do walk-forward validation, purged cross-validation, and embargo periods fix it?

    A daily price path over 40 trading days above a strip of 40 day cells, where 8 shuffled cells are marked as test rows and the rest as training rows; below the strip, the 5-day label windows of training row 17, test row 18, and training row 19 are drawn as horizontal bars that almost completely overlap

    The Problem: A daily return series split by shuffled 5-fold assignment. Test row 18 sits between training rows 17 and 19, and every row’s label is the next 5-day return, so the three label windows cover almost the same days. What does the cross-validation score actually measure here?

    Answer

    Random k-fold assumes rows are exchangeable, so holding one out should reveal nothing about it to the model. Temporal data break that assumption through three leakage paths: look-ahead into future periods, serial correlation between adjacent rows, and overlapping labels whose horizons share the same future returns. The result is a validation score that rewards recalling neighbors, and it collapses once the model faces a genuinely unseen future. Walk-forward validation removes look-ahead by training only on the past and testing on the next block, with a gap of one label horizon before each test window. Purged k-fold keeps training data on both sides of the test block but deletes every training row whose label window touches the test span. An embargo then drops a further buffer of rows after the test block to absorb dependence that purging cannot see.

    (1) Look-Ahead Path: Shuffled folds train on 2024 to predict 2022, so the model absorbs regimes, volatility levels, and drift it could never have known at prediction time.
    (2) Neighbor Path: With persistent features such as moving averages or rolling volatility, rows t-1 and t+1 are near-duplicates of row t, so a flexible model scores well by recalling neighbors rather than learning signal.
    (3) Label-Overlap Path: A label built over horizon h shares up to h-1 return days with each adjacent label, and in 5-fold about 80% of those overlapping neighbors land in training, handing the model most of the test target.
    (4) Expanding vs Rolling Walk-Forward: Expanding windows keep all history and suit stable relationships. Rolling windows keep only the last W periods and adapt to drift at the cost of higher variance.
    (5) Purge Plus Embargo: Purging removes label-window overlap on both sides of the test block, and the embargo (often \epsilon \approx 0.01T) removes the rows right after it whose features still carry test-period information.
    (6) Distinct From Pipeline Leakage: This is not target leakage or a scaler fit on the full dataset. A perfectly clean feature pipeline still leaks here, because the leak lives in the dependence structure of the rows themselves.

    Walk-forward validation is the closest replica of deployment: fit on everything up to a cut-off, score the next block, move the cut-off forward, and refit. The gap of h rows before each test block is not optional, because the last training labels would otherwise be computed from returns inside the test window. Scikit-learn exposes it directly as TimeSeriesSplit(gap=h, max_train_size=W), where setting W switches expanding to rolling. The weakness of walk-forward is statistical: one backtest path, early folds starved of data, and only the later part of history ever tested. Purged k-fold fixes the data budget by letting every block take a turn as the test set while still training on both sides, which is acceptable when the feature-label relationship is roughly stationary. Note that unshuffled contiguous k-fold is not a fix on its own, since it still trains on the future and leaks through every fold boundary.

    Mathematical Formulation:
    \mathcal{I}_i = [t_{i,0},\, t_{i,1}]
    t_{i,1} = t_{i,0} + h
    \mathcal{P} = \{\, i : \mathcal{I}_i \cap [T_0, T_1] = \emptyset \,\}
    \mathcal{E} = \{\, i : T_1 \leq t_{i,0} \leq T_1 + \epsilon \,\}
    \mathcal{S}_{\mathrm{purged}} = \mathcal{P} \setminus \mathcal{E}
    \mathcal{S}^{(k)}_{\mathrm{WF}} = \{\, i : \mathcal{I}_i \cap [T_0^{(k)}, \infty) = \emptyset \,\}
    \mathcal{S}^{(k)}_{\mathrm{roll}} = \{\, i \in \mathcal{S}^{(k)}_{\mathrm{WF}} : t_{i,0} \geq T_0^{(k)} - W \,\}

    Where:

    • \mathcal{I}_i is the label window of sample i: features are observed and the prediction is made at t_{i,0}, and the label is fully realized at t_{i,1}, which is h steps later (fixed, or per row for event-driven labels).
    • [T_0, T_1] is the test span, running from the first test row’s t_{i,0} to the latest test label end t_{i,1}.
    • \mathcal{P} is the purged candidate set with no label-window overlap, \mathcal{E} is the embargo set of rows starting within \epsilon after T_1 (commonly \epsilon \approx 0.01T for a series of length T), and \mathcal{S}_{\mathrm{purged}} is the final training set.
    • \mathcal{S}^{(k)}_{\mathrm{WF}} is the expanding walk-forward training set for fold k with test start T_0^{(k)}. Requiring every label window to end before the test starts builds the h-row gap in automatically, and \mathcal{S}^{(k)}_{\mathrm{roll}} keeps only the last W time units.

    Worked Example: Take T = 1000 trading days, one row per day, with a 5-day forward-return label, so h = 5 and row d has window [d, d+5]. In purged 5-fold, fold 3 tests rows 400 to 599, and the last test label ends at day 604, so the test span is [400, 604]. Rows 395 to 399 have windows reaching day 400 or later and are purged. Rows 600 to 604 start inside the span and are purged too. A 1% embargo then drops the next 10 rows, 605 to 614.

    \text{purged} = 5 + 5 = 10
    \text{embargoed} = 0.01 \times 1000 = 10
    \text{kept} = 800 - 10 - 10 = 780

    Purged CV keeps 780 of the 800 candidate training rows (97.5%), so the protection is cheap. Expanding walk-forward on the same test block trains only on rows 0 to 394, which is 395 rows. That data cost is why purged CV is the usual tool for model selection, while walk-forward serves as the final deployment rehearsal.

    PropertyPurged k-fold + embargoWalk-forward (expanding)Walk-forward (rolling)Random k-fold
    Training dataPast and future of the test blockAll history before the test blockLast W periods before the test blockShuffled rows from everywhere
    Overlapping labelsPurged on both sidesGap of h before the test blockGap of h before the test blockNot handled; neighbors share returns
    Residual serial dependenceEmbargo after the test blockOnly the past side existsOnly the past side existsNot handled
    Periods testedWhole series once (CPCV gives several paths)Later periods only, one pathLater periods only, one pathAll rows, but leaky
    Mimics deploymentNo, some folds train on the futureYes, refits with growing historyYes, refits on a recent windowNo
    Main weaknessAssumes a roughly stationary relationshipEarly folds starve; stale regimes dilute the fitHigher variance; W is another hyperparameterOptimistic by construction

    Login to view more content
  • MSD0146 Customer LTV Prediction

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0144 Multi-Annotator Label Aggregation

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0141 LLM-Assisted Grading of Human Labeling Work

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.

  • MSD0140 Feature Store: Online and Offline

    This is an IntvML Pro interview question. Upgrade to Pro to unlock the full prompt, diagrams, and solution.