What is cross-validation?

In short
Cross-validation is a way to test a machine learning model on several different slices of your data. The data is split into k parts, the model is trained on all but one part, and tested on the part left out. Repeating this gives a more reliable estimate of how well the model will handle new data.
Cross-validation is a method for checking how well a model will work on data it has never seen. It helps you avoid being fooled by a model that only memorized its training examples.
Why we need it
If you train a model and test it on the same data, the score can look excellent. The model may simply repeat the answers it has already seen. This problem is called overfitting. A model that overfits performs well on the data it learned from and poorly on anything new.
The usual fix is to hold back part of your data as a test set. The model never sees this part during training, so its score on that part is a fairer estimate. The documentation shows this with the classic iris flower dataset, where 40 percent of the samples are held out for testing.
There is a catch. If you keep trying different settings and pick whichever scores best on the test set, knowledge of that test set leaks into your choices. Settings such as the C value of a support vector machine are called hyperparameters, and tuning them this way can make the test score misleading.
How it works
One answer is a separate validation set. You train on one part, tune on a second part, and keep a third part for the final check. The drawback is that three splits leave fewer samples for learning, and the result can depend on which random samples land in each split.
Cross-validation solves this by reusing the data. In the basic approach, called k-fold cross-validation, the training data is divided into k smaller groups, called folds. For each fold, the model trains on the other k minus one folds and is scored on the fold it left out. The final score is the average of these k results.
You still keep a test set for the final evaluation. Cross-validation only replaces the validation set. Because every sample is used for both training and scoring at different times, very small datasets get more value from it.
A simple example
In scikit-learn, the cross_val_score helper runs this loop for you. You pass in the model, the data and the number of folds:
from sklearn.model_selection import cross_val_score
from sklearn import datasets, svm
X, y = datasets.load_iris(return_X_y=True)
clf = svm.SVC(kernel='linear', C=1, random_state=42)
scores = cross_val_score(clf, X, y, cv=5)
print(scores.mean(), scores.std())
The result is one score per fold. The mean tells you the typical performance, and the standard deviation tells you how much it varies between folds. In the documentation example the mean is 0.98 with a standard deviation of 0.02.
If you need more than one metric, the cross_validate function accepts several scorers and also returns fit and score times. The docs also note that preprocessing steps such as standardization should be learned from the training part of each fold only. A Pipeline helps with this, because it keeps the preprocessing inside the cross-validation loop. You can read more in our guide to machine learning pipelines once you are comfortable with the basics.
Common mistakes
The most frequent mistake is fitting a scaler or feature selector on the full dataset before splitting. Information from the held-out folds then leaks into training. Put these steps inside a pipeline so they are refitted for each fold.
Another mistake is using cross_val_predict as if it measured generalization. The documentation warns that its output combines predictions from several different models, so it is not the same as the averaged score from cross_val_score. Use it to inspect predictions, not to report performance.
Finally, remember that cross-validation costs time. Each fold trains a new model, so with large datasets or slow models the process can take a long while.
Alternatives
The default splitter is KFold, or StratifiedKFold for classifiers. The documentation also mentions ShuffleSplit, which draws random train and test splits. You can pass any of these as the cv argument, or pass your own iterable of index arrays for full control.
For small datasets where you need very careful estimates, look at the other strategies in the scikit-learn guide. For a quick first check, a single train and test split with train_test_split is often enough.
FAQ
How many folds should I use?
Five and ten are common choices. More folds use more data for each training run but cost more time. The right number depends on your dataset size and how long a single training run takes.
Is cross-validation the same as a test set?
No. Cross-validation estimates performance during model development, using the training data. A separate test set should still be held out and used only for the final evaluation.
Why does the score change between folds?
Each fold contains different samples, so the model is trained and tested on slightly different data. The spread between fold scores, shown by the standard deviation, tells you how stable the model is.
Can I use cross-validation with any model?
Yes, as long as the model follows the scikit-learn estimator interface. The helpers take the estimator, the data and a cv setting, and handle the splitting and scoring for you.
Sources
This page is based on the official documentation below. Read it for full detail.
Cross-validation — official documentation ↗Cross-validation in the news
Anthropic Ports Claude API From Python to Rust Using Production Traffic as the Test
Anthropic says it rewrote its Messages API from Python to Rust without downtime, cutting CPU use by about 70%. The main challenge was verifying the new code, which it did by comparing live traffic against the old service.
