Imagine you have a dataset with two classes: 90% are class A and 10% are class B. You want to split the data into 5 folds for cross-validation.
Why is Stratified K-fold better than regular K-fold in this case?
Think about keeping the class proportions consistent in each fold.
Stratified K-fold keeps the class distribution in each fold similar to the original dataset. This helps the model learn and test on representative samples, especially when classes are imbalanced.
Given this code, what is the output of the printed train indices for the first fold?
from sklearn.model_selection import StratifiedKFold import numpy as np X = np.array([[i] for i in range(10)]) y = np.array([0,0,0,0,1,1,1,1,1,1]) skf = StratifiedKFold(n_splits=2, shuffle=False) for fold, (train_index, test_index) in enumerate(skf.split(X, y)): if fold == 0: print(train_index.tolist())
StratifiedKFold splits data keeping class proportions balanced in each fold.
StratifiedKFold with shuffle=False divides consecutive samples of each class into n_splits chunks. For fold 0, test indices are [0, 1, 4, 5, 6] (first 2 of class 0, first 3 of class 1), so train indices are [2, 3, 7, 8, 9].
You have a dataset with 95% of samples in class 0 and 5% in class 1. You want to evaluate a classification model's performance reliably.
Which cross-validation method is best to use?
Consider maintaining class proportions in each fold.
Stratified K-fold ensures each fold has similar class distribution, which is crucial for imbalanced datasets to avoid biased evaluation.
What is the effect of increasing the number of splits (n_splits) in StratifiedKFold on the training and validation sets?
Think about how splitting data into more folds affects the size of each fold.
Increasing n_splits makes validation sets smaller (n/k) and training sets larger ((k-1)n/k). This reduces bias from training on more data but increases variance from smaller validation sets.
Consider this code snippet:
from sklearn.model_selection import StratifiedKFold
import numpy as np
X = np.array([[i] for i in range(6)])
y = np.array([0, 0, 1, 1, 1, 1])
skf = StratifiedKFold(n_splits=3)
for train_index, test_index in skf.split(X, y):
print("TRAIN:", train_index, "TEST:", test_index)Running this code raises a ValueError. What is the cause?
Check the class distribution and the number of splits.
StratifiedKFold requires that each class has at least as many members as the number of splits. Here, class 0 has only 2 samples but n_splits=3, causing the error.
