There is no universally “best” cross-validation method. Choose the splitter that reproduces how unseen data will arrive: independent rows, imbalanced classes, new entities, future dates, very small samples, or repeated random holdouts. This guide covers seven scikit-learn techniques, working Python examples, leakage-safe pipelines, and the difference between tuning and final evaluation.
What cross-validation estimates
Cross-validation repeatedly divides data into training and validation folds. A model is fitted on the training portion and scored on the held-out portion; every observation is used for validation according to the splitter’s rules. The mean score estimates performance on data drawn from a similar population, while the spread between scores shows sensitivity to the particular split.
A final test set is different. Keep it untouched until model choices, preprocessing decisions, and hyperparameters are fixed. Using the test set repeatedly turns it into another validation set and can make the reported performance optimistic.
In scikit-learn, a CV splitter creates train/test indices, a scoring function converts predictions into a metric, and tools such as GridSearchCV use scores to select hyperparameters. cross_val_score and cross_validate evaluate a specified estimator; they do not make a final production model automatically.
Recommended Free Tools
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
from sklearn.model_selection import cross_val_score
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(f"{scores.mean():.3f} ± {scores.std():.3f}")
print("Individual folds:", scores)
Current scikit-learn documentation describes these splitters and notes that ordinary K-Fold and Shuffle-Split assume independent, identically distributed observations; those assumptions are unsuitable for many time-series problems (cross-validation guide).
Quick decision guide
| Data situation | Recommended technique | Reason |
|---|---|---|
| Independent regression or balanced classification | K-Fold | General-purpose baseline |
| Classification where class proportions matter | Stratified K-Fold | Preserves class proportions approximately |
| Independent data with unstable random partitions | Repeated K-Fold | Shows sensitivity across multiple partitions |
| Very small independent dataset | LOOCV or K-Fold | LOOCV maximizes training size but can be noisy |
| Several rows per person, customer, device, or source | Group K-Fold | Prevents the same entity crossing folds |
| Ordered observations and future prediction | TimeSeriesSplit | Prevents training on future rows |
| Custom repeated holdout proportions | Shuffle-Split | Controls iteration count and test size |
| Hyperparameter selection plus unbiased comparison | Nested CV or a held-out test set | Separates selection from evaluation |
1. K-Fold cross-validation
K-Fold divides the data into k approximately equal folds. It trains on k − 1 folds and validates on the remaining fold, repeating until every fold has been held out. Five or 10 folds are common choices, but neither is universally optimal. More folds increase training-set size and computation; fewer folds reduce computation and may increase bias.
Use it for independent observations when row order, class proportions, and entity boundaries do not require a specialized design. KFold uses five splits by default in current documentation and does not shuffle unless requested (KFold API).
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold, cross_val_score
X, y = load_diabetes(return_X_y=True)
model = Ridge(alpha=1.0)
cv = KFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(
model, X, y, cv=cv, scoring="neg_mean_squared_error"
)
mse = -scores
print("Fold MSEs:", mse)
print(f"Mean MSE: {mse.mean():.3f}")
print(f"Standard deviation: {mse.std():.3f}")
- Plain K-Fold does not preserve class proportions.
- Without shuffling, results can depend on the original row order.
- Do not shuffle when row order encodes time, subject, or another dependency.
- Never let the same entity appear in both training and validation folds.
2. Stratified K-Fold
StratifiedKFold keeps each fold’s class proportions as close as possible to the overall classification dataset. It is especially useful when a minority class could otherwise be absent or severely underrepresented in a fold (StratifiedKFold API).
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=2000)
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
results = cross_validate(
model, X, y, cv=cv,
scoring=["accuracy", "precision", "recall", "roc_auc"]
)
for metric in ["test_accuracy", "test_precision", "test_recall", "test_roc_auc"]:
print(metric, results[metric].mean())
Stratification is a way to construct workable folds, not a cure for imbalance, dependence, or leakage. The least-populated class must have enough observations for the requested number of folds. For severe imbalance, select a metric such as balanced accuracy, precision, recall, F1, ROC AUC, or average precision according to the application; accuracy alone may hide poor minority-class performance. Stratified K-Fold also does not prevent rows from the same patient or customer crossing folds.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
3. Repeated K-Fold
Repeated K-Fold runs K-Fold several times with different randomized partitions. The extra scores reveal how much the estimate depends on one particular partition. For classification, use RepeatedStratifiedKFold instead of RepeatedKFold (RepeatedKFold API).
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RepeatedKFold, cross_val_score
X, y = load_diabetes(return_X_y=True)
model = RandomForestRegressor(
n_estimators=300, random_state=42, n_jobs=-1
)
cv = RepeatedKFold(n_splits=5, n_repeats=3, random_state=42)
scores = cross_val_score(
model, X, y, cv=cv,
scoring="neg_mean_absolute_error", n_jobs=-1
)
mae = -scores
print("Number of scores:", len(mae))
print(f"Mean MAE: {mae.mean():.3f}")
print(f"Standard deviation: {mae.std():.3f}")
from sklearn.model_selection import RepeatedStratifiedKFold
cv = RepeatedStratifiedKFold(
n_splits=5, n_repeats=3, random_state=42
)
Repeated CV improves the view of split sensitivity, not the validity of a flawed split. It does not fix entity leakage or future leakage, repeated scores are not all independent, and computation grows as k × repetitions.
4. Leave-One-Out cross-validation
Leave-One-Out (LOOCV) makes each individual observation the validation set once. With n observations, the estimator is fitted n times. Scikit-learn provides this iterator through LeaveOneOut (LeaveOneOut API).
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import LeaveOneOut, cross_val_score
X, y = load_diabetes(return_X_y=True)
scores = cross_val_score(
Ridge(alpha=1.0), X, y,
cv=LeaveOneOut(),
scoring="neg_mean_absolute_error",
n_jobs=-1
)
print(f"Mean LOOCV MAE: {(-scores).mean():.3f}")
LOOCV can be appropriate for a very small independent dataset when maximizing each training set matters. It is not automatically superior to five- or 10-fold CV: each validation score is based on one observation, the estimate can have high variance, and the computation may be prohibitive for expensive models. Leaving out one row also does not isolate a patient, user, or time period if related rows remain in training.
5. Group K-Fold
Group K-Fold keeps every observation from a group in the same fold. Groups can be patients, customers, households, users, devices, locations, documents, or image sources. This matches a deployment question in which the model must generalize to unseen entities rather than recognize entities it has already seen (GroupKFold API).
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
X = rng.normal(size=(120, 5))
y = rng.integers(0, 2, size=120)
groups = np.repeat(np.arange(20), 6) # six rows per subject
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=2000)
)
cv = GroupKFold(n_splits=5)
scores = cross_val_score(
model, X, y, groups=groups, cv=cv, scoring="roc_auc"
)
print(f"Group-CV ROC AUC: {scores.mean():.3f}")
The groups argument is essential. The number of distinct groups must be at least the number of folds. Because groups cannot be split, folds may contain different numbers of rows. Inspect group sizes and decide whether metrics should be weighted by rows or summarized at the group level.
For classification with both entity boundaries and class-balance concerns, StratifiedGroupKFold attempts to preserve class proportions while keeping groups intact (StratifiedGroupKFold API).
6. Time-Series Split
TimeSeriesSplit models the question “Can the model predict later observations using information available earlier?” Training data precede validation data, usually with an expanding window. This is fundamentally different from randomly shuffling rows.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
rng = np.random.default_rng(42)
n = 100
X = rng.normal(size=(n, 4))
y = np.arange(n) * 0.1 + rng.normal(size=n)
cv = TimeSeriesSplit(n_splits=5, test_size=10, gap=2)
scores = cross_val_score(
Ridge(alpha=1.0), X, y,
cv=cv, scoring="neg_mean_absolute_error"
)
print(f"Mean time-series MAE: {(-scores).mean():.3f}")
Sort records by time before splitting. Current scikit-learn supports:
n_splitsfor the number of temporal rounds.test_sizefor the validation-window length.gapfor observations excluded between training and validation.max_train_sizefor a rolling rather than expanding training window.
See the TimeSeriesSplit API. Use a gap when labels, rolling features, or delayed data overlap the boundary. A time-aware splitter cannot repair a feature that was calculated with future records: rolling averages, customer totals, interpolations, and target-derived aggregates must use only information available at prediction time.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
7. Shuffle-Split
ShuffleSplit repeatedly selects random training and validation subsets, giving explicit control over the number of iterations and test proportion. Unlike K-Fold, validation sets can overlap; some observations may be validated several times and others not at all (ShuffleSplit API).
Free tools Windows power users keep installed
One-click scans. No signup required.
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import ShuffleSplit, cross_val_score
X, y = load_diabetes(return_X_y=True)
model = RandomForestRegressor(
n_estimators=300, random_state=42, n_jobs=-1
)
cv = ShuffleSplit(n_splits=10, test_size=0.2, random_state=42)
scores = cross_val_score(
model, X, y, cv=cv,
scoring="neg_root_mean_squared_error", n_jobs=-1
)
print(f"Mean RMSE: {(-scores).mean():.3f}")
For classification, StratifiedShuffleSplit maintains class proportions. Use GroupShuffleSplit when groups, rather than rows, must remain separated. Shuffle-Split is invalid for ordinary time-dependent data and does not protect against duplicate entities by itself.
Prevent leakage with a Pipeline
Any learned transformation must be fitted on the training portion of each fold. Put imputation, scaling, feature selection, dimensionality reduction, target encoding, and the estimator in a scikit-learn pipeline (pipeline documentation).
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
("model", LogisticRegression(max_iter=2000))
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(
pipeline, X, y, cv=cv, scoring="roc_auc"
)
Fitting a scaler or imputer on the full dataset first lets validation information influence training. The same problem occurs when selecting features with all labels, applying SMOTE before splitting, target-encoding with validation labels, creating aggregates from future records, or allowing duplicate patients, customers, or documents across folds. For SMOTE and other resampling, use an imbalanced-learn pipeline so resampling occurs inside each training fold.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Hyperparameter tuning and nested cross-validation
When cross-validation is used to select hyperparameters, its score is a model-selection score, not an untouched final-test result.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
from sklearn.model_selection import GridSearchCV
param_grid = {"model__C": [0.01, 0.1, 1, 10]}
search = GridSearchCV(
estimator=pipeline,
param_grid=param_grid,
cv=cv,
scoring="roc_auc",
n_jobs=-1,
refit=True
)
search.fit(X, y)
print(search.best_params_)
print(search.best_score_)
For rigorous comparison of many models or hyperparameter settings, use nested CV: an inner loop selects the model and an outer loop estimates performance.
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(
pipeline, param_grid, cv=inner_cv,
scoring="roc_auc", n_jobs=-1
)
nested_scores = cross_val_score(
search, X, y, cv=outer_cv,
scoring="roc_auc", n_jobs=-1
)
print(f"Nested mean ROC AUC: {nested_scores.mean():.3f}")
Nested CV separates selection from evaluation (scikit-learn nested-CV example). A held-out test set is an alternative when data volume permits.
How to interpret and report results
Choose one metric that reflects the decision. Regression commonly uses MAE, MSE, RMSE, or R². Classification may use accuracy for balanced classes, or balanced accuracy, precision, recall, F1, ROC AUC, or average precision for imbalanced tasks. Probabilistic predictions may require log loss or Brier score.
from sklearn.model_selection import cross_validate
results = cross_validate(
pipeline, X, y, cv=cv,
scoring={"accuracy": "accuracy", "roc_auc": "roc_auc"},
return_train_score=True, n_jobs=-1
)
print(results["test_accuracy"].mean())
print(results["test_accuracy"].std())
Report the metric, number of folds and repetitions, shuffling and seed, grouping or temporal rules, pipeline contents, and whether the scores were used for tuning. For example: “Five-fold stratified CV ROC AUC: 0.912 ± 0.018.” Training scores are useful diagnostically but are not unbiased estimates of performance.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11High fold-to-fold variation can indicate a small sample, rare classes, unequal groups, outliers, distribution shift, or an unstable model. A higher mean is not automatically better if it comes from a less realistic splitter, a different metric, or a leaky pipeline.
Comparison and computational cost
| Technique | Typical scikit-learn class | Main benefit | Main risk | Approximate fits |
|---|---|---|---|---|
| K-Fold | KFold |
Simple independent-data baseline | No class or group protection | k |
| Stratified K-Fold | StratifiedKFold |
More workable class-balanced folds | Does not solve dependence or leakage | k |
| Repeated K-Fold | RepeatedKFold |
Measures split sensitivity | More computation; repeated scores overlap | k × repeats |
| Leave-One-Out | LeaveOneOut |
Nearly all rows used for each fit | Noisy single-observation scores | n |
| Group K-Fold | GroupKFold |
Unseen-entity evaluation | Unequal row counts between folds | k |
| Time-Series Split | TimeSeriesSplit |
Chronological validation | Feature timing can still leak | k |
| Shuffle-Split | ShuffleSplit |
Custom repeated holdouts | Overlapping test sets | iterations |
Grid search multiplies fits by the number of folds and parameter combinations; nested CV multiplies inner and outer folds again. Fix integer random_state values when shuffling is intentional and reproducibility matters, but remember that a repeatable invalid split is still invalid.
Common failure modes
- Too many stratified folds: reduce
n_splitsif the smallest class cannot populate every fold. - Too few groups:
GroupKFoldrequires at least as many distinct groups as folds. - Unequal groups: inspect group counts and consider group-level metrics if large groups dominate.
- Duplicate or near-duplicate records: deduplicate or assign duplicates to one group.
- Distribution shift: random CV may be inappropriate across periods, geographies, devices, or customer segments; design validation around deployment.
- Many experiments: repeated decisions against the same CV results can overfit the validation process; use nested CV, a final test set, or genuinely new data.
Final takeaway
Select the splitter from the data-generating process, not from a ranking of methods. Use K-Fold for independent data, stratification for class proportions, grouping for repeated entities, temporal splits for future prediction, repetition to study split sensitivity, LOOCV only with a clear small-data rationale, and Shuffle-Split for deliberate repeated holdouts. Keep every learned transformation inside the fold, report dispersion as well as the mean, and reserve a final test set—or an outer CV loop—for the performance estimate you intend to trust.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

