Bookmarks
ReferenceData & AIVerified

Machine learning basics

Machine learning builds models that learn from data. This reference covers scikit-learn, data preparation, models, metrics, overfitting and pipelines.

checked 7 Nov · next check 14 Nov · 61 min read

Sections
12
Reading
61 min
Current version
1.9.1
Written from
scikit-learn.org/stable/user_guide.html

Check status of the reference

Verified 7 Nov · next check 14 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What machine learning is and how it works

Machine learning is a way to get a model from data: an algorithm finds patterns in examples and predicts answers for new data where no rule has been written in advance. The main Python library for it is scikit-learn.

A model is useful where a rule is hard to state: telling spam from legitimate mail by its text, estimating a flat’s price from dozens of features, grouping customers by behaviour. The task determines what the model predicts and how it is evaluated:

TaskWhat it predictsExampleTypical metric
Classificationa category: spam or notdiagnosis from symptomsaccuracy
Regressiona number: a price, a temperaturethe price of a flatmean absolute error
Clusteringa group of similar examplescustomer segmentssilhouette coefficient
Dimensionality reductionnew features in place of the old onescompressing 200 features to 10explained variance ratio

Supervised and unsupervised learning

The difference is whether correct answers are available. In supervised learning, the answers y are known alongside the features X: spam or not spam, the price of a flat. This is how classifiers and regressors are trained. In unsupervised learning there are no answers, and the model looks for structure on its own: groups of similar customers, a compact description of the features, rare deviations. Outlier detection and density estimation belong to the same kind.

When you do not need machine learning

If the rule can be stated explicitly (“if the age is under 18, refuse”), write it as ordinary code: it is transparent, needs no data and cannot go wrong through overfitting. A model is justified when a rule is hard to extract from data. Two more reasons to avoid it: there is little data (a few dozen examples), or the cost of an error is unacceptable and every decision must be explainable.

The unified estimator API

In scikit-learn, every method is an estimator: an object that learns with fit and predicts with predict. The score method returns the quality of a trained estimator: accuracy for classifiers, the coefficient of determination for regressors. Transformers have transform instead of predict and only prepare features. This single interface lets you swap models for one another and assemble a pipeline from steps.

consoletraining and evaluation, from the documentation example
>>> from sklearn.pipeline import make_pipeline>>> from sklearn.preprocessing import StandardScaler>>> from sklearn.linear_model import LogisticRegression>>> from sklearn.datasets import load_iris>>> from sklearn.model_selection import train_test_split>>> from sklearn.metrics import accuracy_score>>> X, y = load_iris(return_X_y=True)>>> X_train, X_test, y_train, y_test = train_test_split(...     X, y, random_state=0)>>> pipe = make_pipeline(StandardScaler(), LogisticRegression())>>> pipe.fit(X_train, y_train)>>> accuracy_score(pipe.predict(X_test), y_test)0.97...

From data to prediction

Work on a task looks like a pipeline. The model is trained on one part of the data and checked on another that it has not seen; otherwise the score only shows success on memorised examples. Parameters are tuned with cross-validation inside the training part, and the test set is spent once, at the very end.

Evaluate on the test part once, at the end; for more on splitting, see “Data, features and splitting”.
  1. Collect the data: a feature matrix X and, for supervised learning, the answers y.
  2. Split it into training and test parts with train_test_split.
  3. Train the model on the training part with fit.
  4. Evaluate on the test part: predict and a metric from “Evaluation and metrics”.
  5. Tune the parameters with cross-validation; see “Cross-validation and hyperparameter tuning”.
  6. Train the final model and apply it to new data.

How it differs from neural networks and chatbots

Classical machine learning trains a model on your tabular data and gives a verifiable prediction: a probability, a number, a label. Large language models (LLMs) generate text after training on huge corpora and solve different tasks. For where each one fits, see the LLM and RAG reference. How neural networks and large models are built, trained and fine-tuned is covered in the AI models reference.

What to know beforehand

  • Python: functions, classes, working with lists and dictionaries; see the Python reference.
  • Tables: DataFrames, reading CSV, selecting columns; see the pandas reference.
  • Virtual environments with venv and installing packages; see the Python reference, “Installation and first run”.

Section sources

the section is written from these pages

Cheat sheet

A cheat sheet for everyday work with scikit-learn: data, feature preparation, models, evaluation, hyperparameter tuning and saving. Each row is one task with ready-made code. How each step works is covered in its own section of the reference.

Data

TaskHow to write it
Load a dataset to experiment withload_iris(return_X_y=True)
Split into training and test setstrain_test_split(X, y, test_size=0.25, random_state=0)
A dataset for regressionload_diabetes(return_X_y=True)

Preparation

TaskHow to write it
Bring features to the same scaleStandardScaler().fit_transform(X)
Encode a categorical feature as numbersOneHotEncoder(handle_unknown="ignore")
Fill missing values with the meanSimpleImputer(strategy="mean")
Squeeze features into the range 0 to 1MinMaxScaler().fit_transform(X)

Models

TaskHow to write it
Linear classificationLogisticRegression(max_iter=1000, random_state=0)
An ensemble of decision treesRandomForestClassifier(random_state=0)
Linear regressionLinearRegression()
Clustering into k groupsKMeans(n_clusters=3, random_state=0)
Gradient boosting over treesHistGradientBoostingClassifier(random_state=0)

Train a model with fit(X, y) and predict with predict(X). KMeans has no target variable: fit(X). For which models to choose for a task, see “Supervised learning” and “Unsupervised learning”.

Evaluation

TaskHow to write it
Share of correct classification answersaccuracy_score(y_test, y_pred)
Precision and recall for each classclassification_report(y_test, y_pred)
Number of errors for each pair of classesconfusion_matrix(y_test, y_pred)
Score over five cross-validation foldscross_val_score(model, X, y, cv=5)
The mean of those scorescross_val_score(model, X, y, cv=5).mean()
Explained variance of a regressionr2_score(y_test, y_pred)
Mean regression error in the same unitsmean_absolute_error(y_test, y_pred)

For which metrics suit which task, see “Evaluation and metrics”.

Hyperparameter tuning

pythonparameter search with cross-validation
from sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import GridSearchCV param_grid = {"n_estimators": [100, 300], "max_depth": [None, 10, 20]}search = GridSearchCV(    RandomForestClassifier(random_state=0), param_grid, cv=5)search.fit(X_train, y_train)print(search.best_params_, search.best_score_)

Take the finished model and its parameters from search.best_estimator_. For how cross-validation works, see “Cross-validation and hyperparameter tuning”.

Saving a model

pythonsaving and loading a trained model
import joblib joblib.dump(model, "model.joblib")model = joblib.load("model.joblib")

A loaded model needs the same scikit-learn version as was used for training. For what changes between versions, see “Versions and what’s new”.

Section sources

the section is written from these pages

Installation and first run

Install scikit-learn into a separate virtual environment (venv) with pip install -U scikit-learn; conda is the alternative. You can verify the installation in one line: python -c "import sklearn; sklearn.show_versions()".

Linux

Python 3 is already present in most distributions. Check:

bashon the host
python3 --versionpip3 --version

Create an environment in the project directory and install the library:

bashon the host
python3 -m venv .venvsource .venv/bin/activatepip install -U scikit-learn

pip installs the NumPy and SciPy dependencies by itself, so you do not need to install them separately. An isolated environment keeps its own scikit-learn version, independent of other Python packages. In each new terminal, activate the environment again with source .venv/bin/activate. The second official way is conda from the conda-forge channel: the environment and the library are installed with one command, and the conda installer does not need administrator rights:

bash
conda create -n sklearn-env -c conda-forge scikit-learnconda activate sklearn-env

The 1.9 branch needs Python 3.11 or newer. On macOS, install Python 3 with Homebrew (brew install python); on Windows, use the 64-bit version from python.org. The commands after that are the same as on Linux; only environment activation differs on Windows: .venv\Scripts\activate.

