Implement Dietterich's 5x2cv Paired t-Test to Compare Two Estimators

Quick Overview

Implement Dietterich's 5x2cv paired t-test to compare two scikit-learn estimators: build five seeded half-splits, collect paired score differences and compute the t statistic and two-sided p-value. It tests careful cross-validation design, use of clone, and why naive k-fold t-tests mislead.

Implement Dietterich's 5x2cv Paired t-Test to Compare Two Estimators

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement three functions that compare two scikit-learn estimators with Dietterich's 5x2cv paired t-test. `paired_t_test_5x2cv` returns `(t_stat, p_value)` as Python `float`s. ```python def five_by_two_splits(n_samples, random_state=0) -> list[tuple[np.ndarray, np.ndarray]]: ... def five_by_two_differences(estimator_a, estimator_b, X, y, random_state=0, scoring=None) -> np.ndarray: ... def paired_t_test_5x2cv(estimator_a, estimator_b, X, y, random_state=0, scoring=None) -> tuple[float, float]: ... ``` Requirements: - `five_by_two_splits(n_samples, random_state)`: create one `rng = np.random.default_rng(random_state)`. For each of 5 replications, set `perm = rng.permutation(n)`. Return a list of 5 tuples `(sorted(perm[:(n+1)//2]), sorted(perm[(n+1)//2:]))`. Raise `ValueError` if `n < 2`. - `five_by_two_differences` returns a `(5, 2)` array of `score_a - score_b`. Column 0 trains on the first half and tests on the second. Column 1 is the reverse. - `scoring(y_true, y_pred)` is higher-is-better. When it is `None`, use accuracy (`mean(y_true == y_pred)`). - Fit fresh copies of each estimator with `clone` for every fold. The estimators passed in must stay unfitted. - Compute the statistic and p-value with the formula below. Raise `ValueError` when the denominator is `0`. Formula: ```python d = differences # shape (5, 2) m_i = d[i].mean() s2_i = ((d[i] - m_i) ** 2).sum() t = d[0, 0] / sqrt(mean(s2_i over i)) p = 2 * scipy.stats.t.sf(abs(t), df=5) ``` ```hint Seeding the halves Think about where the random generator is created. The five permutations should differ from each other, and the whole run should repeat exactly for the same seed. ``` ```hint Checking the variance term Each row's `s2_i` depends only on the gap between its two differences. Work that out by hand for one row to test your implementation. ``` ### Constraints & Assumptions - `X` has `n_samples` rows and `y` has one label per row, with `n_samples >= 2`. - Both estimators follow the scikit-learn `fit` / `predict` API. - The design is fixed at 5 replications of 2-fold CV, so the reference distribution has 5 degrees of freedom. ### What a Strong Answer Covers - Split generation that follows the seeding, permutation, half-size and sorting rules exactly. - The `(5, 2)` difference layout, with fresh clones for every fit and accuracy as the default score. - The t statistic and two-sided p-value from the given formula, the zero-denominator error and plain `float` outputs. - Why the numerator is `d[0, 0]` and the reference is t with 5 degrees of freedom, and which assumptions that relies on. - The cost in model fits. ### Follow-up Questions - Why not just run a paired t-test on 10-fold CV scores? - The statistic uses only `d[0, 0]` in the numerator. How would you make it more stable? - How would you stratify the half-splits for imbalanced classification?

Overview: Implement Dietterich's 5x2cv paired t-test to compare two scikit-learn estimators: build five seeded half-splits, collect paired score differences and compute the t statistic and two-sided p-value. It tests careful cross-validation design, use of clone, and why naive k-fold t-tests mislead.

PracHub logo
General
Nov 24, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement three functions that compare two scikit-learn estimators with Dietterich's 5x2cv paired t-test. paired_t_test_5x2cv returns (t_stat, p_value) as Python floats.

def five_by_two_splits(n_samples, random_state=0) -> list[tuple[np.ndarray, np.ndarray]]: ...

def five_by_two_differences(estimator_a, estimator_b, X, y, random_state=0, scoring=None) -> np.ndarray: ...

def paired_t_test_5x2cv(estimator_a, estimator_b, X, y, random_state=0, scoring=None) -> tuple[float, float]: ...

Requirements:

  • five_by_two_splits(n_samples, random_state) : create one rng = np.random.default_rng(random_state) . For each of 5 replications, set perm = rng.permutation(n) . Return a list of 5 tuples (sorted(perm[:(n+1)//2]), sorted(perm[(n+1)//2:])) . Raise ValueError if n < 2 .
  • five_by_two_differences returns a (5, 2) array of score_a - score_b . Column 0 trains on the first half and tests on the second. Column 1 is the reverse.
  • scoring(y_true, y_pred) is higher-is-better. When it is None , use accuracy ( mean(y_true == y_pred) ).
  • Fit fresh copies of each estimator with clone for every fold. The estimators passed in must stay unfitted.
  • Compute the statistic and p-value with the formula below. Raise ValueError when the denominator is 0 .

Formula:

d = differences            # shape (5, 2)
m_i  = d[i].mean()
s2_i = ((d[i] - m_i) ** 2).sum()
t = d[0, 0] / sqrt(mean(s2_i over i))
p = 2 * scipy.stats.t.sf(abs(t), df=5)

Constraints & Assumptions

  • X has n_samples rows and y has one label per row, with n_samples >= 2 .
  • Both estimators follow the scikit-learn fit / predict API.
  • The design is fixed at 5 replications of 2-fold CV, so the reference distribution has 5 degrees of freedom.

What a Strong Answer Covers Guidance

  • Split generation that follows the seeding, permutation, half-size and sorting rules exactly.
  • The (5, 2) difference layout, with fresh clones for every fit and accuracy as the default score.
  • The t statistic and two-sided p-value from the given formula, the zero-denominator error and plain float outputs.
  • Why the numerator is d[0, 0] and the reference is t with 5 degrees of freedom, and which assumptions that relies on.
  • The cost in model fits.

Follow-up Questions Guidance

  • Why not just run a paired t-test on 10-fold CV scores?
  • The statistic uses only d[0, 0] in the numerator. How would you make it more stable?
  • How would you stratify the half-splits for imbalanced classification?