Controlling Randomness with random_state in Scikit-Learn
Learn how different types of random_state affect the reproducibility of fit and split calls and the statistical robustness of cross-validation results.
On this page
The short answer
The random_state parameter controls the internal Random Number Generator (RNG) of scikit-learn objects. Passing an integer resets the RNG at the start of every fit or split call, ensuring identical results across repeated calls. In contrast, passing None or a RandomState instance allows the RNG to evolve, producing different results on each call. For cross-validation, using a RandomState instance in estimators ensures that each fold is trained with a different random seed, increasing robustness. Conversely, using an integer in CV splitters ensures that the data is partitioned identically across different model comparisons, preventing the overestimation of performance variance.
The Role of random_state in Scikit-Learn
In scikit-learn, many objects are inherently stochastic, such as RandomForestClassifier or KFold. The random_state parameter is the primary mechanism used to control this randomness. It determines how the internal random number generator is initialized and updated, which is critical for debugging, auditing, and scientific reporting.
Practical tip
For a production-ready pipeline that is both reproducible and robust: declare a single RandomState instance at the top of your script and pass it to all estimators and splitters. This avoids the unpredictability of None while preventing the 'frozen' randomness of integers during cross-validation folds.
Behavior of Integer random_state
When an integer is passed to random_state, the RNG is reset to the same initial state every time the fit or split method is called. This means that multiple calls to the same method on the same object will always yield identical results. This behavior is essential for creating exact clones of models and ensuring that a specific experiment can be replicated exactly by another researcher.
Behavior of None and RandomState Instances
If random_state is set to None (the default) or a RandomState instance is provided, the fit and split methods will produce different results on each subsequent call. While None tells scikit-learn to use the global numpy RNG, a RandomState instance is a stateful object. As the object is used, its internal state evolves, meaning the succession of calls explores different sources of entropy rather than restarting from a fixed point.
Impact on Estimator Fit and Cross-Validation
The choice of random_state type significantly alters cross-validation (CV) procedures. If an integer is used in an estimator, the RNG is reset for every fold, meaning the estimator uses the same random sequence for every training set. Using a RandomState instance instead allows the RNG to vary across folds. This is generally preferred because it ensures the CV results are robust against the specific randomness of the estimator.
Impact on CV Splitters and Data Splits
Randomized CV splitters like KFold behave similarly. If a RandomState instance is passed, calling split multiple times yields different data partitions. If you compare two different estimators by calling split repeatedly, you may mistakenly attribute performance differences to the models when they are actually caused by the varying data splits. To ensure a fair, fold-to-fold comparison between different models, an integer should be passed to the splitter.
from sklearn.model_selection import KFold
import numpy as np
X = np.arange(10)
y = np.arange(10)
# Using RandomState instance: splits change on second call
rng = np.random.RandomState(0)
cv = KFold(n_splits=2, shuffle=True, random_state=rng)
# First call
first_split = list(cv.split(X, y))
# Second call yields different indices
second_split = list(cv.split(X, y))
print(f"Splits are different: {first_split != second_split}")
# Illustrative output: Splits are different: TrueThe Cloning Side Effect
The scikit-learn clone function behaves differently based on the random_state type. If an integer is used, the cloned estimator is an exact copy. However, if a RandomState instance is passed, the original and the clone share the same RNG object. Consequently, they are statistically interdependent; calling fit on the original estimator consumes the RNG state, which directly affects the subsequent fit call on the clone.
Ensuring Global Reproducibility
To achieve full reproducibility across different program executions, all instances of random_state=None must be removed. The most effective strategy is to define a single RandomState instance or integer at the top of the program and pass it to every estimator, splitter, and data transformation function. This ensures that the entire pipeline remains deterministic.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_classification
# Define global seed
seed = 42
# Use the same seed across all random components
X, y = make_classification(random_state=seed)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=seed)
rf = RandomForestClassifier(random_state=seed)
rf.fit(X_train, y_train)
print(f"Score: {rf.score(X_test, y_test):.2f}")
# Illustrative output: Score: 0.84Summary of Best Practices for Robustness
For optimal results, use RandomState instances (or None) for estimators to ensure that cross-validation captures the model's sensitivity to randomness. For CV splitters, use integers to ensure that all models are evaluated on the exact same data partitions. This combination maximizes the statistical validity of the comparison while maintaining the ability to reproduce the results.
Things to check
- Verify that integer random_state is described as resetting the RNG on every call.
- Confirm that RandomState instances are identified as stateful and producing different results on repeated calls.
- Ensure the distinction between estimator robustness (RandomState) and splitter consistency (Integer) is clear.
- Check that the interdependence of clones sharing a RandomState instance is explained.
- Verify that the recommended strategy for global reproducibility involves removing all None values.
Where this applies
This guide applies specifically to scikit-learn objects that accept a random_state parameter; it does not cover external libraries or non-randomized estimators.