Cross-Validated Metrics with Pooled Out-of-Fold Scores

Quick Overview

Implement unshuffled k-fold splits, leak-free out-of-fold predictions from a scaled ridge regression, and a summary of MSE, MAE and R² per fold and on the pooled predictions. It tests careful cross-validation mechanics, fold standard errors, and why pooled and averaged R² can disagree.

Cross-Validated Metrics with Pooled Out-of-Fold Scores

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement three functions that evaluate a ridge regression with k-fold cross-validation: - `kfold_indices(n_samples, n_splits)` builds unshuffled k-fold splits. - `out_of_fold_predictions(X, y, n_splits, alpha=1.0)` produces leak-free out-of-fold (OOF) predictions. - `cross_validate_metrics(X, y, n_splits, alpha=1.0)` summarizes MSE, MAE and R² both per fold and on the pooled OOF predictions. Requirements: - `kfold_indices` uses contiguous validation blocks in input order, and the first `n % k` folds get one extra sample. It returns a list of `(train_idx, val_idx)` pairs that match unshuffled `KFold`. - In each fold, fit `StandardScaler` and `Ridge(alpha)` on the training fold only, then predict the validation fold. - `out_of_fold_predictions` returns `(preds, fold_ids)`: float64 predictions and the int64 fold index (0-based) of each sample. - `cross_validate_metrics` returns a float64 `DataFrame` with columns `fold_mean`, `fold_se`, `pooled` and index `["mse", "mae", "r2"]` named `metric`. - `fold_se` is the standard deviation of the per-fold scores (`ddof=1`) divided by `sqrt(k)`. `pooled` is each metric computed once on all OOF predictions. Use the sklearn definitions of MSE, MAE and R² (`1 - SS_res/SS_tot`). Shuffling is out of scope. Example: ```python folds = kfold_indices(10, 3) [val.tolist() for _, val in folds] # [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]] folds[1][0].tolist() # training indices are all remaining rows, ascending # [0, 1, 2, 3, 7, 8, 9] ``` ```hint Pooled versus per-fold Before writing the summary, check which of the three metrics are plain averages of per-sample errors. That tells you which pooled values you can sanity-check against a size-weighted average of the fold values. ``` ```hint Degenerate folds Ask what R² does when a validation fold has constant targets, for example a fold that holds a single sample. ``` ### Constraints & Assumptions - `X` is a numeric array of shape `(n_samples, n_features)` and `y` is a numeric vector of length `n_samples`. - `n_splits` satisfies `2 <= n_splits <= n_samples`; other values raise `ValueError`, as `KFold` does. - Rows are used in the order given. There is no shuffling, grouping or stratification. ### What a Strong Answer Covers - Fold construction that matches unshuffled `KFold` exactly, including uneven fold sizes and ascending training indices. - Scaler and model fitted on training rows only in every fold, with every sample predicted exactly once. - Correct per-fold MSE, MAE and R², the `ddof=1` standard error over k folds, and pooled metrics on the full OOF vector. - The exact output contract: dtypes, column names, and the index named `metric`. - Edge cases such as an invalid `n_splits` and a fold whose targets have zero variance. ### Follow-up Questions - Why can pooled R² differ from the mean of per-fold R²? - Is `fold_se` a trustworthy confidence measure? - How would you tune `alpha` without biasing these estimates?

Overview: Implement unshuffled k-fold splits, leak-free out-of-fold predictions from a scaled ridge regression, and a summary of MSE, MAE and R² per fold and on the pooled predictions. It tests careful cross-validation mechanics, fold standard errors, and why pooled and averaged R² can disagree.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement three functions that evaluate a ridge regression with k-fold cross-validation:

  • kfold_indices(n_samples, n_splits) builds unshuffled k-fold splits.
  • out_of_fold_predictions(X, y, n_splits, alpha=1.0) produces leak-free out-of-fold (OOF) predictions.
  • cross_validate_metrics(X, y, n_splits, alpha=1.0) summarizes MSE, MAE and R² both per fold and on the pooled OOF predictions.

Requirements:

  • kfold_indices uses contiguous validation blocks in input order, and the first n % k folds get one extra sample. It returns a list of (train_idx, val_idx) pairs that match unshuffled KFold .
  • In each fold, fit StandardScaler and Ridge(alpha) on the training fold only, then predict the validation fold.
  • out_of_fold_predictions returns (preds, fold_ids) : float64 predictions and the int64 fold index (0-based) of each sample.
  • cross_validate_metrics returns a float64 DataFrame with columns fold_mean , fold_se , pooled and index ["mse", "mae", "r2"] named metric .
  • fold_se is the standard deviation of the per-fold scores ( ddof=1 ) divided by sqrt(k) . pooled is each metric computed once on all OOF predictions.

Use the sklearn definitions of MSE, MAE and R² (1 - SS_res/SS_tot). Shuffling is out of scope.

Example:

folds = kfold_indices(10, 3)
[val.tolist() for _, val in folds]
# [[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]
folds[1][0].tolist()  # training indices are all remaining rows, ascending
# [0, 1, 2, 3, 7, 8, 9]

Constraints & Assumptions

  • X is a numeric array of shape (n_samples, n_features) and y is a numeric vector of length n_samples .
  • n_splits satisfies 2 <= n_splits <= n_samples ; other values raise ValueError , as KFold does.
  • Rows are used in the order given. There is no shuffling, grouping or stratification.

What a Strong Answer Covers Guidance

  • Fold construction that matches unshuffled KFold exactly, including uneven fold sizes and ascending training indices.
  • Scaler and model fitted on training rows only in every fold, with every sample predicted exactly once.
  • Correct per-fold MSE, MAE and R², the ddof=1 standard error over k folds, and pooled metrics on the full OOF vector.
  • The exact output contract: dtypes, column names, and the index named metric .
  • Edge cases such as an invalid n_splits and a fold whose targets have zero variance.

Follow-up Questions Guidance

  • Why can pooled R² differ from the mean of per-fold R²?
  • Is fold_se a trustworthy confidence measure?
  • How would you tune alpha without biasing these estimates?