What you will be able to do
- Run k-fold cross-validation with cross_val_score and cross_validate, and choose their cv and scoring arguments
- Wrap preprocessing and model in one pipeline so every fold refits it from scratch
- Pick the splitter that matches the data: StratifiedKFold for imbalanced classes, a time-ordered splitter for temporal data, CrossValidator in Spark
- Use the mean cross-validated score as the objective in hyperparameter tuning, and count the fits a grid search with cross-validation runs
Key concept
Cross-validated score — One number built from k separate fits: each fold is held out once, a model trained on the other folds is scored on it, and the k scores are averaged. That average, not any single fold's score, is the estimate you report and optimise.
1.How a cross-validated score is computed
Cross-validation estimates how a model will do on data it has never seen. It does this by fitting the model several times, each time on a different part of the data, and scoring each fit on rows that fit never trained on. Why use rotating folds rather than one fixed holdout? That trade-off is covered in k-fold cross-validation vs a single train-validation split. This page is about running it.
In k-fold cross-validation the training data is cut into k folds. For each fold, a model is trained on the other k−1 folds, and the resulting model is validated on the remaining part of the data. Every row is held out exactly once, so with cv=5 you get five fits and five scores, and the reported figure is their mean.
Take a data scientist with only 500 labelled rows. Scoring the model on the rows it was trained on is the classic mistake: a model that memorised the labels would have a perfect score but would fail to predict anything useful on yet-unseen data. A single fixed 90/10 split avoids that mistake but stakes everything on 50 rows, and its result depends on which 50 rows the split happened to pick. Five rotating folds use all 500 rows for both training and scoring, and averaging five scores gives a steadier estimate than any one of them. On a dataset this small, cross-validation does not waste too much data, which is why it beats setting aside a fixed validation set here.
>>> from sklearn.model_selection import cross_val_score
>>> clf = svm.SVC(kernel='linear', C=1, random_state=42)
>>> scores = cross_val_score(clf, X, y, cv=5)
>>> scores
array([0.96, 1. , 0.96, 0.96, 1. ])Report the result as the mean together with its spread across folds. In the example above that comes to scores.mean() of 0.98 and scores.std() of 0.02. A small standard deviation means the folds agree. A large one means the score depends heavily on which rows land in the held-out fold.
Checkpoint 1 of 9· Fill the gap
This sample should fit and score the SVC five times: each fold is held out once and scored by a model trained on the other four. Which keyword argument completes the call?
>>> from sklearn.model_selection import cross_val_score
>>> clf = svm.SVC(kernel='linear', C=1, random_state=42)
>>> scores = cross_val_score(clf, X, y, ? =5)
>>> scores
array([0.96, 1. , 0.96, 0.96, 1. ])The cv argument of cross_val_score sets the number of folds. With cv=5 you get five fits and five held-out scores, and you report their mean (0.98) with the spread across folds (0.02). n_splits and test_size are real scikit-learn parameters, but they belong to splitter objects, not to cross_val_score.
Checkpoint 2 of 9· Exam question
A data scientist has only 500 labeled rows and wants a robust, low-variance estimate of a scikit-learn classifier's generalization performance without permanently setting aside data as a fixed holdout. Which approach best fits this goal?
Correct answer: A — Call cross_val_score with cv=5 so the model trains and scores across five rotating train/test partitions, then average the resulting scores.
- A.
cross_val_scorewithcv=5rotates which fifth of the data is held out each round, so every row is scored exactly once while still being trained on for the other folds. Averaging the five scores gives a lower-variance estimate than any single split, which is exactly what a small dataset benefits from. - B. A single 90/10 split still wastes a chunk of the already-small dataset on a one-time holdout, and the resulting score depends heavily on which rows happened to land in that 10%. With only 500 rows, that variance is large enough to make the estimate unreliable.
- C. Scoring a model on the exact rows it was trained on measures memorization rather than generalization, since the model has already seen the correct labels for every evaluated row. This produces an optimistically biased estimate that does not reflect performance on unseen data.
- D. A single bootstrap resample still yields one score from one particular sample of the data, so it does not reduce variance the way averaging across multiple rotating folds does. It also does not guarantee every original row gets evaluated when it was excluded from training.
2.The cv and scoring arguments of cross_val_score and cross_validate
The cv argument controls how the data is split. An integer sets the number of folds and picks the default splitter: KFold for regressors, StratifiedKFold for classifiers. You can also pass a splitter object such as ShuffleSplit(n_splits=5, test_size=0.3, random_state=0), or any iterable that yields (train, test) index arrays. This is how you plug in the data-specific splitters described further down. Databricks' own scikit-learn tuning notebooks start from the same import, from sklearn.model_selection import cross_val_score.
The scoring argument controls what is measured on each held-out fold. Left unset, it uses the estimator's own score method, which means accuracy for classifiers and R² for regressors. Pass a string such as 'f1_macro' or 'recall_macro' to use a named metric instead. Every scorer follows one convention: higher is better. Error metrics are therefore exposed in negated form, so mean squared error is 'neg_mean_squared_error' and its fold scores come back as negative numbers. A metric that needs extra parameters, such as fbeta_score with beta=2, must first be wrapped with make_scorer. A misspelled scoring name raises an InvalidParameterError.
cross_validate is the richer sibling. It accepts several metrics at once, as a list of names, a dict of name to scorer, or a callable that returns a dict. It returns a dict rather than an array, with fit_time, score_time and one test_<name> key per metric. Training-set scores are left out unless you set return_train_score=True, because computing them costs time. return_estimator=True keeps the model fitted on each fold, and return_indices=True keeps each fold's row indices.
>>> from sklearn.model_selection import cross_validate
>>> from sklearn.metrics import recall_score
>>> scoring = ['precision_macro', 'recall_macro']
>>> clf = svm.SVC(kernel='linear', C=1, random_state=0)
>>> scores = cross_validate(clf, X, y, scoring=scoring)
>>> sorted(scores.keys())
['fit_time', 'score_time', 'test_precision_macro', 'test_recall_macro']Checkpoint 3 of 9· Check yourself
A teammate needs to report how well a regressor will generalise. They run cross_val_predict with cv=5, then compute R² once on the full array of pooled predictions. What is wrong with this approach?
cross_val_predict returns each row's held-out prediction, but different fold models produced those predictions. Scoring them together is not a generalization estimate. Use the fold-averaged score from cross_val_score or cross_validate instead.
“cross_val_predict simply returns the labels (or probabilities) from several distinct models undistinguished. Thus, cross_val_predict is not an appropriate measure of generalization error.”Source: scikit-learn.org
Checkpoint 4 of 9· Check yourself
Two regressors are compared with cross_val_score(..., scoring='neg_mean_squared_error'). Model A's mean fold score is -12.4 and model B's is -30.1. Which reading is correct?
Every scorer follows the rule that higher is better, so error metrics come back negated. A higher (less negative) neg-MSE means a lower MSE, which makes model A the better model. A misspelled scoring name raises an InvalidParameterError. It does not return a fallback score.
“All scorer objects follow the convention that higher return values are better than lower return values.”Source: scikit-learn.org
3.Refitting the whole pipeline inside every fold
A preprocessing step learns parameters, such as a scaler's mean and variance. Those parameters must be learned from training rows only, which is why preprocessing and model belong in one pipeline, as explained in Fit preprocessing on training data only (leakage-safe Pipeline). Cross-validation applies the same rule fold by fold: each fold's "training rows" are the other k−1 folds.
When you pass a pipeline to cross_val_score, the whole pipeline is refitted inside every fold. In fold one the scaler learns its statistics from folds two to five, then transforms fold one using those statistics. In fold two it starts over. The held-out fold never contributes to any parameter that is used to score it. This applies to every learned transformation, including standardisation and feature selection.
>>> from sklearn.pipeline import make_pipeline
>>> clf = make_pipeline(preprocessing.StandardScaler(), svm.SVC(C=1))
>>> cross_val_score(clf, X, y, cv=cv)
array([0.977, 0.933, 0.955, 0.933, 0.977])The failure this prevents is easy to commit. Suppose you call StandardScaler().fit_transform(X) on the full dataset and then cross-validate only the SVC. Every fold is now scored on rows whose scaling was computed partly from those same rows, so the reported mean is an optimistic estimate of how the model generalises. The same pattern holds in Spark ML, where pipelines and cross-validation sit side by side in the same tuning toolkit: give the cross-validator the whole pipeline, not just the final model.
Checkpoint 5 of 9· Fill the gap
The cross-validated score should come from refitting the StandardScaler on each fold's training rows only, so the held-out fold never influences its own scaling. Which function goes in the blank?
>>> clf = ? (preprocessing.StandardScaler(), svm.SVC(C=1))
>>> cross_val_score(clf, X, y, cv=cv)
array([0.977, 0.933, 0.955, 0.933, 0.977])make_pipeline chains the scaler and the SVC into one estimator. When that pipeline goes to cross_val_score, the scaler is refitted on the k−1 training folds of every split, so no held-out fold leaks into its own preprocessing. make_scorer wraps a metric, and cross_validate and cross_val_predict are cross-validators, not ways to combine preprocessing with a model.
Source: scikit-learn.org4.Matching the splitter to the data
The default splitters assume that rows are independent and that any fold looks like any other. That assumption breaks in three common situations: rare classes, time order and repeated subjects. In each one, a plain split produces folds that misrepresent the data, even though the code runs without complaint.
>>> from sklearn.model_selection import StratifiedKFold, KFold
>>> import numpy as np
>>> X, y = np.ones((50, 1)), np.hstack(([0] * 45, [1] * 5))
>>> skf = StratifiedKFold(n_splits=3)
>>> for train, test in skf.split(X, y):
... print('train - {} | test - {}'.format(
... np.bincount(y[train]), np.bincount(y[test])))
train - [30 3] | test - [15 2]
train - [30 3] | test - [15 2]
train - [30 4] | test - [15 1]
>>> kf = KFold(n_splits=3)
>>> for train, test in kf.split(X, y):
... print('train - {} | test - {}'.format(
... np.bincount(y[train]), np.bincount(y[test])))
train - [28 5] | test - [17]
train - [28 5] | test - [17]
train - [34] | test - [11 5]For imbalanced classes, such as a 95/5 fraud or screening dataset, use StratifiedKFold. Each of its folds contains approximately the same percentage of each class as the full set. Without stratification, a fold with no positives makes metrics such as ROC AUC undefined, and the fit can even raise an exception. Plain KFold and ShuffleSplit cannot help, because neither looks at the labels. LeaveOneOut cannot help either: it holds out a single row per fit. Databricks AutoML applies the same idea to its own splits, using a stratified random split for classification so every class is represented in training, validation and test.
Time-ordered data needs a different splitter. KFold and ShuffleSplit assume independent rows. Shuffled folds would let a model train on next month and be scored on last month, so the estimate looks better than any real forecast could be. TimeSeriesSplit always trains on earlier rows and tests on the rows that follow, and each training set is a superset of the one before it. Databricks AutoML does the same for forecasting: it extends the training window chronologically and validates on later time points.
| Splitter | How it splits | Use it when |
|---|---|---|
| KFold | k folds of equal size, ignoring labels and groups | Regression or balanced classification on independent rows |
| StratifiedKFold | k folds, each keeping the overall class proportions | Classification, especially with a rare class |
| ShuffleSplit | A chosen number of independent random train/test splits | You want direct control over the number of iterations and the test fraction |
| GroupKFold | The same group never appears in both a training and a test fold | Several rows per patient, subject or device |
| TimeSeriesSplit | Train on earlier rows, test on the next block; training sets grow | Data collected over time |
| LeaveOneOut | n fits, each holding out a single row | Rarely: it is costly, and 5- or 10-fold is generally preferred |
Checkpoint 6 of 9· Check yourself
A team is building a model to forecast next month's demand from five years of monthly sales records. They want a cross-validated score that reflects how the model will perform on future months. Which splitter should they pass as cv?
Time-ordered data needs folds that train only on the past and test on what follows. TimeSeriesSplit does this, as does Databricks AutoML for forecasting. Shuffled or grouped folds can train on later months and score on earlier ones, which makes the estimate look better than any real forecast could be.
“This method incrementally extends the training dataset chronologically and performs validation on subsequent time points.”Source: docs.databricks.com
Checkpoint 7 of 9· Exam question
A binary classification dataset is severely imbalanced, with 95% negative and 5% positive labels. An engineer wants to run k-fold cross-validation while keeping the same 95/5 class ratio inside every fold. Which cross-validator should they use?
Correct answer: A — StratifiedKFold
- A.
StratifiedKFoldbuilds each fold so the proportion of each class matches the proportion in the full dataset, which keeps the rare positive class represented in every fold's train and test split. - B. Plain
KFoldsplits rows into folds without regard to class labels, so with a 95/5 imbalance it can easily produce folds where the minority class is underrepresented or missing entirely. - C.
ShuffleSplitgenerates random train/test partitions with possible overlap between iterations and does not account for class proportions, so it offers no built-in guarantee of preserving the 95/5 ratio. - D.
LeaveOneOutholds out a single row per iteration and trains on the rest, which is computationally expensive on larger data and does nothing to balance class proportions within folds.
5.Cross-validation as the objective inside hyperparameter tuning
Hyperparameter tuning compares candidate settings, and cross-validation provides the number each candidate is judged by. Each candidate is cross-validated in full, and its mean fold score becomes the value the search compares. A noisy score from a single split could favour a candidate that simply drew an easy validation set. A mean over folds makes that much less likely.
def objective(C):
# Create a support vector classifier model
clf = SVC(C=C)
# Use the cross-validation accuracy to compare the models' performance
accuracy = cross_val_score(clf, X, y).mean()
# Hyperopt tries to minimize the objective function. A higher accuracy value means a better model, so you must return the negative accuracy.
return {'loss': -accuracy, 'status': STATUS_OK}Two details in that objective are easy to get wrong. First, .mean() turns five fold scores into a single scalar, which is the only kind of value the optimiser can compare. Second, the sign is flipped. fmin minimises, so an objective that returned accuracy itself would steer the search toward the worst model. With an error metric such as 'neg_mean_squared_error', the scorer has already negated the error, so negate the mean again to get a positive loss. How fmin and search spaces work is covered in Hyperopt's fmin. Note that Hyperopt is not included in Databricks Runtime ML after 16.4 LTS ML.
scikit-learn's GridSearchCV builds the same loop for you. It takes a param_grid, a cv and a scoring argument, and cross-validates every combination in the grid. That makes the cost easy to work out: each candidate costs one fit per fold. Take a grid of 3 max_depth values × 4 n_estimators values. That is 12 candidates, and with cv=5 the search runs 12 × 5 = 60 fits. Counting 12 fits ignores the folds, while 15 or 20 adds the two dimensions instead of multiplying them. The full counting rules are in counting models in grid search with cross-validation.
On Spark DataFrames, the equivalent is Spark ML's CrossValidator, which is also available in the pyspark.ml.connect module used with Databricks Connect. It wraps an estimator or pipeline, a parameter grid and an evaluator, and runs the same per-fold refitting on the cluster. To track these tuning runs in MLflow, use PySpark ML autologging (mlflow.pyspark.ml.autolog()), which is enabled by default through Databricks Autologging.
Checkpoint 8 of 9· Check yourself
In a Hyperopt objective for a regressor, each candidate is scored with cross_val_score(reg, X, y, scoring='neg_mean_squared_error'). What should the objective return as 'loss' so that fmin moves toward the lowest error?
'neg_mean_squared_error' returns the negated error, so higher is better. fmin minimises, so negating the mean again gives a positive MSE that shrinks as models improve. Returning the raw mean would steer the search toward the largest error. The loss has to be a single scalar, and a misspelled scoring name raises an InvalidParameterError.
“like metrics.mean_squared_error, are available as ‘neg_mean_squared_error’ which return the negated value of the metric.”Source: scikit-learn.org
Checkpoint 9 of 9· Exam question
A team configures GridSearchCV with a param_grid covering 3 values for max_depth and 4 values for n_estimators, and sets cv=5. How many individual model fits does this search perform in total?
Correct answer: A — 60 model fits
- A. The grid has 3 x 4 = 12 unique hyperparameter combinations, and each combination is evaluated with a full 5-fold cross-validation, so 12 x 5 = 60 separate model fits are performed before the best combination is selected.
- B. 12 is only the count of unique hyperparameter combinations (3
max_depthvalues times 4n_estimatorsvalues); it ignores that each of those combinations is refit once per cross-validation fold. - C. 15 would follow from multiplying 3 combinations by 5 folds, but it drops the
n_estimatorsdimension entirely and undercounts the actual combination gridGridSearchCViterates over. - D. 20 would follow from multiplying 4 combinations by 5 folds, but it drops the
max_depthdimension entirely and undercounts the full 3 x 4 combination grid thatGridSearchCVactually searches.
Sources
(7)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Cross-validation provides a robust evaluation of a model's performance over different segments of time.”
↩︎ How a cross-validated score is computed“This method incrementally extends the training dataset chronologically and performs validation on subsequent time points.”
↩︎ Matching the splitter to the data - 2.https://scikit-learn.org/stable/modules/cross_validation.htmlSecondary source
“the resulting model is validated on the remaining part of the data”
↩︎ How a cross-validated score is computed“would have a perfect score but would fail to predict anything useful on yet-unseen data”
↩︎ How a cross-validated score is computed“the results can depend on a particular random choice for the pair of (train, validation) sets.”
↩︎ How a cross-validated score is computed“does not waste too much data (as is the case when fixing an arbitrary validation set)”
↩︎ How a cross-validated score is computed“It allows specifying multiple metrics for evaluation.”
↩︎ The cv and scoring arguments of cross_val_score and cross_validate“A Pipeline makes it easier to compose estimators, providing this behavior under cross-validation:”
↩︎ Refitting the whole pipeline inside every fold“each set contains approximately the same percentage of samples of each target class as the complete set”
↩︎ Matching the splitter to the data“classical cross-validation techniques such as KFold and ShuffleSplit assume the samples are independent and identically distributed”
↩︎ Matching the splitter to the data“successive training sets are supersets of those that come before them.”
↩︎ Matching the splitter to the data“GroupKFold is a variation of K-fold which ensures that the same group is not represented in both testing and training sets.”
↩︎ Matching the splitter to the data“As a general rule, most authors and empirical evidence suggest that 5 or 10-fold cross validation should be preferred to LOO.”
↩︎ Matching the splitter to the data“The performance measure reported by k-fold cross-validation is then the average of the values computed in the loop.”
↩︎ Key concept“Thus, cross_val_predict is not an appropriate measure of generalization error.”
↩︎ Exam trap 1“Note that KFold is not affected by classes or groups.”
↩︎ Exam trap 2“should be learnt from a training set and applied to held-out data for prediction”
↩︎ Exam trap 4“cross_val_score uses the KFold or StratifiedKFold strategies by default, the latter being used if the estimator derives from ClassifierMixin.”
↩︎ Prediction“cross_val_predict simply returns the labels (or probabilities) from several distinct models undistinguished. Thus, cross_val_predict is not an appropriate measure of generalization error.”
↩︎ Checkpoint“cross-validation splitting can generate train or validation folds without any occurrence of a particular class.”
↩︎ Prediction - 3.https://docs.databricks.com/aws/en/machine-learning/automl-hyperparam-tuning/hyperopt-spark-mlflow-integrationOfficial docs
“from sklearn.model_selection import cross_val_score”
↩︎ The cv and scoring arguments of cross_val_score and cross_validate“Use the cross-validation accuracy to compare the models' performance”
↩︎ Cross-validation as the objective inside hyperparameter tuning“Hyperopt is not included in Databricks Runtime for Machine Learning after 16.4 LTS ML.”
↩︎ Cross-validation as the objective inside hyperparameter tuning“Hyperopt tries to minimize the objective function. A higher accuracy value means a better model, so you must return the negative accuracy.”
↩︎ Exam trap 3 - 4.https://scikit-learn.org/stable/modules/model_evaluation.htmlSecondary source
“All scorer objects follow the convention that higher return values are better than lower return values.”
↩︎ The cv and scoring arguments of cross_val_score and cross_validate“take a scoring parameter that controls what metric they apply to the estimators evaluated.”
↩︎ Cross-validation as the objective inside hyperparameter tuning“like metrics.mean_squared_error, are available as ‘neg_mean_squared_error’ which return the negated value of the metric.”
↩︎ Checkpoint - 5.https://docs.databricks.com/aws/en/machine-learning/train-model/distributed-training/distributed-ml-for-spark-connectOfficial docs
“The pyspark.ml.connect module consists of common learning algorithms and utilities, including classification, feature transformers, ML pipelines, and cross validation.”
↩︎ Refitting the whole pipeline inside every fold“Model tuning: pyspark.ml.connect.tuning.CrossValidator”
↩︎ Cross-validation as the objective inside hyperparameter tuning - 6.
“For classification, a stratified random split ensures that each class is adequately represented in the training, validation, and test sets.”
↩︎ Matching the splitter to the data - 7.
“Instead, use MLflow PySpark ML autologging by calling mlflow.pyspark.ml.autolog(), which is enabled by default with Databricks Autologging.”
↩︎ Cross-validation as the objective inside hyperparameter tuning