Verification

bashinside the environment
python -c "import sklearn; sklearn.show_versions()"
textexample output
System:    python: 3.14.10 (main, Oct 25 2026) [GCC 14.2.0]executable: /home/user/ml-project/.venv/bin/python   machine: Linux-6.8.0-85-generic-x86_64-with-glibc2.39 Python dependencies:      sklearn: 1.9.1          pip: 25.2        numpy: 2.3.4        scipy: 1.17.0...   matplotlib: 3.10.7       joblib: 1.5.2threadpoolctl: 3.6.0...Built with OpenMP: True

show_versions() prints the Python version and the path to the interpreter: the path shows that the package is installed in the project environment rather than in the system-wide Python. The versions of scikit-learn and its dependencies follow. python -m pip show scikit-learn also shows the package version and install location.

Your first project

Keep data and code next to the environment. data/ holds the source data and trained models; do not commit them to git. notebooks/ holds exploratory notebooks. A typical project directory:

text
ml-project/├── .venv/├── data/├── notebooks/├── requirements.txt└── train.py
bashproject environment and a list of versions
python3 -m venv .venvsource .venv/bin/activatepip install -U scikit-learn matplotlibpip freeze > requirements.txt

After pip freeze, requirements.txt contains the exact versions of every package in the environment; use it to restore the environment with pip install -r requirements.txt. matplotlib is needed for the plots that accompany the examples in the documentation.

Train your first model on the built-in iris dataset, a runnable example that needs nothing but the installed library. Save these lines in train.py and run python train.py:

pythontrain.py
from sklearn.datasets import load_irisfrom sklearn.neighbors import KNeighborsClassifier X, y = load_iris(return_X_y=True)model = KNeighborsClassifier().fit(X, y)print(model.predict([[5.1, 3.5, 1.4, 0.2]]))
textexample output
[0]

The number 0 is the predicted class of the flower in the iris dataset: KNeighborsClassifier found the closest flower in the training set and returned its class. load_iris(return_X_y=True) returns the features and the target variable. For how the fit step works, see “Supervised learning”; for data preparation, see “Data, features and splitting”.

Section sources

the section is written from these pages

Data, features and splitting

The data for a scikit-learn model is a feature matrix X and a vector of answers y. Before training, you prepare it: fill in missing values, encode categories and text, bring numbers to a common scale, and set the test part aside in advance, showing it to the model last.

Each row of X is one object: a flat, an email, a patient. Each column is a feature: area, text length, temperature. The matrix has n_samples rows and n_features columns, hence the shape (n_samples, n_features). y is the target: what the model must predict, a number in regression or a class in classification. pandas DataFrames can be passed to models directly.

pythonfeatures and target
# features: each column is one characteristic of an objectX = df[["area", "rooms", "floor"]]# target: the model predicts the pricey = df["price"]

Splitting into training and test sets

train_test_split shuffles the objects and divides them into two parts. The test_size parameter sets the share of the test part as a number from 0 to 1, or an absolute number of objects. If you set neither test_size nor train_size, a quarter goes to the test set. The data is shuffled by default; shuffle=False turns that off. random_state makes the split repeatable: with the same number, you get the same split.

pythonsplitting the sample
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(    X, y, test_size=0.25, stratify=y, random_state=42,)

For classification, add stratify=y: the class proportions in both parts stay the same as in the whole dataset. Without it, a rare class can end up almost entirely in one part, and training or evaluation on it breaks down.

The test set answers one question: how the model behaves on data it has not seen. If you use it to choose features, thresholds and models, it stops being an exam and the score is inflated. Spend the test set once, at the very end, and do working checks and tuning with cross-validation inside the training part; see “Cross-validation and hyperparameter tuning”.

Scaling

Features with different spreads, such as age in years and income in roubles, get in the way of models that use scale directly: SVMs with an RBF kernel and linear models with L1 and L2 regularisation. A feature with a large variance overwhelms the others, and the model learns worse. Scaling brings the numbers to a common measure: StandardScaler subtracts the mean and divides by the standard deviation, while MinMaxScaler squeezes values into a range, 0 to 1 by default.

TransformerWhat it doesWhen it is useful
StandardScalersubtracts the mean and divides by the standard deviation: features with mean 0 and unit variancethe default choice; SVMs with an RBF kernel, regularised linear models
MinMaxScalersqueezes each feature into a given range, 0–1 by defaultwhen you need the range 0–1 or a feature’s spread is very small; MaxAbsScaler scales sparse data

For a scaler, call fit on the training part first, then transform on both parts. The fit_transform method does both steps at once, but it too is applied only to the training data.

Categorical features

Columns with strings, such as city, brand or day of the week, are first encoded as numbers. OrdinalEncoder replaces each category with an integer, but this representation does not suit every model as it is: the numbers read as an order that the categories may not have. OneHotEncoder creates a column for each category and puts 1 in the column of the value it meets and 0 in the others.

pythonencoding the city category
from sklearn.preprocessing import OneHotEncoder enc = OneHotEncoder(handle_unknown="ignore")city_train = enc.fit_transform(X_train[["city"]])# categories are taken from the training part onlycity_test = enc.transform(X_test[["city"]])

Missing values

Missing values (NaN) make a dataset unusable for many scikit-learn models: most estimators expect numbers in every cell. SimpleImputer performs imputation: it fills in a column statistic computed on the training part. The strategy parameter chooses the approach: mean and median for numbers, most_frequent for categories, and constant fills in the value given in fill_value.

pythonfilling missing values with the median
from sklearn.impute import SimpleImputer imputer = SimpleImputer(strategy="median")imputer.fit(X_train)X_train = imputer.transform(X_train)X_test = imputer.transform(X_test)

Text to a matrix

Text is turned into numbers by vectorisation: CountVectorizer splits it into words and counts the occurrences of each word. The output is a sparse matrix whose columns are vocabulary words and whose rows are texts. TfidfVectorizer does the same and lowers the weight of words that are common across the whole corpus: prepositions and general words get a small weight, rare and specific ones a large weight. This weighted variant is used more often; if you need to add weighting to ready-made counts, put TfidfTransformer on top of CountVectorizer.

pythontexts to a sparse matrix
from sklearn.feature_extraction.text import TfidfVectorizer vectorizer = TfidfVectorizer()# the word vocabulary is built from the training texts onlyX_train_text = vectorizer.fit_transform(texts_train)X_test_text = vectorizer.transform(texts_test)

Order of operations and leakage

Every scikit-learn transformer has a fit that collects parameters (the mean for a scaler, the category table for an encoder, the vocabulary for a vectoriser) and a transform that applies them to data. Collect parameters on the training part only; otherwise data leakage occurs: information from the test part seeps into training, and the score is inflated.

The test part must not take part in fit.

The correct order is always the same:

  1. Split the data into training and test parts.
  2. Fit each transformer on the training part with fit.
  3. Apply transform to both parts.

In real code, these steps are assembled into a pipeline: Pipeline and ColumnTransformer call fit and transform in the right order themselves; see “Pipelines and ColumnTransformer” for details. Typical mistakes when working with data are covered in “Mistakes and limitations”.

Section sources

the section is written from these pages

Supervised learning

Supervised learning is training a model on examples that come with the right answers: the model receives the features and the target, then predicts the target for new data. The task is either classification (predict a class) or regression (predict a number).

In scikit-learn, all supervised models are estimators with the same interface: fit trains on X and y, and predict returns a prediction. That makes switching models a one-line change. For tabular data, start with tree ensembles, HistGradientBoosting or RandomForest, and keep linear models for simple relationships and as a baseline for comparison.

A first example

The built-in load_iris dataset has 150 iris flowers with 4 features each and 3 classes. It is a standard test bed for classifiers. Splitting into training and test sets is covered in the “Data, features and splitting” section.

