Implement k-fold and hold-out splits and compare train, hold-out and CV accuracy

Quick Overview

Implement contiguous k-fold and seeded hold-out index splits in NumPy, then compare a decision tree's training, hold-out and cross-validated accuracy. It tests exact split semantics, input validation, and why training accuracy overstates how well an unpruned tree generalizes.

Implement k-fold and hold-out splits and compare train, hold-out and CV accuracy

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement three functions that compare a model's accuracy on the data it was trained on, on one random hold-out split, and averaged over k folds. The model is always `DecisionTreeClassifier(random_state=0)` from scikit-learn, fit fresh for every split. `X` is a 2-D feature array with one row per sample and `y` holds the class labels. - `kfold_indices(n_samples, n_splits=5)` returns a list of `(train_idx, val_idx)` pairs. The validation folds are contiguous blocks in input order. Each fold has `n_samples // n_splits` samples and the first `n_samples % n_splits` folds get one extra, which matches unshuffled `KFold`. A fold's training indices are all the other samples. Raise `ValueError` when `n_splits` is outside `[2, n_samples]`. - `holdout_indices(n_samples, test_size=0.25, seed=0)` returns `(train_idx, test_idx)`. Compute `perm = np.random.default_rng(seed).permutation(n_samples)`, take the first `ceil(test_size * n_samples)` entries as the test set and the rest as the training set, and sort both ascending. Raise `ValueError` when either set would be empty. - `compare_scores(X, y, n_splits=5, test_size=0.25, seed=0)` returns a pandas `DataFrame` with columns `["method", "score"]`, rows `train`, `holdout`, `cv` in that order, and `score` of dtype `float64`. The train score fits on all of `X` and scores on all of `X`. The hold-out score fits on the hold-out training split and scores on its test split. The CV score is the unweighted mean of the per-fold validation accuracies. ```python kfold_indices(37, 5) # validation fold sizes: [8, 8, 7, 7, 7] holdout_indices(41, test_size=0.3) # len(test) == 13, len(train) == 28 compare_scores(X, y) # method score # 0 train 1.000 # 1 holdout below 1.0 # 2 cv below 1.0 ``` In the last call, the rows of `X` are all distinct and `y` has some label noise. The unpruned tree memorizes the noise, so its training accuracy is 1.0 while both held-out estimates come out lower. ```hint Fold boundaries Compute the list of fold sizes before slicing anything, then move a start offset through `np.arange(n_samples)`. Each of the three scores needs its own freshly fit tree. ``` ### Constraints & Assumptions - `X` has shape `(n_samples, n_features)` and `y` has length `n_samples`. Treat both as NumPy arrays (convert with `np.asarray`). - `2 <= n_splits <= n_samples`. Any other value raises `ValueError`. - `test_size` is a fraction between 0 and 1. A value that makes `ceil(test_size * n_samples)` equal to 0 or to `n_samples` raises `ValueError`. - K-fold does no shuffling and nothing is stratified. The only randomness is the seeded permutation in the hold-out split. ### What a Strong Answer Covers - Fold sizes and boundaries that match the spec exactly, including where the `n_samples % n_splits` extra samples go and the `ValueError` range. - A hold-out split that uses the given generator call, rounds the test count up, sorts both index arrays, and rejects an empty side. - A new model fit on only the training part of each split and scored on the part it did not see, with the CV score taken as the plain mean of fold accuracies. - The returned `DataFrame` with the exact columns, row order and `float64` dtype. - Why the training score is optimistic for an unpruned tree, and why the hold-out and CV numbers differ from each other. ### Follow-up Questions - Why is contiguous, unshuffled k-fold risky when the rows are ordered by class, time or source, and what would you use instead? - Why prefer the k-fold estimate over a single hold-out score on a small dataset? - When can an unpruned decision tree score below 1.0 on its own training data? - Which tree settings would shrink the gap between training and validation accuracy, and how would you choose them without tuning on the data you report?

Overview: Implement contiguous k-fold and seeded hold-out index splits in NumPy, then compare a decision tree's training, hold-out and cross-validated accuracy. It tests exact split semantics, input validation, and why training accuracy overstates how well an unpruned tree generalizes.

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

Implement three functions that compare a model's accuracy on the data it was trained on, on one random hold-out split, and averaged over k folds. The model is always DecisionTreeClassifier(random_state=0) from scikit-learn, fit fresh for every split. X is a 2-D feature array with one row per sample and y holds the class labels.

  • kfold_indices(n_samples, n_splits=5) returns a list of (train_idx, val_idx) pairs. The validation folds are contiguous blocks in input order. Each fold has n_samples // n_splits samples and the first n_samples % n_splits folds get one extra, which matches unshuffled KFold . A fold's training indices are all the other samples. Raise ValueError when n_splits is outside [2, n_samples] .
  • holdout_indices(n_samples, test_size=0.25, seed=0) returns (train_idx, test_idx) . Compute perm = np.random.default_rng(seed).permutation(n_samples) , take the first ceil(test_size * n_samples) entries as the test set and the rest as the training set, and sort both ascending. Raise ValueError when either set would be empty.
  • compare_scores(X, y, n_splits=5, test_size=0.25, seed=0) returns a pandas DataFrame with columns ["method", "score"] , rows train , holdout , cv in that order, and score of dtype float64 . The train score fits on all of X and scores on all of X . The hold-out score fits on the hold-out training split and scores on its test split. The CV score is the unweighted mean of the per-fold validation accuracies.
kfold_indices(37, 5)                 # validation fold sizes: [8, 8, 7, 7, 7]
holdout_indices(41, test_size=0.3)   # len(test) == 13, len(train) == 28

compare_scores(X, y)
#     method  score
# 0    train  1.000
# 1  holdout  below 1.0
# 2       cv  below 1.0

In the last call, the rows of X are all distinct and y has some label noise. The unpruned tree memorizes the noise, so its training accuracy is 1.0 while both held-out estimates come out lower.

Constraints & Assumptions

  • X has shape (n_samples, n_features) and y has length n_samples . Treat both as NumPy arrays (convert with np.asarray ).
  • 2 <= n_splits <= n_samples . Any other value raises ValueError .
  • test_size is a fraction between 0 and 1. A value that makes ceil(test_size * n_samples) equal to 0 or to n_samples raises ValueError .
  • K-fold does no shuffling and nothing is stratified. The only randomness is the seeded permutation in the hold-out split.

What a Strong Answer Covers Guidance

  • Fold sizes and boundaries that match the spec exactly, including where the n_samples % n_splits extra samples go and the ValueError range.
  • A hold-out split that uses the given generator call, rounds the test count up, sorts both index arrays, and rejects an empty side.
  • A new model fit on only the training part of each split and scored on the part it did not see, with the CV score taken as the plain mean of fold accuracies.
  • The returned DataFrame with the exact columns, row order and float64 dtype.
  • Why the training score is optimistic for an unpruned tree, and why the hold-out and CV numbers differ from each other.

Follow-up Questions Guidance

  • Why is contiguous, unshuffled k-fold risky when the rows are ordered by class, time or source, and what would you use instead?
  • Why prefer the k-fold estimate over a single hold-out score on a small dataset?
  • When can an unpruned decision tree score below 1.0 on its own training data?
  • Which tree settings would shrink the gap between training and validation accuracy, and how would you choose them without tuning on the data you report?