Tag: Data Eng

  • DL0261 Double Descent Reproduction

    Reproduce double descent: as you add samples, the min-norm least-squares test error peaks twice. Where is the interpolation threshold, and what creates the second peak?

    A three-panel question card. The first panel lists the setup: 40 strong features with variance 1.0, 160 weak unscaled features with variance 0.0025, label noise variance 1.0, a pseudo-inverse fit, and a sweep of n from 10 to 600. The second panel sketches a test-error curve against samples n with one spike near n of 40 and a taller spike near n of 200. The third panel asks which spike is the interpolation threshold, what creates the other spike, and what flattens both.

    The Problem: A team reproducing double descent sweeps the training-set size from 10 to 600 for a min-norm least-squares fit on 200 features (40 standardized, 160 left unscaled at variance 0.0025, label noise standard deviation 1). The averaged test error spikes near n = 40 and again near n = 200, and before the plot goes into a report they must say which spike is the interpolation threshold, what creates the other one, and how to flatten both.

    Answer

    For min-norm least squares on d features, the interpolation threshold is n = d, the last sample size at which the pseudo-inverse can still fit every noisy label exactly. There the design matrix is square with a smallest singular value near zero, so the coefficient norm explodes and the variance term \sigma^2 n/(d-n-1) diverges. A second peak needs a second scale in the features. When k directions have large variance and the other d-k are tiny, the tiny block acts as an implicit ridge \lambda_{\mathrm{eff}} = (d-k)\varepsilon on the strong block. The strong block then hits its own threshold at n \approx k, the effective number of parameters, while training error is still zero, and that peak grows taller as \lambda_{\mathrm{eff}} shrinks. Both peaks are label noise being interpolated through near-singular directions, so ridge tuned per sample size flattens them.

    (1) Threshold Equals Rank: For generic features the pseudo-inverse interpolates every label while n \leq d, so the threshold is n = d = 200, or more generally the rank of the feature covariance. It is the sample size where training error first leaves zero.
    (2) Variance, Not Bias, Blows Up: Near n = d the noise projected onto the smallest singular direction is amplified by the inverse of a near-zero singular value. The expected excess risk is infinite for n within one of d.
    (3) More Data Can Hurt: On the left flank every new row is one more constraint the interpolator must satisfy using ever-weaker directions, so adding samples raises error. This sample-wise non-monotonicity is model-wise double descent read along the other axis of the ratio n/d.
    (4) The Second Peak Needs Two Scales: Isotropic features give exactly one peak. With 40 unit-variance and 160 tiny-variance columns, the tiny block adds roughly \lambda_{\mathrm{eff}} I_n to the Gram matrix, a weak implicit ridge on the strong block.
    (5) Location Tracks Effective Parameters: The strong block reaches its own threshold at n \approx k = 40, the count of directions whose variance dominates the tail, even though training error is still zero there. Its height scales like 1/\sqrt{\lambda_{\mathrm{eff}}/k}, so a heavier tail smooths it away.
    (6) Noise Is The Fuel: Both spikes scale with \sigma^2. With clean labels and a well-specified model they nearly vanish, while omitted features act as extra noise and revive them.
    (7) Tuned Ridge Removes Both: Choosing \lambda per sample size gives a smooth, near-monotone curve. Standardizing all 200 features removes only the extra peak and leaves the one at n = d.

    Mathematical Formulation:
    \hat w = X^{\top}(XX^{\top})^{-1} y \quad (n \leq d)
    \hat w = (X^{\top}X)^{-1}X^{\top} y \quad (n \geq d)
    R(\hat w) = (\hat w - w^{*})^{\top}\Sigma\,(\hat w - w^{*})
    R_{\mathrm{iso}}(n) = \|w^{*}\|^2 (1 - n/d) + \frac{\sigma^2 n}{d - n - 1}
    R_{\mathrm{iso}}(n) = \frac{\sigma^2 d}{n - d - 1}
    XX^{\top} = SS^{\top} + WW^{\top} \approx SS^{\top} + \lambda_{\mathrm{eff}} I_n
    \lambda_{\mathrm{eff}} = (d - k)\,\varepsilon

    Where:

    • \hat w is the fitted coefficient vector, X \in \mathbb{R}^{n \times d} the design matrix with n samples and d features, and y the noisy labels. Both lines equal the pseudo-inverse solution X^{+}y.
    • R is the excess test risk (test MSE minus the noise floor), w^{*} the true coefficients, \Sigma the feature covariance, and \sigma^2 the label-noise variance.
    • The two R_{\mathrm{iso}} lines are exact for isotropic Gaussian features, the first for n \leq d-2 and the second for n \geq d+2. The second holds for any \Sigma, because ordinary least squares is invariant to invertible reparameterizations of the features.
    • S \in \mathbb{R}^{n \times k} holds the strong columns (variance 1) and W \in \mathbb{R}^{n \times (d-k)} the weak columns (variance \varepsilon), and I_n is the n \times n identity.
    • \lambda_{\mathrm{eff}} is the implicit ridge contributed by the weak block, equal to its total variance. In the scenario k = 40, d - k = 160, and \varepsilon = 0.0025.

    Worked Example (d = 200, k = 40, unit-norm signal, noise variance 1):
    R(210) = 200/9 \approx 22.2
    R(400) = 200/199 \approx 1.0
    \lambda_{\mathrm{eff}} = 160 \times 0.0025 = 0.4
    R(40) \approx \frac{\sigma^2}{2\sqrt{\lambda_{\mathrm{eff}}/k}} = \frac{1}{2 \times 0.1} = 5
    R(100) \approx \frac{40}{59} + \frac{60}{99} \approx 1.3

    The first two lines are exact for this anisotropic design, because above the threshold the risk only knows n and d. The last two are heuristics for the two-scale design. At n = k the smallest eigenvalues of S^{\top}S crowd toward zero along the Marchenko-Pastur edge, so a ridge of only 0.4 caps the variance near 5 instead of infinity. Between the peaks the risk splits into an OLS-like strong part k/(n-k-1) and a weak part (n-k)/(d-n-1), in which 160 tiny features interpolate the leftover n-k noise dimensions. That weak term grows from about 0.6 at n = 100 to about 7.4 at n = 180, which is more data hurting in its plainest form.

    To reproduce the curve, draw Gaussian rows with column standard deviations 1 for 40 features and 0.05 for 160, and set w^{*} to a unit vector on the strong block. Fit np.linalg.pinv(X) @ y for each n and score the exact excess risk (\hat w - w^{*})^{\top}\Sigma(\hat w - w^{*}) rather than a finite test set, averaging 60 draws per n. Log training error as well, because it is the only measurement that locates the threshold unambiguously. It stays at zero through n = 200 and turns positive right after.

    Two log-scale panels against training samples n from 10 to 600. Left: the min-norm excess test risk rises to a first spike at n of 40, falls to a valley near n of 100, climbs to a much taller spike at n of 200, then decays, while ridge with lambda tuned per n stays smooth and low throughout. Right: the same min-norm risk split by feature block, where the strong-block curve carries the n of 40 spike alone and both curves spike at n of 200 with the weak block on top.

    Figure 1: Left, the min-norm excess risk averaged over 60 draws spikes at n = 40 and again at n = 200, while ridge with its penalty tuned per sample size stays smooth. Right, the n = 40 spike lives only in the strong block, while near n = 200 both blocks blow up and the weak block carries most of the variance.

    The two spikes look alike on a test-error plot but differ in every diagnostic that matters. That is why the interpolation threshold has to be read from training error and parameter count, not from the tallest bump. Above n = d the variance splits between the blocks exactly in proportion to their sizes, 40 to 160. Below it, the extra spike is a hidden threshold of the strong subspace that the training curve never shows.

    PropertySpike near n = 40 (extra peak)Spike at n = 200 (threshold)
    Location rulen close to k, the count of high-variance directions (effective parameters)n equal to d, the full column rank of the design
    What goes near-singularThe 40 strong columns aloneThe whole square 200 by 200 design
    Training error on each sideZero on both sides, the model still interpolatesZero below, positive above
    Height set byImplicit ridge of 0.4 from the weak block, finite at about 5Nothing, expected risk diverges at n = d
    Present with isotropic featuresNoYes
    Removed byStandardizing features, a heavier weak tail, or tuned ridgeTuned ridge, or keeping n well away from d

    Login to view more content
  • DL0235 The Infinite Web Paradox

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

  • DL0226 Checkpoint Formats: safetensors and Memory Mapping

    A teammate wants to load a 40GB pickle checkpoint and wonders why Hugging Face pushed safetensors instead. Separately, how does a 2TB dataset fit in 64GB of RAM?

    A three-panel question card. The first panel describes one shared checkpoint: file pytorch_model.bin, Python pickle format, 40 GB in fp16, downloaded from a stranger's repo, on a box with 64 GB of RAM, and asks whether it is safe to load and whether it will fit. The second panel shows Hugging Face moving the Hub default from a pickle .bin file to a safetensors file and asks why. The third panel shows 2 TB of token ids on NVMe next to 64 GB of RAM and asks how the corpus fits.

    The Problem: A teammate on a 64 GB training box wants to torch.load a 40 GB pickle checkpoint pulled from someone else’s repo, and asks why Hugging Face moved the Hub to safetensors. The same box must also train on a 2 TB tokenized corpus, which is about 31 times larger than its RAM.

    Answer

    A pickle checkpoint is a program, not a data file. Python’s unpickler executes opcodes that can import any callable and call it, so loading an untrusted .bin is arbitrary code execution. Safetensors replaces it with a passive layout of an 8-byte length, a JSON header that maps each tensor name to dtype, shape and byte offsets, and one contiguous byte buffer. Because nothing needs decoding, a loader can mmap the file and hand out zero-copy tensor views, so only the pages a process actually touches are read from disk. That removes the unpickling pass and the second copy of the weights, which is why CPU loading is often more than an order of magnitude faster and peak RAM halves. The 2 TB dataset fits the same way, because Hugging Face datasets keeps it as memory-mapped Apache Arrow (or streams it) and the OS page cache holds only the working set.

    (1) Pickle Is A Program: The GLOBAL opcode imports any module attribute and REDUCE calls it with arguments, so a __reduce__ returning os.system runs at load time. Sharing a pickle checkpoint means sharing whatever payload it carries.
    (2) weights_only Is A Mitigation, Not A Format: torch.load(weights_only=True) restricts the unpickler to an allowlist of types, but it still parses an executable opcode stream and has needed security patches.
    (3) Header Then Bytes: The first 8 bytes are a little-endian unsigned 64-bit length N, the next N bytes are JSON, and the rest is tensor data in C order with no gaps or overlaps, so validation is just bounds checking.
    (4) Zero-Copy mmap: Tensors are views into the mapped file, so there is no deserialization pass and no intermediate copy, and every process on the host shares the same page cache.
    (5) Lazy And Sliced Loads: safe_open with get_tensor or get_slice reads one tensor or one slice of it, which is how a tensor-parallel rank loads only its own columns.
    (6) Meta-Device Skeleton: from_pretrained builds the model with no storage on the meta device and fills it shard by shard, so the random-init copy never exists.
    (7) Datasets Never Load Into RAM: Arrow files are memory-mapped and row lookup is offset arithmetic, while streaming=True reads remote shards incrementally, so RAM holds the working set, not the corpus.

    The danger on the pickle side is concrete. torch.save writes a zip archive whose data.pkl entry is a pickle program, with tensor storages kept as separate raw entries. On load, the unpickler walks that program: GLOBAL pushes a callable named by module and attribute, and REDUCE applies it to a tuple. A crafted object whose __reduce__ returns os.system with a shell command therefore executes the moment the file is opened, before a single tensor is touched. Safetensors has no such code path. A typical header entry reads “model.embed_tokens.weight”: {“dtype”: “F16”, “shape”: [32000, 4096], “data_offsets”: [0, 262144000]}, the library rejects headers above 100 MB, duplicate names, and offsets that disagree with dtype times shape, and the worst a malicious file can do is fail validation.

    Byte layout of a safetensors file: an 8-byte length N, a JSON header of N bytes, then contiguous tensor data for embed_tokens, layers.0.q_proj, 288 more tensors, and lm_head. Below the header, a box shows a JSON entry with dtype F16, shape 32000 by 4096 and data offsets 0 to 262144000. Below the tensor region, a row of twenty 4 KiB pages mapped into the process shows only the six pages under layers.0.q_proj shaded as resident after one get_tensor call, while the rest are mapped but never read.

    Figure 1: A safetensors file is an 8-byte length, a JSON index, and one contiguous tensor buffer. After a single mmap call, asking for layers.0.q_proj faults in only the pages under its byte range (plus the partial edge pages), while every other tensor stays on disk until touched.

    Mathematical Formulation:
    \mathrm{start}(t) = 8 + N + b_t
    e_t - b_t = s(\tau_t) \prod_{j} d_{t,j}
    M_{\mathrm{pickle}} \approx 2 P s
    M_{\mathrm{safe}} \approx P s
    W_{\mathrm{step}} = B \cdot L \cdot s_{\mathrm{tok}}

    Where:

    • \mathrm{start}(t) is the absolute file byte where tensor t begins, N is the JSON header length stored in the first 8 bytes, and b_t is the begin value of its data_offsets, which is relative to the end of the header.
    • e_t is the end offset, s(\tau_t) the bytes per element of dtype \tau_t (2 for F16 and BF16, 4 for F32), and d_{t,j} the shape dimensions; a header where this product disagrees with the byte range is rejected.
    • P is the parameter count and s the bytes per parameter of the stored dtype; M_{\mathrm{pickle}} counts a random-initialized model plus the unpickled state dict held at the same time.
    • M_{\mathrm{safe}} counts a single copy when the skeleton lives on the meta device, and that copy is file-backed page cache the kernel can evict and share rather than anonymous memory.
    • W_{\mathrm{step}} is the data touched per training step, with B sequences per batch, L tokens per sequence, and s_{\mathrm{tok}} bytes per token id (2 for uint16 when the vocabulary has at most 65,536 entries).

    Worked Example (one 64 GB box, 40 GB checkpoint, 2 TB corpus):
    P s = 20 \times 10^{9} \cdot 2\ \mathrm{B} = 40\ \mathrm{GB}
    M_{\mathrm{pickle}} \approx 2 \cdot 40\ \mathrm{GB} = 80\ \mathrm{GB} > 64\ \mathrm{GB}
    M_{\mathrm{safe}} \approx 40\ \mathrm{GB}
    W_{\mathrm{step}} = 512 \cdot 2048 \cdot 2\ \mathrm{B} = 2\ \mathrm{MiB}
    2 \times 10^{12}\ \mathrm{B} / 4096\ \mathrm{B} \approx 4.9 \times 10^{8}

    The checkpoint numbers explain the teammate’s experience. A 20B-parameter fp16 model is 40 GB, and the classic pickle path needs about 80 GB of anonymous memory, so on a 64 GB box it swaps or gets OOM-killed before load_state_dict finishes. The mmap path holds one evictable copy, and the unavoidable cost is the raw read itself, roughly 13 s at 3 GB/s from NVMe. Hugging Face’s own GPT-2 benchmark reports tens of times faster CPU loading with a warm page cache and about 2x on GPU, where the host-to-device copy dominates; part of the CPU number is deferred I/O, since pages are read on first touch rather than at open. The corpus numbers are even more lopsided. A 2048-token uint16 sequence is exactly 4096 bytes, one page, so the 2 TB file holds about 490 million sequences and a 512-sequence batch is 512 random 4 KiB reads. A datacenter NVMe drive serves several hundred thousand such reads per second, which puts each step’s I/O on the order of a millisecond.

    Two schematic charts of host RAM. Left: loading a 40 GB fp16 checkpoint, the pickle path climbs to 40 GB during random initialization and then to about 80 GB while torch.load reads the state dict, crossing the 64 GB physical RAM line, while the safetensors path keeps anonymous RAM near 1 GB and its page cache rises to 40 GB. Right: reading a 2 TB corpus, loading it into RAM runs out of memory after 64 GB, while the memory-mapped path keeps process RSS near 2 GB and the page cache saturates just under the RAM ceiling.

    Figure 2: Schematic resident memory on the 64 GB box. (a) The pickle path holds a random-initialized model and the unpickled state dict at once and needs about 80 GB, while the mmap path keeps the weights in evictable page cache. (b) Reading the 2 TB corpus into RAM fails after 64 GB, whereas a memory-mapped corpus keeps process RSS near 2 GB and lets the page cache cycle at the RAM ceiling.

    Inside transformers, from_pretrained runs a fixed chain: resolve repo id and revision → fetch files into the hub cache (content-addressed blobs behind snapshot symlinks) → read config.json and pick the model class → open model.safetensors.index.json, whose weight_map assigns every tensor name to a shard → build the module tree on the meta device → per shard, safe_open, read each tensor, cast to torch_dtype and assign → tie shared weights and place layers by device_map. When only pytorch_model.bin exists, the same chain unpickles instead. That is why Hugging Face’s conversion bot opened safetensors pull requests on popular repos and why save_pretrained now writes safetensors by default.

    The dataset side uses the same operating-system trick on a different file format. load_dataset converts source files once into Apache Arrow tables in the local cache, and a Dataset object is a view over those memory-mapped files. Arrow stores a token column as one contiguous values buffer plus an offsets buffer, so row i is two offset lookups and a slice, with no Python objects created until you ask for them. Many pretraining codebases go one step simpler and write a single flat uint16 token array read with numpy.memmap, where sample i is a slice at byte 4096 i. When 2 TB exceeds local disk too, streaming=True returns an IterableDataset that pulls shards over HTTP as iteration proceeds and shuffles approximately with a shard-order shuffle plus a fixed-size sample buffer.

    PropertysafetensorsPickle .bin (torch.save)
    What the file isPassive data: 8-byte length, JSON index, raw tensor bytesA pickle program inside a zip archive, plus raw storage entries
    Opening an untrusted fileNo code path; a malformed header fails bounds checksOpcodes can import and call any function, so loading runs attacker code
    Load pathmmap, zero-copy views, pages read on first touchUnpickle, rebuild objects, copy storages into fresh memory
    Peak host RAM, 40 GB modelAbout one evictable copy with a meta-device skeletonAbout two copies: initialized model plus state dict
    Partial readsget_tensor and get_slice fetch one tensor or one sliceThe whole program is unpickled; mmap=True since PyTorch 2.1 avoids only the storage copies
    What it can storeTensors plus a flat string-to-string metadata mapAny Python object: optimizer state, schedulers, custom classes
    ReadersRust core with PyTorch, NumPy, JAX, TensorFlow and MLX bindingsPython with the exact classes importable, in practice PyTorch only

    Login to view more content
  • DL0219 Preference Modeling vs Reward Modeling

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

  • DL0211 LLMs as Classifiers via Log-Probs

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

  • ML0142 Feature Selection Methods

    You have 50,000 features and 100,000 rows. How do you choose features with filter, wrapper, and embedded methods, and when does feature selection itself leak?

    Line-art sketch of a training matrix with 100,000 rows and 50,000 thin feature columns, a separate green label column y, a shaded block of near-copy columns, and a pale yellow holdout band across the bottom rows, next to three boxes stating p equals 50,000, n equals 100,000, p over n equals 0.5, that only a few hundred columns likely carry signal, and the question of which columns to keep and how to score that choice honestly

    The Problem: A 100,000 by 50,000 training matrix with a label column, a block of near-copy columns, and a holdout band. Most columns are noise, and whatever procedure picks the columns must still be scored honestly.

    Answer

    With 50,000 features and 100,000 rows, no single method fits, so run a cost-ordered funnel in which each stage only scores what the cheaper stage kept. Filter scores such as mutual information, chi-squared, or correlation with a false-discovery cutoff cut 50,000 columns to a few thousand in minutes, but they judge each feature alone. Embedded methods such as an L1 path or gradient-boosted importance, repeated under stability selection, then choose a few hundred features jointly. A wrapper such as RFE with cross-validation is affordable only on that short list, because forward selection over all 50,000 columns would need millions of model fits. Selection leaks whenever a label-reading step sees rows that later score the model, so the whole funnel must be refit inside every training fold and the holdout must never touch it.

    (1) Filter First: Univariate scores (MI, chi-squared, ANOVA F, correlation) cost O(np) and parallelize across columns, but they miss interactions and keep redundant copies. At \alpha = 0.05, 50,000 tests produce about 2,500 false hits by chance, so cut with Benjamini-Hochberg.
    (2) Embedded Second: L1-penalized models and tree importances select features jointly for roughly the price of one model fit. The lasso keeps an arbitrary member of a correlated group, and impurity importance favors high-cardinality columns.
    (3) Wrapper Last: RFE and forward or backward search score the real model, so they catch interactions, but cost grows with features times refits. Dropping 10% per round takes 300 features to 80 in about 13 refits.
    (4) Stability Beats a Single Ranking: Refitting on 100 random half-samples and keeping features chosen at least 80% of the time puts a hard bound on the expected number of false selections.
    (5) Permutation Beats Impurity: Measure importance as the held-out score drop when a column is shuffled, and shuffle near-duplicates together so credit is not split between them.
    (6) Selection Is Training: Any step that reads y belongs inside the cross-validation pipeline, and choosing k with the same CV that reports the score requires nested CV.

    Left-to-right funnel: 50,000 raw features pass label-free hygiene that removes constant, duplicate, and mostly missing columns leaving about 38,000, then a filter stage with mutual information, chi-squared, correlation and a Benjamini-Hochberg cutoff leaving about 3,000, then an embedded stage with an L1 path, gradient-boosted gain and stability selection leaving about 300, then an RFE-CV wrapper with permutation scores leaving about 80, then the final model; the filter, embedded and wrapper stages sit inside a dashed box labeled as fit on the training fold and applied to the validation fold, and an arrow from the final model goes down to an untouched holdout box that scores the whole funnel once

    Figure 1: The selection funnel. Label-free hygiene runs once, while the filter, embedded, and wrapper stages sit inside the dashed box and are refit on every training fold. Counts are typical for a wide tabular dataset, and the untouched holdout scores the finished funnel exactly once.

    The funnel shape follows from cost. Label-free hygiene (constant columns, exact duplicates, columns over 95% missing) never reads the label, so running it once on all rows is nearly harmless, and on wide tabular data it often trims the 50,000 columns to roughly 38,000. Every stage after that reads y, which makes it a fitted transform exactly like a model: fit it on the training fold, apply it to the validation fold. In scikit-learn terms the selector lives inside the Pipeline handed to the cross-validator, not in a preprocessing script that runs before the split. With p/n = 0.5 the problem is wide but not hopeless, so a regularized model could train on everything; selection here is mostly about serving cost, interpretability, and stability, which is why the funnel should optimize recall early and precision late.

    Mathematical Formulation:
    I(X_j;Y) = \sum_{x,y} p(x,y)\log\frac{p(x,y)}{p(x)\,p(y)}
    \hat{w} = \arg\min_{w}\ \frac{1}{n}\sum_{i=1}^{n}\ell(y_i, w^\top x_i) + \lambda\|w\|_1
    \mathrm{PI}_j = s(f, D_{\mathrm{val}}) - \mathbb{E}_{\pi}\, s(f, D_{\mathrm{val}}^{\pi_j})
    \hat{\Pi}_j = \frac{1}{B}\sum_{b=1}^{B}\mathbf{1}\{j \in \hat{S}_{\lambda}(I_b)\}
    \mathbb{E}[V] \leq \frac{q^2}{(2\pi_{\mathrm{thr}} - 1)\,p}

    Where:

    • I(X_j;Y) is the mutual information between feature X_j and label Y, with joint p(x,y) and marginals p(x), p(y). It is zero only under independence, so unlike correlation it also detects nonlinear dependence.
    • \hat{w} are the coefficients of an L1-penalized model over n rows (x_i, y_i), \ell is the log-loss, and \lambda sets sparsity: a larger \lambda drives more coefficients to exactly zero.
    • \mathrm{PI}_j is the permutation importance of feature j: the score s (for example AUC) of fitted model f on held-out data D_{\mathrm{val}}, minus the average score after shuffling column j, written D_{\mathrm{val}}^{\pi_j}.
    • \hat{\Pi}_j is the selection frequency of feature j across B random half-samples I_b, and \hat{S}_{\lambda}(I_b) is the set selected on subsample b at penalty \lambda.
    • V is the number of noise features that survive, q is the average number selected per subsample, \pi_{\mathrm{thr}} \in (0.5, 1] is the frequency threshold, and p is the total feature count; the bound assumes noise features are exchangeable.

    Worked Leakage Example:
    Make every one of the 50,000 features pure noise, rank them by absolute correlation with y on all 100,000 rows, keep the top k = 500, and only then run 5-fold CV with OLS. A kept feature has |z| > 2.576, so its expected squared correlation is about 8.45/n, and because selection used every row, the validation folds share that spurious correlation.

    \mathbb{E}[R^2_{\mathrm{cv}}] \approx \sum_{j \in S} r_j^2 - k/n_{\mathrm{tr}}
    500 \times 8.45/10^5 - 500/80000 \approx 0.036

    Here S is the selected set, r_j the full-data correlation of feature j, and n_{\mathrm{tr}} = 80{,}000 the training-fold size. The leaky pipeline reports an R^2 of about 0.036 on a target nothing can predict, while selecting inside each fold reports about -500/80000 \approx -0.006, the honest answer.

    PropertyFilterEmbeddedWrapper
    What it scoresEach feature alone against the label (MI, chi-squared, F, correlation)Features jointly, as a side effect of fitting (L1 zeros, tree gain)Candidate subsets by the real model’s validation score
    Cost at 50,000 featuresOne pass per column; seconds to minutesAbout one model fit, times B under stability selectionInfeasible on all columns; forward search needs millions of fits
    Interactions and redundancyBlind to both; keeps every copy of a duplicated signalTrees see interactions; lasso drops redundant copies arbitrarilySees both, through the model it wraps
    Main bias or riskMultiple testing: thousands of chance hits without FDR controlUnstable on correlated groups; impurity importance favors high cardinalityOverfits the validation score after searching many subsets
    Role in the funnelFirst: generous threshold, optimize recallSecond: joint pruning to a few hundred, stabilizedLast: fine pruning on the short list

    Login to view more content
  • ML0141 Fairness Metrics & Calibration

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

  • ML0131 Survival Analysis & Censoring

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

  • ML0120 Sampling Methods

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

  • ML0117 Clustering Internal Metrics

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