pythonclassifying irises
from sklearn.datasets import load_irisfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_split X, y = load_iris(return_X_y=True)X_train, X_test, y_train, y_test = train_test_split(    X, y, test_size=0.25, random_state=0, stratify=y) clf = RandomForestClassifier(n_estimators=200, random_state=0)clf.fit(X_train, y_train)print(clf.score(X_test, y_test))print(clf.predict(X_test[:3]))print(clf.predict_proba(X_test[:3]).round(3))

predict returns the predicted class, and predict_proba returns the probability of each class. You need probabilities when you, not the model, choose the decision threshold: for example, to send everything with a probability of default above 0.3 to manual review. Not every model computes probabilities well: in SVC they are off by default, because they come from an expensive cross-validation. The probability parameter is deprecated in 1.9 and will be removed in 1.11; instead of SVC(probability=True), wrap the model in CalibratedClassifierCV(SVC(), ensemble=False).

Linear models

A linear model predicts a weighted sum of the features. LinearRegression fits the coefficients by least squares and works well when the features are reasonably independent. If features are correlated, the estimate becomes unstable; use Ridge then, which adds a penalty on the size of the coefficients to the error. The strength of the penalty is the regularisation parameter alpha: the larger it is, the closer the coefficients are pulled to zero and the more robust the model is to redundant and correlated features. The easiest way to choose alpha is cross-validation; see the “Cross-validation and hyperparameter tuning” section.

pythonridge regression
from sklearn.datasets import load_diabetesfrom sklearn.linear_model import Ridgefrom sklearn.model_selection import train_test_split X, y = load_diabetes(return_X_y=True)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)reg = Ridge(alpha=1.0)reg.fit(X_train, y_train)print(reg.coef_.round(3))print(reg.score(X_test, y_test))

Despite its name, LogisticRegression is a classification model. It predicts the probability of a class, and regularisation is set by the parameter C, the inverse of the penalty strength: a smaller C means stronger regularisation. The default is C=1.0; smaller values reduce overfitting on noisy data.

Trees and ensembles

DecisionTreeClassifier and DecisionTreeRegressor split the data with a series of questions of the form “is the feature at most the threshold?” and predict a value in the leaf. By default a tree grows until its leaves are pure, so a single tree tends to overfit; see the “Overfitting and generalisation” section. The main control is max_depth: a depth of 2–3 gives a tree you can read as rules (the export_text function prints them as text), while the default, unlimited depth is only suitable inside an ensemble.

Ensembles combine many trees. RandomForest trains trees independently on random subsamples and averages their predictions, so the errors of individual trees cancel out. HistGradientBoosting builds trees one after another, each correcting the errors of the previous ones. On tabular data, gradient boosting often gives better quality and trains faster than a random forest from tens of thousands of rows upwards. It handles missing values in features without imputation. On large data, compare both options with cross-validation.

KNeighborsClassifier is nearest neighbours: the prediction is a vote of the closest training samples. SVC is a support vector machine: it separates classes with a hyperplane of maximum margin, and the kernel lets it separate non-linear data too.

Models differ in their tasks, sensitivity to feature scale and key parameters:

ModelTasksScalingWhat to watch
LinearRegressionregressionrecommendedcorrelated features distort the coefficients
Ridgeregressionrecommendedalpha: larger means a stronger penalty
LogisticRegressionclassificationrecommendedC: smaller means stronger regularisation
KNeighborsClassifierclassification, regressionrequiredthe number of neighbours n_neighbors; memory: it stores all the data
SVCclassification, regressionrequiredthe kernel; slow on large data
DecisionTreeClassifierclassification, regressionnot neededmax_depth, or it will overfit
RandomForestClassifierclassification, regressionnot neededn_estimators; more is more accurate and slower
HistGradientBoostingClassifierclassification, regressionnot neededmax_iter; reads missing values itself; fast on large data

In classification the classes are often imbalanced: fraud, for example, may be one row in a thousand. Then accuracy is misleading, as explained in the “Evaluation and metrics” section. In LogisticRegression, the class_weight='balanced' parameter sets the class weights: mistakes on the rare class are penalised more, and the model stops predicting only the frequent class.

What next

Measure model quality on a held-out set and with cross-validation; the “Evaluation and metrics” section covers the metrics and how to choose one for your task. Tuning alpha, C and the number of boosting iterations max_iter with a grid search is in the “Cross-validation and hyperparameter tuning” section. Grouping similar objects without ready-made answers is in the “Unsupervised learning” section.

Section sources

the section is written from these pages

Unsupervised learning

Unsupervised learning is training on features without ready-made answers: the model looks for structure in the data on its own. There are three typical tasks: clustering (split objects into groups), dimensionality reduction (compress the features while keeping the spread) and anomaly detection (flag outliers).

There are no right answers, so there is no “accuracy” either: quality is judged by measures of the structure itself, such as the silhouette score. Always check the result for sense: are the groups you got understandable, and is the compressed representation good enough for the next steps?

Clustering

Clustering groups similar objects: customer segments, document topics, network nodes. The main question is what shape of groups you expect. KMeans looks for round groups of equal density around centres (centroids), while DBSCAN finds regions of high density of any shape. Each model handles the number of groups differently: for KMeans and AgglomerativeClustering you set it yourself, while DBSCAN finds it on its own.

pythonclustering irises into three groups
from sklearn.cluster import KMeansfrom sklearn.preprocessing import StandardScalerfrom sklearn.datasets import load_irisfrom sklearn.pipeline import make_pipeline X, y = load_iris(return_X_y=True) model = make_pipeline(    StandardScaler(),    KMeans(n_clusters=3, n_init=10, random_state=0),)labels = model.fit_predict(X)print(labels[:15])

labels holds the group number of each object. The predict method assigns a new object to the nearest centre, so KMeans also works as a pipeline step. The n_init parameter sets how many times the algorithm restarts with different initial centres: the run with the best inertia is kept. By default ('auto') there is one run with k-means++ initialisation and ten with random initialisation; several runs are recommended for sparse high-dimensional data.

MethodWhen to choose itKey parameter
KMeansthe groups are roughly round and similar in size; fast on large datan_clusters: the number of groups
DBSCANgroups of any shape and an unknown number; noise points do not fall into any groupeps: the neighbourhood radius, min_samples: the density
AgglomerativeClusteringyou need a hierarchy of groups, or the dataset is smalln_clusters or distance_threshold

In agglomerative clustering every object starts on its own, and then groups are merged pairwise until n_clusters remain. The linkage parameter sets how merging is measured; by default ward gives groups of the most even size. On large data without connectivity constraints the method is slow, so use KMeans there.

DBSCAN marks noise with the label -1 and the other groups with numbers. eps has to be chosen for your data, and the default is rarely suitable; a common technique is the “knee” on a plot of distances to the nearest neighbours. If too many points end up as noise, increase eps; if groups merge into one, decrease it. A smaller eps or a larger min_samples makes clusters denser and smaller.

How many clusters: the silhouette score

The number of groups is rarely known in advance. The silhouette score rates a partition with a number from -1 to 1: for each object it compares the mean distance to its own group (a) with the mean distance to the nearest other group (b). Closer to its own group and farther from the others means closer to 1; around zero means groups overlap; negative means the object probably belongs to another group.

pythonsilhouette score for different numbers of clusters
from sklearn.metrics import silhouette_score for k in range(2, 7):    km = KMeans(n_clusters=k, n_init=10, random_state=0)    labels = km.fit_predict(X)    s = silhouette_score(X, labels)    print(k, round(s, 3))

Try n_clusters from 2 to 6–7 and take the value with the highest silhouette score; after the first maximum the curve usually falls. The silhouette score uses Euclidean distances, so on high-dimensional data compute it after PCA.

Dimensionality reduction: PCA

