Class-balanced model evaluation
Evaluating a binary or multiclass classifier with cross-validation.
Scikit-Learn · Class
StratifiedKFold generates classification cross-validation folds that preserve class proportions. It returns train/test indices and can optionally shuffle class samples reproducibly.
StratifiedKFold creates K-fold train/test splits while preserving approximately the class proportions in the target for binary or multiclass classification. It can optionally shuffle samples within each class before assigning them to folds, with random_state controlling that order.
class sklearn.model_selection.StratifiedKFold(n_splits=5, *, shuffle=False, random_state=None)| Name | Type | Description |
|---|---|---|
n_splits | int | Number of folds; must be at least 2. Default: 5. |
shuffle | bool | Whether to shuffle each class's samples before splitting into batches. Default: False. |
random_state | int, RandomState instance, or None | Controls index ordering when shuffle=True; accepts an int, RandomState instance, or None. Default: None. |
An iterator yielding train/test index arrays for each fold.
from sklearn.model_selection import StratifiedKFold
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for train_idx, test_idx in skf.split(X, y):
X_train, X_test = X[train_idx], X[test_idx]
y_train, y_test = y[train_idx], y[test_idx]
print(len(X_train), len(X_test), y_test.tolist())Creates five reproducible stratified splits and obtains train/test indices for each fold.
Evaluating a binary or multiclass classifier with cross-validation.
Working with imbalanced labels where ordinary folds could have different class mixes.
Testing models with randomized but repeatable fold assignments.
StratifiedKFold is a K-fold cross-validator for classification that preserves the percentage of samples from each class in every fold. It provides train and test indices rather than fitting an estimator itself.
Follow-up: How does it differ from KFold? KFold does not use class labels, so StratifiedKFold is preferable when class proportions must remain comparable across folds.
n_splits determines how many folds are created and must be at least 2. Each iteration uses one fold for testing and the remaining folds for training.
Follow-up: What constraint should be checked? The target must contain enough examples of each class for the requested split count.
shuffle controls whether each class's samples are shuffled before being divided into batches. When shuffle is True, random_state controls the ordering of indices and makes the resulting assignment reproducible when fixed.
Follow-up: What happens when shuffle is False? random_state should remain None because it does not affect the split.
KFoldStratifiedGroupKFoldcross_val_score