Cross-validation helps us estimate how well our model will generalise to new data by the following measures:
Dividing the training data into multiple subsets (folds).
Training and testing/validating the model on different combinations of these folds.
Averaging the results to get a more reliable performance estimate.
It ensures the model generalizes well, prevents overfitting, and provides a more accurate estimate of performance than a single training-test split.
Here we have a 5-fold cross validation (cv=5 below) and we see 5 different scores for each fold with the average accuracy of around 96%.
from sklearn.model_selection import cross_val_scorecv_scores = cross_val_score(RandomForestClassifier( n_estimators=300, # number of trees — more is generally better (diminishing returns) max_depth=2, # maximum depth per tree — limits overfitting min_samples_leaf=10, # each leaf must contain at least 10 peguins max_features="sqrt", # each split considers sqrt(p) features — standard for classification class_weight="balanced", # account for 118/97/51 class imbalance random_state=1, # reproducible results n_jobs=-1 ), train_X, train_y, cv=5, scoring='accuracy')print(f"Cross-validation scores: {cv_scores}")print(f"Mean CV accuracy: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
This highlights the limitations of our small dataset (300 samples for training and 33 for testing) generalising to new data given the varying results between 92% and 100% for accuracy across the 5 subsets.
Fitting 5 folds for each of 9 candidates, totalling 45 fits
Best parameters: {'max_depth': 5, 'min_samples_leaf': 10, 'n_estimators': 200}
Best GridSearchCV score: 0.970