Principal component analysis (PCA) compresses a table of features into a smaller number of new ones, the principal components. Each component is a direction along which the data is spread out the most; the first components carry most of the spread (variance). The share of variance for each component is in explained_variance_ratio_; if all components are kept, they sum to 1.

pythoncompressing 64 features to 95% of the variance
from sklearn.decomposition import PCAfrom sklearn.datasets import load_digits X, y = load_digits(return_X_y=True) pca = PCA(n_components=0.95, random_state=0)X2 = pca.fit_transform(X)print(X.shape, "->", X2.shape)print(pca.explained_variance_ratio_.round(3))

A fractional n_components=0.95 keeps as many components as are needed for 95% of the variance. On the digits dataset this compresses 64 features to about three dozen with almost no loss of spread. If you need a specific size, pass a number: PCA(n_components=2) gives two components for a plot.

fit_transform learns the components and projects the data; transform then compresses new objects with the same components. PCA centres the features itself, but the features have different scales, so put a StandardScaler in front of it. The components are linear combinations of the original features, and they only turn into new features after fit.

Dimensionality reduction helps clustering too: in high-dimensional spaces Euclidean distances grow and stop telling groups apart, and PCA before clustering removes this effect and speeds up the computation. Most often PCA is placed before KMeans in the same Pipeline.

Anomaly detection

IsolationForest separates outliers from the bulk of the data: a forest of random trees cuts the data with random thresholds, and an anomaly, a point off to the side, is isolated in noticeably fewer cuts. The method works on high-dimensional data and makes no assumptions about the distribution.

pythonanomalies are about 2% of the data
from sklearn.ensemble import IsolationForest model = IsolationForest(    n_estimators=200, contamination=0.02, random_state=0,)labels = model.fit_predict(X)print((labels == -1).sum())

predict returns 1 for ordinary points and -1 for anomalies. The contamination parameter is the expected share of outliers; it sets the threshold on the scores. Set 0.02 when about 2% are anomalies, and leave 'auto' if the share is unknown. The scores themselves come from the score_samples method: the lower the value, the more suspicious the object.

What next

How to put StandardScaler into a chain of steps is in the “Pipelines and ColumnTransformer” section. Cross-validation and grid search over the number of components or clusters are in the “Cross-validation and hyperparameter tuning” section. Typical mistakes when interpreting clusters and components are in the “Mistakes and limitations” section.

Section sources

the section is written from these pages

Evaluation and metrics

A “good model” is one that, on data it has not seen, predicts better than the simplest baseline. A metric is a number that measures this; which metric to choose is decided by the cost of an error in your task, not by the habit of reaching for accuracy.

Never check a model on the data it was trained on: the score will be inflated. Set the test part aside in advance (see the “Data, features and splitting” section), and cross-validation computes the same metric over several splits (see the “Cross-validation and hyperparameter tuning” section).

The baseline: the simplest model

Before measuring quality, decide what to compare against. DummyClassifier and DummyRegressor predict by a simple rule without using the features: the most frequent class or the mean of the answers. If a real model is only slightly better than that, it has not yet extracted anything from the features.

pythona baseline on imbalanced data
from sklearn.datasets import make_classificationfrom sklearn.dummy import DummyClassifierfrom sklearn.model_selection import train_test_split # imbalanced classes: 5% fraudX, y = make_classification(    n_samples=5000, n_features=10, weights=[0.95, 0.05],    flip_y=0.02, random_state=42)X_train, X_test, y_train, y_test = train_test_split(    X, y, test_size=0.25, random_state=42, stratify=y) dummy = DummyClassifier(strategy="most_frequent")dummy.fit(X_train, y_train)print(dummy.score(X_test, y_test))

Why accuracy misleads

Accuracy is the share of correct answers among all objects. When classes are imbalanced, it is earned almost entirely on the frequent class: a model that always answers “no fraud” is right 99% of the time if fraud is one case in a hundred, yet it catches none.

pythonimbalanced classes: 5% fraud
from sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import classification_reportfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScaler model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))model.fit(X_train, y_train)print(classification_report(    y_test, model.predict(X_test), target_names=["ok", "fraud"]))
textexample output
              precision    recall  f1-score   support           ok       0.95      0.99      0.97      1174       fraud       0.69      0.24      0.35        76     accuracy                           0.95      1250   macro avg       0.82      0.62      0.66      1250weighted avg       0.94      0.95      0.93      1250

An accuracy of 0.95 looks good, but the recall for the fraud class is 0.24: the model finds only a quarter of the fraud cases. The baseline has an accuracy of 0.939. Comparing by accuracy alone tells you nothing here; look at the class the model was built for.

Confusion matrix

A confusion matrix shows where the model sends the objects of each class: the diagonal holds the correct ones, and everything off it is confused. Rows are the true class and columns are the predicted class. ConfusionMatrixDisplay draws the matrix, and normalize='true' converts the counts to row-wise fractions.

pythonconfusion matrix
from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix y_pred = model.predict(X_test)print(confusion_matrix(y_test, y_pred))ConfusionMatrixDisplay.from_estimator(model, X_test, y_test)
textexample output: rows are the true class
[[1166    8] [  58   18]]

Classification metrics

In the matrix above, 58 fraud cases went to the ok class; this is the low recall that accuracy does not see. Precision and recall are computed for the positive class. Precision answers “of those labelled positive, how many are right”; it matters when a false alarm is expensive. Recall answers “of the truly positive, how many were found”; it matters when a miss is expensive, as in diagnostics and in searching for fraud and defects.

MetricWhat it showsWhen to use it
accuracy_scorethe share of correct answersthe classes are balanced and errors cost the same
precision_scorethe share of correct ones among those labelled positivea false alarm is expensive: a spam filter, issuing a loan
recall_scorethe share of true positives founda miss is expensive: disease, fraud, a defect
f1_scorethe harmonic mean of precision and recallyou need a single number for a report
balanced_accuracy_scorethe mean recall over all classesthe classes are imbalanced
roc_auc_scorethe quality of ranking by probability, independent of the thresholdcomparing models and choosing a threshold
confusion_matrixhow many objects of each class are confusedanalysing errors before choosing a metric

roc_auc_score takes probabilities, not predictions: model.predict_proba(X_test)[:, 1] is the second column, the probability of the positive class (classes_[1]). A score of 0.5 equals random guessing, and 1.0 equals perfect ranking.

Regression metrics

mean_absolute_error is the mean error in the units of the target, and it is the easiest to explain. root_mean_squared_error amplifies large misses: because of the square, an error of 10 units weighs as much as a hundred errors of 1. r2_score compares the model with predicting the mean: 0 is the same as the mean, 1 is perfect. A negative value means the model is worse than the mean; for a baseline that predicts the mean, R² will be about zero.

pythonregression metrics
from sklearn.datasets import make_regressionfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import (mean_absolute_error, r2_score,                             root_mean_squared_error)from sklearn.model_selection import train_test_split X, y = make_regression(n_samples=2000, n_features=8, noise=10.0,                       random_state=42)Xr_train, Xr_test, yr_train, yr_test = train_test_split(    X, y, random_state=42)reg = LinearRegression().fit(Xr_train, yr_train)y_pred = reg.predict(Xr_test) print(mean_absolute_error(yr_test, y_pred))print(root_mean_squared_error(yr_test, y_pred))print(r2_score(yr_test, y_pred))
textexample output: regression
7.659.70.997

The scoring parameter

The evaluation and tuning tools, cross_val_score, GridSearchCV and TunedThresholdClassifierCV, take a scoring parameter: a string with the name of a metric. sklearn.metrics.get_scorer_names() returns the list of all names.

pythonone metric under cross-validation
from sklearn.model_selection import cross_val_score scores = cross_val_score(reg, X, y, cv=5,                         scoring="neg_root_mean_squared_error")print((-scores).mean())

The name strings correspond to the functions of the sklearn.metrics module: accuracy, f1, f1_macro, roc_auc, neg_mean_absolute_error, r2. For imbalanced classes, use f1_macro or balanced_accuracy rather than accuracy.

