Cross-Validation

Python · Machine Learning (Scikit-Learn)

Theory

A single train/test split gives one score that depends on which rows happened to land in the test set. K-fold cross-validation repeats the evaluation: the data is cut into k folds, the model is trained on k-1 folds and scored on the remaining one, and this rotates until every fold has been the test fold once. You get k scores; their mean is a more reliable estimate and their spread shows how stable the model is.

cross_val_score(model, X, y, cv=5) does it in one line and returns the five scores. For classifiers an integer cv uses StratifiedKFold, keeping class proportions in every fold; pass KFold(n_splits=5, shuffle=True, random_state=0) for explicit control, and scoring='f1' or 'neg_mean_absolute_error' to choose the metric. cross_validate can return several metrics at once. Put preprocessing in a Pipeline so it is refitted inside each fold.

Why we use it

It gives a more trustworthy performance estimate than one split, uses all the data for both training and testing and shows whether a score is stable or a lucky draw, which matters most for small datasets.

When to use it

Use cross-validation to compare models and tune hyperparameters, keeping a final test set aside for one last check. Use 5 or 10 folds; StratifiedKFold for classification and TimeSeriesSplit for time-ordered data, never a shuffled KFold.

How it works

  1. Training data and a model (or pipeline)
  2. Split rows into k folds
  3. Train on k-1 folds, score on the held-out fold
  4. Has every fold been the test fold? Yes: Average the k scores. No: Rotate to the next fold.
  5. Compare models by mean score and spread
  6. Reliable performance estimate

Syntax

from sklearn.model_selection import cross_val_score, KFold
cv = KFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring='accuracy')
scores.mean(), scores.std()

Example

scores = cross_val_score(model, X, y, cv=5)
print(scores.round(3), scores.mean().round(3))

Key points

Python topics

Getting Started

Variables & Data Types

Operators

Strings

Lists

Tuples

Sets

Dictionaries

Control Flow

Loops

Functions & OOP

Working with Data

Tooling & Errors

File Handling

Exception Handling

NumPy Library

Pandas Basics

Data Cleaning

Combining DataFrames (SQL Joins & Unions)

GroupBy & SQL-Style Analytics

Reshaping & Workflow

Data Visualization

Machine Learning (Scikit-Learn)

Advanced Python & AI

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Python for Data Analysts

From basics to business insights — the complete step-by-step Python roadmap. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice Python Online 141 Python questions for data analysts — strings, records, dates, statistics and regex — with hidden tests and instant verdicts. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Python  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
▶ Try It Live — runs real Python 3.12 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic