TATECHATLAS
◎ English
Math & models / Tip

How random_state Type Affects Cross-Validation Reproducibility and Model Comparison in scikit-learn

Passing an integer to a CV splitter guarantees identical folds across estimator comparisons, while a RandomState instance causes different splits on each split() call, making fold-wise scores non-comparable.

On this page

For estimators, pass a RandomState instance or None to let the RNG evolve across folds and avoid lucky-seed bias. For CV splitters, pass an integer so that repeated calls to split() produce identical folds, enabling valid fold-to-fold comparison across different estimators.

Context and Recommendation

Many scikit-learn estimators and cross-validation splitters accept a random_state parameter that controls their internal randomness. The type of value passed to this parameter has non-obvious consequences for reproducibility, especially during cross-validation. The scikit-learn documentation recommends passing a RandomState instance or None when creating randomized estimators, and passing an integer when creating CV splitters. This combination balances two goals: robustness of individual estimator evaluation against specific seed luck, and comparability of fold-wise scores across different models.

The key insight is that the semantics of random_state differ between estimators and splitters. For an estimator, the random_state governs internal initialization (random forest tree bootstraps, SGD weight initialization). For a CV splitter, it governs which data points land in which fold. Because these two roles interact during cross-validation, choosing the wrong type for either parameter can silently invalidate your experimental conclusions.

Reasoning and Trade-offs

When an integer is passed to an estimator's random_state, scikit-learn resets the internal RNG to that seed at the beginning of every fit call. This means each fold sees the identical random initialization. While this produces deterministic results, it introduces a subtle risk: if that particular seed happens to produce a favorable initialization, the cross-validation mean score will be optimistically biased. The estimator appears robust across folds, but it is only robust to that one lucky seed.

When a RandomState instance or None is passed to an estimator, the RNG advances between fit calls. Each fold receives a different random initialization. This tests whether the estimator is genuinely robust to its own randomness, not just to one fixed seed. The trade-off is slightly higher variance in the reported mean score, and the fact that the shared instance creates interdependencies between objects that reference it.

For CV splitters the situation is reversed. An integer seed guarantees that every call to split() returns the same fold assignments. A RandomState instance causes each call to split() to produce different folds because the underlying RNG state advances. This becomes critical when cross_val_score or GridSearchCV internally calls split() once per estimator evaluation. If the splitter uses a RandomState instance, the first estimator gets one set of folds and the second estimator gets a different set, making fold-wise comparisons meaningless.

The scikit-learn documentation states directly: for comparable fold-to-fold results in all scenarios, one should pass an integer to the CV splitter. It also notes that while fold-to-fold comparison is not advisable with RandomState instances, average scores can still support the conclusion that one estimator outperforms another, provided enough folds and data are used.

Concrete Illustration

The following example isolates the splitter behavior by using two deterministic estimators (LinearDiscriminantAnalysis and GaussianNB). Because these models have no internal randomness, any difference in fold-wise scores between them must come from the splitter producing different folds. With a RandomState instance for the splitter, the two estimators are evaluated on different data partitions, so comparing their per-fold scores is invalid. With an integer, both estimators see identical folds, and fold-wise comparison becomes meaningful.

The corrected approach uses random_state=0 (an integer) for KFold. Both cross_val_score calls then receive the same five fold assignments, and the resulting score arrays can be compared element by element.

For a fully realistic pipeline where estimators are also randomized (for example, SGDClassifier), the recommendation is to pass a RandomState instance to the estimator's random_state while keeping the splitter's random_state as an integer. This gives robust estimator evaluation and comparable folds simultaneously.

import numpy as np
from sklearn.model_selection import KFold, cross_val_score
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import make_classification

X, y = make_classification(n_samples=100, n_features=20, random_state=42)

# PITFALL: RandomState instance for the splitter
rng = np.random.RandomState(0)
cv_bad = KFold(n_splits=5, shuffle=True, random_state=rng)

lda = LinearDiscriminantAnalysis()
nb = GaussianNB()

# cross_val_score calls cv.split() internally once per estimator.
# With a RandomState instance, the second call produces different folds.
scores_lda_bad = cross_val_score(lda, X, y, cv=cv_bad)
scores_nb_bad = cross_val_score(nb, X, y, cv=cv_bad)

print("Bad Comparison (Different Splits):")
print(f"LDA: {scores_lda_bad}")
print(f"NB:  {scores_nb_bad}")

# FIX: Integer seed for the splitter ensures identical folds
cv_good = KFold(n_splits=5, shuffle=True, random_state=0)

scores_lda_good = cross_val_score(lda, X, y, cv=cv_good)
scores_nb_good = cross_val_score(nb, X, y, cv=cv_good)

print("\nGood Comparison (Identical Splits):")
print(f"LDA: {scores_lda_good}")
print(f"NB:  {scores_nb_good}")

# Verify folds are identical by inspecting split() output directly
folds_lda = list(cv_good.split(X))
folds_nb = list(cv_good.split(X))
print("\nFolds identical:", folds_lda == folds_nb)

Applicability Limits

These guidelines apply only to randomized components. Deterministic estimators such as LogisticRegression with solver='lbfgs' (converged) or LinearDiscriminantAnalysis ignore random_state entirely. Similarly, a KFold splitter without shuffle=True produces deterministic folds regardless of the random_state value.

Using a shared RandomState instance across multiple estimator objects creates hidden coupling. If two estimators reference the same instance, fitting one advances the RNG and changes the initialization the other will receive on the next fit. This interdependency complicates debugging and makes it harder to reason about individual estimator behavior in isolation.

The recommendation to use RandomState for estimators targets robustness against seed-specific luck. It does not eliminate the need for sufficient folds and sample size. With very few folds, even a RandomState-based evaluation may not reveal instability. The scikit-learn documentation cautions that average scores with RandomState splitters can still support model ranking, but fold-wise comparisons should be avoided in that configuration.

For hyperparameter search utilities such as GridSearchCV and RandomizedSearchCV, a single call to search.fit invokes cv.split exactly once, so fold-wise comparison within that call remains valid even with a RandomState splitter. The problem arises only across separate calls to search.fit or cross_val_score.

Applicability

  • Does your comparison require fold-wise (per-fold) score alignment between two or more estimators? If yes, the CV splitter must use an integer random_state.
  • Are your estimators genuinely randomized (SGD, RandomForest, KMeans with n_init>1)? If not, the RandomState-vs-integer distinction for estimator random_state has no effect.
  • Do you share a single RandomState instance across multiple estimator objects in the same pipeline? If yes, be aware of hidden interdependencies during debugging.
  • Is your goal final production reproducibility across script re-runs? If yes, replace all None values with fixed integers, since None consumes system entropy and is not reproducible.

This guidance addresses the interaction between random_state type and cross-validation comparability. It does not cover the effect of random_state on hyperparameter tuning convergence, on distributed computing backends that may reset RNG state differently, or on NumPy global seed interactions. The recommendations assume scikit-learn's standard single-process execution model and may need adjustment for joblib parallel backends that clone estimators.

Sources

  1. scikit-learn: learning curves ↗
  2. scikit-learn: common pitfalls ↗
Back to top ↑