The decision threshold

By default a binary classifier assigns an object to the positive class when the probability is above 0.5. The threshold can be moved: in a task where a miss is expensive, lower it to catch more positives at the price of extra alarms. The TunedThresholdClassifierCV wrapper chooses the threshold for a given metric using cross-validation. The wrapper’s predict uses the new threshold; the probabilities do not change.

pythontuning the threshold for a metric
from sklearn.model_selection import TunedThresholdClassifierCV tuned = TunedThresholdClassifierCV(model, scoring="f1")tuned.fit(X_train, y_train)print(tuned.best_threshold_)

What to do with the errors you find, and how not to tailor a model to the test set, is covered in the “Overfitting and generalisation” section. Why feature transformations are fitted only on the training part, so that the score is not inflated, is explained in the “Data, features and splitting” and “Pipelines and ColumnTransformer” sections.

Section sources

the section is written from these pages

Overfitting and generalisation

Overfitting is fitting a model to the training data together with its noise, so that it performs worse on new data than on the training data. The opposite is underfitting: a model that is too simple makes errors even on the training data. The diagnosis rests on two scores: one on training and one on validation.

Quality is not checked on the data the model learned from: the score there is almost always inflated. A reliable score comes from cross-validation or a held-out test part; how to get them is described in the “Data, features and splitting” and “Cross-validation and hyperparameter tuning” sections. Below, “validation score” means either of them.

Diagnosis from two errors

Train the model and compute the error twice: on the training data and on validation. Any metric will do as long as it is the same for both scores; for how to choose, see the “Evaluation and metrics” section.

Training errorValidation errorDiagnosis
lowlowthe model fits
highhighunderfitting: the model is too simple
lowhighoverfitting: the model memorised the noise

Both errors break down into bias, variance and data noise. Bias is the model’s systematic error across different samples: it is high in models that are too simple. Variance is sensitivity to a change of sample: it is high in models that are too flexible. Making a model more complex lowers bias and raises variance, so the goal of tuning is a balance, not maximum flexibility.

Typical cases: an unconstrained DecisionTreeClassifier grows until its leaves are pure and memorises the sample, so it overfits; LinearRegression on a non-linear relationship underfits.

Validation curves and learning curves

A validation curve shows both scores for different values of a single hyperparameter. It answers which value is best and which way to move.

pythonvalidation curve over regularisation strength
from sklearn.linear_model import Ridgefrom sklearn.model_selection import validation_curve train_scores, valid_scores = validation_curve(    Ridge(), X, y, param_name="alpha",    param_range=[0.1, 1.0, 10.0, 100.0],    scoring="neg_root_mean_squared_error",)

Read the curves by the gap. The functions return “bigger is better” scores: neg_root_mean_squared_error is the error with a minus sign. If both scores are low, it is underfitting; a high training score with a low validation score is overfitting. The best parameter value is where the validation score is highest and the gap is moderate. A training score above the validation score is normal; the reverse almost never happens.

A learning curve shows both scores for different training set sizes. It answers whether new data will help: if the curves have converged at a low level, new data will hardly help and the limit is in the model itself; if the gap is large, adding data will raise the validation score.

pythonlearning curve over sample size
from sklearn.model_selection import learning_curve sizes, train_scores, valid_scores = learning_curve(    Ridge(), X, y, train_sizes=[50, 100, 200, 400],    scoring="neg_root_mean_squared_error",)

Both functions compute scores by cross-validation and return matrices: a row is a parameter value or a sample size, and a column is a cross-validation repeat. For a ready-made plot, use the ValidationCurveDisplay.from_estimator and LearningCurveDisplay.from_estimator classes.

Example: polynomial regression

The official example approximates a section of a cosine with 30 noisy points, using a pipeline of PolynomialFeatures and LinearRegression with degrees 1, 4 and 15, and evaluates each degree with cross-validation.

