Cross validation: why a single split misleads you and how cross validation fixes it
A single train-test split misleads you because the score depends on which rows happened to land on each side: a lucky split inflates the metric and an unlucky one drags it down, even when the model is identical. Cross validation fixes this by training and evaluating the model several times on different parts of the data, then summarizing performance with the average and the spread across rounds. The Python for Data Science and Analytics course covers cross validation inside its machine learning content, from zero to advanced.
Why does a single train-test split mislead you?
When you split the data into train and test only once, the number you get at the end is the product of one specific arrangement of rows. Change the random seed and the metric moves, sometimes a lot, without anything changing in the model itself.
On small datasets the effect gets worse. If the test set holds few rows, every example carries a lot of weight, and a handful of easy or hard cases shifts the whole metric. You end up comparing models on noise.
There is a quieter mistake too: tuning hyperparameters while watching the test set. After enough rounds of trial and error, the test set stops being an honest measurement and becomes part of training. The model looks better than it is.
- The metric swings when you change the random seed.
- The test set is small relative to the total number of rows.
- You chose the model or the hyperparameters by looking at the test score.
- Classes are imbalanced and the split left one of them under-represented.
How does cross validation fix the single-split problem?
In k-fold cross validation the data is split into k parts of similar size. The model is trained k times; on each round a different part is held out for validation while the other k-1 parts train. By the end, every row has been used for validation exactly once.
The output is not a single number but a distribution of k scores. You report the average and the spread across folds. The average is a more stable estimate of performance, and the spread shows how much the result depends on which rows went into training.
That stability is the whole point. Instead of deciding between two models from one measurement, you compare two distributions. If one model wins on every fold, the difference is far more convincing than the same gap seen in a single split.
How many folds should you use, and what does the spread tell you?
Five and ten folds are the most common choices. The trade-off is direct: the larger the k, the more times the model is trained and the longer the experiment takes, while each validation fold gets smaller and each individual round becomes noisier.
When k equals the number of rows, every round leaves a single example out. That extreme case is known as leave-one-out: computational cost grows sharply and the spread across folds can actually increase, because the training sets end up nearly identical to each other.
Looking at the average alone is only half the job. A large spread across folds warns you that the model is sensitive to the composition of the data, and that warning is often worth more than the average itself.
When do stratification or time-based splits change the result?
In classification with imbalanced classes, plain random splitting can leave a fold with very few examples of the minority class. Stratified cross validation forces each fold to keep roughly the same class proportions as the full dataset.
In time series, shuffling the rows destroys the order and creates leakage: the model ends up training on future data to predict the past. Here the folds have to be cuts in time, always training on what came earlier and validating on what came later.
There are also cases where rows come in groups, such as the same patient, the same customer or the same store appearing many times. If a group shows up in both training and validation, the model can recognize the group instead of learning the pattern. The split has to be made by group.
How do you run cross validation in Python without data leakage?
The most common mistake is scaling, normalizing or selecting features before splitting. If the mean and standard deviation used for standardization were computed over the entire dataset, information from the validation fold leaked into training. The scaler has to be fitted inside each fold, which is what a pipeline is for.
The same rule applies to feature selection, target encoding, imputation, outlier handling and any resampling of the minority class: fit them on the training part only, then apply the already-fitted transformation to the validation part.
Duplicate or near-duplicate rows spread across folds are another quiet source of inflated scores. If the same record appears in training and validation, the model has effectively seen the answer.
The practical loop is short: for each fold, fit preprocessing and model on the training part, transform the validation part, score it, and average the results at the end. When you also tune hyperparameters, nested cross validation keeps the two jobs separate, with an inner loop choosing settings and an outer loop estimating performance.
Where does cross validation fit in the Python for Data Science and Analytics course?
The course covers cross validation as part of its machine learning content, alongside linear and logistic regression, K-Means, SVM, Naive Bayes, decision tree, Random Forest, Gradient Boosting, XGBoost, LightGBM and feature selection. The point is not to memorize an API call, but to understand why the single split misleads and how the folds correct it.
The program is organized into three main modules, Basic, Intermediate and Advanced, plus bonus modules. It starts with IDE and Jupyter Notebook setup, basic functions, NumPy and Pandas, user-defined functions, loops and conditionals, then moves into data visualization, data cleaning and preparation, and outlier detection.
It closes with a final project that runs exploratory analysis and machine learning end to end. Lessons are recorded, so you watch at your own pace, and guided exercises reinforce each topic. The course also includes projects based on real market scenarios to build a portfolio, a certificate of completion, an exclusive community for networking, and unlimited access with no expiry date.
No prior programming experience is required to start. Enrollment is R$ 470, or 12 installments of R$ 20.37 on a credit card, through the Hotmart checkout, which accepts card or boleto. Details are on the course site at python.paanalytics.net.
Learn cross validation hands-on, from zero to advanced
Secure payment via Hotmart, up to 12 installments.
Enroll now Product siteFrequently asked questions
Is cross validation the same thing as a train-test split?
No. A train-test split evaluates the model once on one fixed portion of the data. Cross validation repeats training and evaluation across several folds, so every row is validated once, and you end up with an average and a spread instead of a single number.
Does cross validation replace a held-out test set?
Not necessarily. A common setup keeps a final test set untouched while cross validation handles model comparison and hyperparameter choices. The test set is then used once, at the end, to confirm the estimate.
Can I use cross validation on time series data?
Yes, but not with shuffled k-fold. Shuffling mixes past and future and creates leakage. Time series needs folds that respect the order, training on earlier periods and validating on later ones.
How do I know whether my cross validation score is trustworthy?
Check three things: the spread across folds, whether any preprocessing was fitted before the split, and whether duplicate or grouped rows appear in more than one fold. A tight spread on a leaky setup is still a wrong number.
Do I need to know programming before learning this?
No. The Python for Data Science and Analytics course starts from zero and covers setup, basic functions, NumPy and Pandas before reaching machine learning topics such as cross validation.