pythoncross-validation error for each degree
import numpy as npfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import cross_val_scorefrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import PolynomialFeatures rng = np.random.RandomState(0)X = np.sort(rng.rand(30))y = np.cos(1.5 * np.pi * X) + rng.randn(30) * 0.1 for degree in (1, 4, 15):    model = Pipeline([        ("poly", PolynomialFeatures(degree=degree, include_bias=False)),        # small singular values are not cut off        ("lin", LinearRegression(tol=np.finfo(float).eps)),    ])    scores = cross_val_score(        model, X[:, np.newaxis], y, cv=10,        scoring="neg_mean_squared_error",    )    print(degree, -scores.mean())

Degree 1 underfits: a straight line cannot follow the curve of the cosine, so the error is large on both training and validation. Degree 4 follows the shape of the cosine almost perfectly and gives the lowest validation error; this is generalisation. Degree 15 passes through every point, but between them it swings to extreme values: its validation error is several orders of magnitude higher than for degree 4.

The transformation and the model are assembled in a Pipeline: cross-validation refits this pipeline on each training part, so the polynomial features are computed from that part’s data only. A transformer that learns something, such as scaling, imputation or feature selection, is fitted on the training part only: calling fit on the whole sample gives an inflated validation score.

What helps against overfitting

Overfitting is treated by limiting flexibility, and underfitting by adding it. The main techniques:

TechniqueHow it works
Ridge regularisationpenalises the size of the coefficients: larger alpha is stricter
the C parameter of LogisticRegression and SVCthe inverse of the penalty strength: smaller C means stronger regularisation
max_depth and min_samples_leaf of a treelimit growth and require many objects per leaf
more training datathe learning curve shows whether there is room to grow
fewer featuresfeature selection removes noisy columns
pythonregularisation instead of changing the degree
from sklearn.linear_model import Ridgefrom sklearn.pipeline import make_pipeline # the same degree 15, but with a penalty on the coefficientsmodel = make_pipeline(    PolynomialFeatures(degree=15, include_bias=False),    Ridge(alpha=1.0),)

GridSearchCV automates trying values by hand along the validation curve; see the “Cross-validation and hyperparameter tuning” section for details. If the validation score improves neither with more data nor with model settings, go back to the features and the problem statement; see the “Mistakes and limitations” section.

Section sources

the section is written from these pages

Pipelines and ColumnTransformer

A pipeline chains data preparation steps and a final model into a single scikit-learn estimator: one fit call trains the whole chain. ColumnTransformer sends different DataFrame columns through different transformations. Together they make preparation and model one object, with no data leakage.

A pipeline stores its steps as a list of (name, estimator) pairs. fit walks the chain: each intermediate step is fitted and immediately transforms the data for the next one, and the last step is fitted last. The pipeline exposes the methods of the final step — predict, predict_proba, score — as its own, passing the data through the already fitted transformers first.

The main benefit of a pipeline is protection against leakage. Everything the transformers learn during fit — means for scaling, medians for filling gaps, the list of categories — is learned only from the data the pipeline was trained on. In cross-validation the chain is refitted on every split, so the held-out part never takes part in anything: see the section “Cross-validation and hyperparameter tuning”.

One fit call trains both the transformers and the model.

Pipeline and make_pipeline

All steps except the last must be transformers, that is, have a transform method. The last step can be a model or another transformer, in which case the whole pipeline acts as a transformer. Steps are named explicitly, or make_pipeline names them after their lowercase class names:

pythontwo ways to build a pipeline
from sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import Pipeline, make_pipelinefrom sklearn.preprocessing import StandardScaler # step names given explicitlypipe = Pipeline([    ("scaler", StandardScaler()),    ("model", LogisticRegression()),]) # or automatically: lowercase class namesquick = make_pipeline(StandardScaler(), LogisticRegression())

ColumnTransformer: different columns, different transformations

A table usually holds mixed data: numbers to scale, categories to encode, sometimes text. ColumnTransformer applies a separate transformer to each group of columns and joins the results into one feature matrix. Columns are selected by name, by position or by data type with make_column_selector. Columns that no transformer touches are dropped; remainder="passthrough" appends them unchanged to the end of the matrix.

pythonreference example: a table with numbers and categories
import numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformerfrom sklearn.compose import make_column_selectorfrom sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.pipeline import Pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScaler df = pd.DataFrame({    "age": [35, 44, None, 28],    "income": [1200, 2400, 900, None],    "city": ["Tashkent", "Bukhara", "Tashkent", "Bukhara"],})y = pd.Series([0, 1, 0, 1]) num_cols = make_column_selector(dtype_include=np.number)cat_cols = make_column_selector(dtype_include=object) num = Pipeline([    # medians for missing values are learned only during fit    ("imputer", SimpleImputer(strategy="median")),    ("scaler", StandardScaler()),])# dense matrix: pandas output does not accept a sparse onecat = OneHotEncoder(handle_unknown="ignore", sparse_output=False) pre = ColumnTransformer([    ("num", num, num_cols),    ("cat", cat, cat_cols),])pipe = Pipeline([    ("prep", pre),    ("model", LogisticRegression()),])pipe.fit(df, y)

During fit the imputer learns the medians of the numeric columns, the scaler learns means and standard deviations, and the encoder learns the list of cities, all from the training data only. Numeric columns go through the nested num pipeline: gaps are filled first, then the values are scaled. A new city that was not seen during fit will not crash predict: with handle_unknown="ignore" its columns are all zeros.

TaskTool
combine preparation and a model into one estimatorPipeline or make_pipeline
different transformations for different columnsColumnTransformer or make_column_transformer
select columns by data typemake_column_selector(dtype_include=…)
keep columns outside the transformationsremainder="passthrough" in ColumnTransformer
get a DataFrame with column namesset_output(transform="pandas")
reach a step’s parameterstep name, two underscores, parameter: model__C

Output as a DataFrame

By default a transformer returns a numpy array without column names. Calling pipe.set_output(transform="pandas") switches every step of the pipeline to DataFrame output, with names like num__age: step name, two underscores, column. The get_feature_names_out() method gives the same names and works without pandas. Pandas output requires that transformers do not return a sparse matrix, which is why the encoder has sparse_output=False.

pythonfeatures after the preparation steps
# a DataFrame instead of an array: names like step__columnpipe.set_output(transform="pandas")features = pipe[:-1].transform(df)print(type(features).__name__)print(list(features.columns))
textexample output
DataFrame['num__age', 'num__income', 'cat__city_Bukhara', 'cat__city_Tashkent']

Step parameters

A parameter of any step is written as the step name, two underscores and the parameter name. set_params changes a parameter of an already built pipeline, and get_params returns the parameters of the whole chain. The chain reaches into nested pipelines: prep__num__imputer__strategy is the imputer’s strategy inside the num step. GridSearchCV uses the same names — see the section “Cross-validation and hyperparameter tuning”.

pythonaccessing step parameters
# regularisation strength of the final modelpipe.set_params(model__C=10.0) # imputer strategy in the nested num steppipe.get_params()["prep__num__imputer__strategy"]

make_pipeline names steps after their lowercase classes, such as simpleimputer and standardscaler. Such names are awkward in parameter chains, so give steps explicit names, like imputer in the reference example.

Saving a fitted pipeline

Save the fitted pipeline as a whole: along with the model weights, it holds the medians, means and categories learned during fit. Saving a bare model without its pipeline is a common mistake: predict would receive unscaled numbers and unencoded categories. joblib is efficient with large numpy arrays; skops.io is safer.

pythonsaving and loading
import joblib joblib.dump(pipe, "pipeline.joblib")restored = joblib.load("pipeline.joblib")restored.predict(df)
pythonsaving with a type check
import skops.io as sio sio.dump(pipe, "pipeline.skops")types = sio.get_untrusted_types(file="pipeline.skops")# review the list of types, then loadrestored = sio.load("pipeline.skops", trusted=types)

The transformers in the reference example — scaling, imputation, category encoding — are covered in the section “Data, features and splitting”. For using GridSearchCV with a pipeline, see the section “Cross-validation and hyperparameter tuning”.

Section sources

the section is written from these pages

Cross-validation and hyperparameter tuning

Cross-validation checks a model’s quality on several splits of the dataset: each fold takes a turn as the validation set, and the average score is more reliable than a single check. It is also used to tune hyperparameters, the settings a model does not learn by itself: GridSearchCV and RandomizedSearchCV automate the search.

A score from a single split can be lucky or unlucky: “easy” or “hard” samples may happen to land in the validation part. Cross-validation reduces this randomness: the model is trained and checked several times on different parts, and the scores are averaged. The price is computation: five folds mean five training runs.

How k-fold cross-validation works

In k-fold cross-validation the dataset is divided into k roughly equal parts, called folds. Each fold is used once as the validation set while the other k−1 folds are used for training; the score is the average over the k runs. KFold works this way; StratifiedKFold keeps the class proportions of the original dataset in every fold and suits classification better. Both use 5 folds by default.

The validation fold of the current run is shown in blue.

The cross_val_score function trains the estimator on each split and returns an array of scores, one per fold. The cv parameter sets the number of folds; by default StratifiedKFold is used for classifiers and KFold for everything else.

pythonfive scores, one per fold
from sklearn.model_selection import KFold, cross_val_scorefrom sklearn.svm import SVC # explicit splitter with shuffling and a fixed seedcv = KFold(n_splits=5, shuffle=True, random_state=42)scores = cross_val_score(SVC(kernel="linear"), X, y, cv=cv)

By default the estimator’s score method is used: accuracy for a classifier, R² for a regressor. The scoring parameter selects another metric, such as "f1_macro" or "neg_root_mean_squared_error"; the names are listed in the section “Evaluation and metrics”.

Mean and spread across folds

The array of scores shows both the mean and the spread, and the spread tells you how much the result depends on the split. Compute the mean with scores.mean() and the standard deviation with scores.std():

pythona score with its spread
print(f"{scores.mean():.3f} ± {scores.std():.3f}")

A large spread is a warning sign: the model is unstable when the data changes. A gain of 0.001 in the mean with a spread of 0.1 is not yet an advantage of one model over another.

cross_validate returns more: a dictionary with scores for several metrics at once, plus the training time fit_time and the prediction time score_time:

pythontwo metrics and timings in one pass
from sklearn.model_selection import cross_validate scores = cross_validate(    SVC(kernel="linear"), X, y, cv=5,    scoring=["accuracy", "f1_macro"],)scores["test_accuracy"]scores["test_f1_macro"]

Score keys start with test_. The return_train_score=True parameter adds training scores too; the gap between the two reveals overfitting (see the section “Overfitting and generalisation”).

Hyperparameter tuning

Hyperparameters are model settings fixed before training: C and gamma for SVC, alpha for Ridge, max_depth for a tree. GridSearchCV tries every combination in the param_grid, runs cross-validation for each and keeps the best one.

pythongrid search with cross-validation
from sklearn.model_selection import GridSearchCVfrom sklearn.svm import SVC param_grid = {    "C": [0.1, 1, 10, 100],    "gamma": ["scale", 0.01, 0.1],}search = GridSearchCV(    SVC(), param_grid, scoring="f1_macro", cv=5,)search.fit(X_train, y_train)search.best_params_search.best_score_

After fit, the best parameters are in best_params_, the mean cross-validation score is in best_score_, and the final model, refitted on all the training data, is in best_estimator_ (the search object itself behaves as that model, because refit=True by default). All attempts are in cv_results_, a dictionary of column arrays that becomes a pandas table with pd.DataFrame(search.cv_results_).

What you needWhere to find it
best parameterssearch.best_params_
score of the best combinationsearch.best_score_
fitted modelsearch.best_estimator_ or search itself
all attemptssearch.cv_results_

A grid can also include pipeline parameters, written as the step name plus two underscores: "logistic__C" for C inside a Pipeline.

RandomizedSearchCV tries not the whole grid but n_iter random combinations: instead of lists, param_distributions takes distributions, for example scipy.stats.loguniform(1e-3, 1e2). When there are many parameters or the ranges are wide, random search often finds candidates that are just as good for the same budget.

python20 random combinations instead of the full grid
from scipy.stats import loguniformfrom sklearn.model_selection import RandomizedSearchCV search = RandomizedSearchCV(    SVC(),    {"C": loguniform(1e-3, 1e2), "gamma": ["scale", 0.01, 0.1]},    n_iter=20, random_state=42, cv=5,)

Both searches can run in parallel: n_jobs=-1 uses all cores. A cheaper approach is HalvingGridSearchCV, a tournament in which candidates are first evaluated on a small part of the data and the survivors get more data in later rounds.

The test set and nested cross-validation

Tuning with cross-validation biases its estimate: hundreds of combinations have been tried on the same splits, so the winner has partly fitted itself to them. That is why the final quality is checked on a held-out test set that the search never saw: split the data into training and test parts, run the search on the training part, and make a single final check on the test part (best_estimator_.score(X_test, y_test)).

If you cannot afford to spend the test set on a single check, there is nested cross-validation (nested CV): the outer loop evaluates the model on its own folds, and inside each fold a separate search runs over its own grid. It gives an honest estimate of the whole “search + training” procedure, but is more expensive: the entire search is repeated for every outer fold.

Cross-validation for time series

Classic splitters such as KFold and StratifiedKFold treat samples as independent, but in a time series order matters: training on the future and validating on the past is not allowed, as it inflates the score. TimeSeriesSplit divides the series into consecutive folds: training always uses data that precedes the validation part, and the training set grows with each fold.

pythontime-based cross-validation
from sklearn.model_selection import TimeSeriesSplit tscv = TimeSeriesSplit(n_splits=5, gap=7)scores = cross_val_score(model, X, y, cv=tscv)

The gap parameter cuts out a pause between training and validation, for example when a feature is built from the previous 7 days of data.

If one customer or patient has several rows, those rows form one group: GroupKFold ensures that a group never appears in both training and validation.

Splitting is the first step of the data workflow (see the section “Data, features and splitting”): the rules against leakage apply inside every fold as well. For most tasks cross_val_score and GridSearchCV are enough; deviations depend on the structure of the data: time, groups, rare classes.

Section sources

the section is written from these pages

Mistakes and limitations

Two mistakes most often make a model’s results untrustworthy: data leakage, where the test set took part in training, and evaluating on the training data. Both produce inflated numbers that say nothing about quality on new data, and both are fixed by splitting before any transformation and by using pipelines.

Overfitting, where a model memorises the noise in the training data, is covered in detail in the section “Overfitting and generalisation”; metrics are covered in the section “Evaluation and metrics”.

Leakage during feature preparation

Every transformer learns from data: StandardScaler remembers means and standard deviations, SelectKBest remembers feature scores. If you call fit on all the data before splitting, the test set influences the model even though you never showed it to the model directly.

The consequence is an inflated score. In the example below the labels are random, so the honest accuracy is about 0.5, but after selecting features on the whole dataset it is 0.76.

pythonleakage through feature selection
import numpy as npfrom sklearn.ensemble import HistGradientBoostingClassifierfrom sklearn.feature_selection import SelectKBestfrom sklearn.metrics import accuracy_scorefrom sklearn.model_selection import train_test_split rng = np.random.RandomState(42)X = rng.standard_normal((200, 10000))y = rng.choice(2, 200) # feature selection sees the test part too: fit on all the dataX_sel = SelectKBest(k=25).fit_transform(X, y)X_train, X_test, y_train, y_test = train_test_split(    X_sel, y, random_state=42)model = HistGradientBoostingClassifier(random_state=1)model.fit(X_train, y_train)# score 0.76: the data is random, honest accuracy is about 0.5print(accuracy_score(y_test, model.predict(X_test)))
pythonselection on the training part
X_train, X_test, y_train, y_test = train_test_split(    X, y, random_state=42)select = SelectKBest(k=25)model = HistGradientBoostingClassifier(random_state=1)model.fit(select.fit_transform(X_train, y_train), y_train)# score 0.5: the level of random guessing, no leakageprint(accuracy_score(y_test, model.predict(select.transform(X_test))))

The rule: split first, then call any fit; on the test set use only transform. StandardScaler, SimpleImputer, PCA and almost all scikit-learn transformers behave the same way, and a pipeline follows the rule on its own. Leakage comes only from a fit on data that includes the test set; transform itself must be applied to the test set, which has to go through the same transformations as the training set.

Different preparation for training and prediction

If a model is trained on scaled features but receives raw ones at prediction time, the feature space has changed and the model makes mistakes. In the documentation’s example, a regression trained on scaled data gets an MSE of 62.8 on an unscaled test set instead of 0.9.

pythonscaling inside a pipeline
from sklearn.datasets import make_regressionfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import mean_squared_errorfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScaler Xr, yr = make_regression(random_state=42, n_features=1, noise=1)X_train, X_test, y_train, y_test = train_test_split(    Xr, yr, test_size=0.4, random_state=42)scaler = StandardScaler()model = LinearRegression().fit(scaler.fit_transform(X_train), y_train)# 62.8: the test set is in its original scaleprint(mean_squared_error(y_test, model.predict(X_test)))# 0.9: the same transform as in trainingprint(mean_squared_error(y_test, model.predict(scaler.transform(X_test)))) pipeline = make_pipeline(StandardScaler(), LinearRegression())pipeline.fit(X_train, y_train)# 0.9: the pipeline applies transform to new data itselfprint(mean_squared_error(y_test, pipeline.predict(X_test)))

A pipeline stores the fitted transformers and applies them to new data itself, so a step cannot be forgotten. For details, see the section “Pipelines and ColumnTransformer”.

Evaluating on the training data

The score on the training data is high even for a mediocre model, because the model has memorised those samples. model.score(X, y) on the whole dataset measures memory, not quality on new data. A reliable estimate comes from a held-out test set or from cross-validation.

pythonevaluating on the training data
from sklearn.datasets import make_classificationfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import train_test_split X, y = make_classification(random_state=0)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)model = RandomForestClassifier(random_state=0).fit(X_train, y_train)print(model.score(X_train, y_train))# 1.0: the training part is memorisedprint(model.score(X_test, y_test))# 0.92: the honest score on the held-out test set

The other side of the same sin is reusing the test set. The test set must not be used to choose a model: every iteration of “look at the score, change something” mixes test information into the decision, and the test set stops being an honest check. The right way is to set the test set aside once, and to do training and tuning on the training part with cross-validation, as the selection in the section “Cross-validation and hyperparameter tuning” does.

Accuracy on imbalanced classes

When classes are imbalanced, a model that always predicts the frequent class gets high accuracy. A baseline DummyClassifier(strategy="most_frequent") scores 0.99 accuracy when the positive class is 1% of the data, and finds not a single positive sample.

pythonaccuracy on a rare class
from sklearn.metrics import accuracy_score, balanced_accuracy_score # 1% positives: 990 zeros and 10 onesy_true = [0] * 990 + [1] * 10# the model always answers class 0y_pred = [0] * 1000print(accuracy_score(y_true, y_pred))# 0.99: same as the most-frequent-class baselineprint(balanced_accuracy_score(y_true, y_pred))# 0.5: the level of random guessing

The warning sign is accuracy close to the share of the frequent class while recall for the rare class is low. Use class-sensitive metrics: balanced_accuracy_score, f1_macro, and recall for the rare class, the one the model was built to find. A table of metrics is in the section “Evaluation and metrics”.

Randomness without random_state

KFold(shuffle=True), RandomForestClassifier and other random objects without random_state give a different result on every run: the splits and models differ, so a conclusion like “model A is better than model B” cannot be reproduced.

An integer random_state makes fit and split identical on every call. None (the default) uses numpy’s global random state. For a reproducible result, the documentation advises removing every random_state=None and setting a number explicitly.

pythona repeatable run
from sklearn.datasets import make_classificationfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import KFold, cross_val_score X, y = make_classification(random_state=0)cv = KFold(n_splits=5, shuffle=True, random_state=0)model = RandomForestClassifier(n_estimators=100, random_state=0)# the split is fixed: a second run gives the same numbersprint(cross_val_score(model, X, y, cv=cv).mean())  # 0.93

A subtlety: the splitter always needs an integer, so that folds are comparable between models. For a random estimator under cross-validation, a RandomState object is more useful: each fold gets its own initialisation, and the score is less dependent on a lucky number. Detailed rules are in the section “Cross-validation and hyperparameter tuning”.

Feature scale for distance-based models

KNeighborsClassifier, KMeans and penalised linear models compare features on a common scale. The feature with the largest values dominates the distances: on data with features of different scales, the accuracy of nearest neighbours drops from 0.94 to 0.66. Trees and boosting are not sensitive to scaling.

pythonscale for nearest neighbours
from sklearn.datasets import make_classificationfrom sklearn.model_selection import train_test_splitfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScaler X, y = make_classification(    n_samples=500, n_features=5, scale=[1, 1, 1, 1, 100],    random_state=1)X_train, X_test, y_train, y_test = train_test_split(    X, y, random_state=1)print(KNeighborsClassifier().fit(    X_train, y_train).score(X_test, y_test))# 0.66: the fifth feature is 100 times larger than the rest scaled = make_pipeline(StandardScaler(), KNeighborsClassifier())print(scaled.fit(X_train, y_train).score(X_test, y_test))# 0.94: features on the same scale

The rule: if a model relies on distances, or on feature values in its loss function, put StandardScaler first in the pipeline. For choosing a scaler, see the section “Pipelines and ColumnTransformer”.

Loading a model from an untrusted file

A saved model is an executable file. Formats based on pickle — pickle itself, joblib and cloudpickle — run arbitrary code from the file when it is loaded: loading someone else’s model is the same as running someone else’s program with your user’s privileges.

pythonchecking before loading
import skops.io as sio unknown = sio.get_untrusted_types(file="model.skops")# review the list: load only if everything looks familiarmodel = sio.load("model.skops", trusted=unknown)

The second limitation is the environment: loading a model trained with a different version of scikit-learn or numpy is not supported, and the result may be wrong or the process may crash. Store the dependency versions together with the model file. Saving formats are covered in the cheat sheet, and what changes between versions in the section “Versions and what’s new”.

Summary

MistakeHow it shows upThe right way
leakage: fit on all the datascore is inflated, performance in production is worsesplit before any fit; transform on the test set
different preparation for training and predictionerrors on new data are unexpectedly largescaling inside a Pipeline
evaluating on the training datathe model fails on new datacross-validation, a held-out test set
the test set is reused for tuningthe test score rises with every iterationtune with cross-validation, use the test set once
accuracy on imbalanced classesaccuracy is close to the share of the frequent classbalanced_accuracy_score, f1_macro, recall
randomness without random_statethe result changes on every runset a number in KFold and in estimators
distance-based models without scalingthe largest feature dictates the distancesStandardScaler as the first pipeline step
loading someone else’s pickle filearbitrary code execution, data lossskops.io with a check, ONNX

A checklist before you hand in your work: the split comes before the first fit; training and prediction go through one pipeline; evaluation is not done on the training data; the metric is sensitive to the rare class; random_state is set; the model file comes from a trusted source.

Section sources

the section is written from these pages

Versions and what’s new

This reference describes scikit-learn 1.9: the latest release of the branch is 1.9.1, from 11 September 2026. Major and minor releases come out twice a year, usually in May and November; patch fixes appear as needed and only for the latest branch.

BranchFirst releaseLatest release
1.91.9.0 — 2 June 20261.9.1 — 11 September 2026
1.81.8.0 — 10 December 20251.8.0 — 10 December 2025
1.71.7.0 — 6 June 20251.7.2 — 9 September 2025

The project does not publish support periods: scikit-learn is an open-source project maintained by volunteers. The table shows that a previous branch stops receiving patches around the time the next one is released, so update regularly within a branch. The minimum Python version for the branch is 3.11.

What changed in 1.9

The main changes in 1.9 compared with 1.8:

  • Supervised learning: experimental callbacks — objects attached with set_callbacks that fire at key steps of fit. The built-in ones are ProgressBar and ScoringMonitor; they are supported by LogisticRegression (only with solver="lbfgs"), GridSearchCV, RandomizedSearchCV, the experimental HalvingGridSearchCV and HalvingRandomSearchCV, Pipeline and StandardScaler. See the section “Supervised learning”.
  • Pipelines and ColumnTransformer: the HTML representation of estimators gained a “Fitted attributes” table listing all attributes after fit, and transformers show blocks with the number and names of output features. See the section “Pipelines and ColumnTransformer”.
  • Evaluation and metrics: the metric_at_thresholds function computes any binary metric across all decision thresholds, which helps you choose a threshold from a plot. See the section “Evaluation and metrics”.
  • Sparse array setting: the sparse_interface configuration key selects what functions and transformers return, either SciPy sparse matrices (the default) or sparse arrays (sparray). See the section “Data, features and splitting”.

Other things worth knowing. A lightweight narwhals library has appeared among the dependencies, and polars support now goes through it, because the __dataframe__ protocol is deprecated in polars. LogisticRegression gained Array API support and trains faster on float32 data without converting it to float64.

Deprecated and removed

These are the API Change announcements from the 1.9 changelog: the items below still work, with a warning, and will be removed in 1.11:

  • The criterion="friedman_mse" quality criterion in trees and forests (DecisionTreeRegressor, ExtraTreeRegressor, RandomForestRegressor, ExtraTreesRegressor): the implementation behaved like squared_error, so write criterion="squared_error". In GradientBoosting*, the criterion parameter itself is deprecated.
  • The probability parameter of SVC and NuSVC is not thread-safe. The replacement is CalibratedClassifierCV with ensemble=False. See the section “Supervised learning”.
  • The shuffle and random_state parameters of TargetEncoder: shuffling is now set by the cross-validation generator in cv. See the section “Data, features and splitting”.
  • Passing pos_label and sample_weight positionally to confusion_matrix_at_thresholds, and sample_weight to LogisticRegressionCV.score, is deprecated: pass these parameters by name.
  • The n_alphas parameter of lasso_path and enet_path: the number of points on the path is now passed in alphas.

There is no change of default values in 1.9, but one is planned for 1.11: in LogisticRegressionCV, scoring will become "neg_log_loss" instead of accuracy, which will also affect its score method. The 1.9 changelog has no security updates: no CVE entries appeared in 1.9.0 or 1.9.1.

How to upgrade

Patch releases within a branch are installed with the same pip in the project environment (see the section “Installation and first run”). The risk to your code is small, but check deprecation warnings before moving to a new branch.

bashin the project environment
source .venv/bin/activatepip install "scikit-learn==1.9.*"# show hidden deprecation warnings while checking your codepython -W default::DeprecationWarning your_script.py

Move to the next branch, 1.10, after 1.9.1 and a clean run with no warnings. On the usual schedule it is expected in late 2026. There are no new removals in 1.9, but in 1.10 the deferred deprecations from earlier branches take effect: the PassiveAggressiveClassifier and PassiveAggressiveRegressor classes and the penalty parameter of LogisticRegression and LogisticRegressionCV will disappear, and the shape of LogisticRegressionCV attributes will change. SVC with probability=True still works with a warning and will be removed in 1.11.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 4 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Manual edit

    reason: manual edit
  4. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

18 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Machine learning basics” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61