◆ AI All-in-One

Level 3 In-Depth AI · Programming and Tools

scikit-learn

The standard Python library for classical machine learning. Every model shares the same fit/predict interface, and pipelines chain cleaning, preprocessing and modelling into one object you can cross-validate and tune. Ends with a complete project.

Level
●●●●● Easy
Reading
10 min
To learn it well
1.5 hours to read, a weekend for a first project
↗ Plan a path here

Read first

NumPy and Array ThinkingPandas and Working with DataSupervised Learning

This leads to

—
The full path from zero — 9 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Python for AI
  4. How Machines Learn
  5. Matrices and Matrix Multiplication
  6. Pandas and Working with Data
  7. Supervised, Unsupervised and Reinforcement Learning
  8. NumPy and Array Thinking
  9. Supervised Learning
  10. scikit-learn

Read them roughly in this order. See it on the concept map →

Why it matters

Not every AI problem needs a neural network. A great deal of valuable machine learning works on tables: customer records, medical measurements, sensor logs, loan applications. For tabular data, classical methods such as logistic regression, random forests and gradient boosting are often as accurate as deep learning, far faster to train and much easier to explain.

scikit-learn (imported as sklearn) is the Python library for these methods. It contains dozens of algorithms for classification, regression, clustering and dimensionality reduction, plus all the tools around them: splitting data, preprocessing, cross-validation, hyperparameter search and evaluation metrics. Its biggest strength is consistency. Every model is used in exactly the same way, so once you know how to use one you know how to use them all, and swapping a linear model for a random forest is a one-line change.

Even if you end up working mainly with PyTorch or LLMs, you will keep using scikit-learn for splitting data, computing metrics, quick baselines and PCA. Its design ideas, such as fit and predict and pipelines, have been copied by many other libraries.

The intuition

Think of every scikit-learn model as an apprentice with two moves:

  1. fit(X, y): study these examples and their answers, and learn whatever is needed. For a linear model that means weights. For a decision tree it means a set of questions.
  2. predict(X): given new examples, produce answers using what was learned.

Every object that learns from data is called an estimator. Some estimators don't predict answers but change the data instead. A scaler learns each column's mean and spread during fit and then rescales data during transform. These are called transformers (nothing to do with the Transformer neural network).

The crucial rule is that everything is learned from the training data only, and then applied unchanged to new data. Even the mean used to fill in missing ages is "learned", and must come from the training set. A pipeline packages the whole chain, from filling gaps and scaling to the model itself, into one estimator, so this rule is enforced automatically.

Pipeline: one estimator SimpleImputer fills gaps learns: medians StandardScaler rescales learns: means, stds LogisticRegression the model learns: weights training data X_train, y_train fit(): every step learns new data X_test predict(): reuses what fit() learned predictions y_pred test data never influences what the steps learn
Fig. 1 A scikit-learn pipeline. During fit, each step learns its parameters (medians, means and standard deviations, model weights) from the training data only. During predict, new data flows through the same steps using those stored parameters, without learning anything.

How it works

The data format

scikit-learn expects:

  • X: the features, a 2-D array or DataFrame with shape (n_samples, n_features), one row per example and one column per feature.
  • y: the targets, a 1-D array with shape (n_samples,), the label or value for each row.

A first model in six lines

The breast-cancer dataset that ships with scikit-learn has 569 tumour samples, each described by 30 numeric measurements and labelled malignant (0) or benign (1).

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline

X, y = load_breast_cancer(return_X_y=True)
print(X.shape)                                  # (569, 30)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=0, stratify=y)

model = make_pipeline(StandardScaler(), LogisticRegression())
model.fit(X_train, y_train)
model.predict(X_test[:5])                       # [1 0 0 1 0]   (true: [1 0 0 1 0])
model.predict_proba(X_test[:2]).round(3)        # [[0.004 0.996]
                                                #  [1.    0.   ]]
model.score(X_test, y_test)                     # 0.958   accuracy on unseen data

train_test_split holds back a quarter of the data that the model never sees during training. That is the only honest way to measure performance (see Training, Validation and Test Sets). stratify=y keeps the proportion of each class the same in both parts. random_state fixes the shuffle so results are repeatable. predict_proba gives the model's probability for each class, which is often more useful than the hard decision.

Is 95.8% good? Always compare with a baseline, the score of a trivially simple strategy. DummyClassifier(), which always predicts the most common class, scores 0.629 on the same test set. The model is far better than doing nothing clever.

Preprocessing

Real data needs preparing. The most common steps:

  • Scaling. StandardScaler subtracts each column's mean and divides by its standard deviation. Models based on distances or gradients, such as k-Nearest Neighbours, SVMs and logistic regression, need it. Tree models don't care.
  • Imputation. SimpleImputer fills missing values with the median, mean or most frequent value, learned from the training data. Filling in missing values like this is called imputation.
  • One-hot encoding. Models need numbers, not words. OneHotEncoder turns a column like embarked with values S, C and Q into three 0/1 columns, one per category. This is one-hot encoding. It avoids pretending that categories have an order, as replacing them with 1, 2, 3 would.

Different columns need different treatment. A ColumnTransformer applies one recipe to the numeric columns and another to the categorical ones, then glues the results together.

Pipelines

A pipeline chains transformers and a final model into one estimator. Calling pipe.fit(X, y) fits each step in turn on the training data, passing the transformed output along. Calling pipe.predict(X_new) pushes new data through the same fitted steps. There are two big benefits:

  1. No data leakage. Preprocessing statistics are always computed on the training portion only, even inside cross-validation.
  2. One object to save and deploy. The whole recipe, from raw columns to prediction, travels together. Deploying Models relies on this.

A single train/test split gives a noisy estimate. Cross-validation is more reliable. It splits the training data into kk parts (folds), trains kk times, each time holding out a different fold for evaluation, and averages the kk scores.

training set (80%) test set (20%) round 1 score train train train train untouched 0.81 round 2 train score train train train untouched 0.79 round 3 train train score train train untouched 0.84 round 4 train train train score train untouched 0.80 round 5 train train train train score untouched 0.83 mean 0.814 each round: fit on 4 folds, score on the 5th scores shown are illustrative
Fig. 2 Five-fold cross-validation. The training data is split into five folds. Each round trains on four and scores on the fifth, so every example is used for evaluation exactly once. The test set is kept aside the whole time, for one final check.

Most models have hyperparameters, settings you choose rather than learn, such as the maximum depth of a tree. Grid search tries every combination from a grid of candidate values, cross-validates each, and keeps the best. GridSearchCV does all of this and then refits the best pipeline on the full training set. Inside a pipeline, a step's hyperparameter is named stepname__parameter, with a double underscore.

Metrics

model.score returns accuracy for classifiers and R2R^2 for regressors, but you usually want more. sklearn.metrics contains them all: accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, confusion_matrix, mean_squared_error and classification_report, which prints several at once. Evaluation Metrics explains when to use which.

Key idea In scikit-learn every model is an estimator with fit and predict. Put all preprocessing inside a pipeline, choose models by cross-validation on the training set, and touch the test set once, at the very end.

In code

A complete end-to-end project on the Titanic passenger data from the Pandas and Working with Data chapter: predict who survived from class, sex, age, family and fare. It handles missing values and text columns, compares two models by cross-validation, tunes the better one with a grid search and reports final test results.

import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

url = "https://raw.githubusercontent.com/mwaskom/seaborn-data/master/titanic.csv"
df = pd.read_csv(url)
X = df[["pclass", "sex", "age", "sibsp", "parch", "fare", "embarked"]]
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y)

numeric = ["age", "sibsp", "parch", "fare"]
categorical = ["pclass", "sex", "embarked"]
prep = ColumnTransformer([
    ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
    ("cat", make_pipeline(SimpleImputer(strategy="most_frequent"),
                          OneHotEncoder(handle_unknown="ignore")), categorical),
])

for name, clf in [("logistic", LogisticRegression()),
                  ("forest", RandomForestClassifier(random_state=0))]:
    pipe = Pipeline([("prep", prep), ("model", clf)])
    scores = cross_val_score(pipe, X_train, y_train, cv=5)
    print(f"{name:9s} CV accuracy {scores.mean():.3f} ± {scores.std():.3f}")

pipe = Pipeline([("prep", prep), ("model", RandomForestClassifier(random_state=0))])
grid = GridSearchCV(pipe, {"model__max_depth": [3, 5, 8, None],
                           "model__min_samples_leaf": [1, 5]}, cv=5)
grid.fit(X_train, y_train)
print("best:", grid.best_params_, f"CV {grid.best_score_:.3f}")
print(f"test accuracy {grid.score(X_test, y_test):.3f}")
print(classification_report(y_test, grid.predict(X_test), digits=3))

Output:

logistic  CV accuracy 0.798 ± 0.019
forest    CV accuracy 0.796 ± 0.049
best: {'model__max_depth': 5, 'model__min_samples_leaf': 5} CV 0.823
test accuracy 0.804
              precision    recall  f1-score   support

           0      0.782     0.945     0.856       110
           1      0.870     0.580     0.696        69

    accuracy                          0.804       179
   macro avg      0.826     0.763     0.776       179
weighted avg      0.816     0.804     0.794       179

How to read it. The untuned forest is no better than logistic regression, and its scores vary more between folds. Limiting the tree depth to 5 and requiring at least 5 passengers per leaf, which reins in Overfitting and the Bias–Variance Tradeoff, lifts cross-validated accuracy to 0.823. On the untouched test set the tuned model gets 0.804, a little below the cross-validation estimate, which is normal. The baseline of predicting "did not survive" for everyone would score about 0.615, since 110 of the 179 test passengers died. The report also shows the model's weak spot: its recall for survivors (class 1) is only 0.58. It misses 42% of the people who survived, while rarely raising a false alarm.

Common pitfalls

  • Fitting preprocessing on all the data. Calling StandardScaler().fit(X) before splitting lets test-set statistics leak into training. Put preprocessing inside the pipeline and split first.
  • Tuning on the test set. If you try twenty settings and keep the one with the best test score, the test score is no longer an honest estimate. Tune with cross-validation on the training set and use the test set once.
  • Forgetting to scale. Logistic regression, SVMs and k-nearest neighbours can perform badly or converge slowly on unscaled features. Watch for a ConvergenceWarning.
  • Accuracy on imbalanced data. If 99% of transactions are legitimate, a model that never predicts fraud is 99% accurate and useless. Look at precision, recall and the confusion matrix.
  • Unseen categories. A category in new data that never appeared in training crashes a default OneHotEncoder. Use handle_unknown="ignore", as above.
  • Shapes. y must be 1-D. Passing a one-column DataFrame produces a DataConversionWarning. Use df["col"], not df[["col"]].

Watch out The most common way to fool yourself in machine learning is data leakage: information from the test set, or from the future, sneaks into training. Typical causes are preprocessing before splitting, duplicate rows that land on both sides of the split, and features that are only known after the outcome (such as "number of days in hospital" when predicting admission). Leaked models look excellent in testing and fail in real use.

Where it leads

A bit of history

scikit-learn began in 2007 as a Google Summer of Code project by David Cournapeau, as an add-on ("scikit") to the SciPy library. In 2010 researchers at INRIA, the French national computing research institute, including Fabian Pedregosa, Gaël Varoquaux, Alexandre Gramfort and Vincent Michel, took it over and made the first public release. The 2011 paper "Scikit-learn: Machine Learning in Python" in the Journal of Machine Learning Research became one of the most cited papers in machine learning. A 2013 paper on its API design set out the estimator, transformer and pipeline conventions used above, which have shaped many later libraries. Version 1.0 was released in 2021.

Try it

  1. In the Titanic project, add a third model to the comparison loop, GradientBoostingClassifier() from sklearn.ensemble. Does it beat the forest?
  2. Remove "sex" from the features and rerun. How much does cross-validated accuracy drop? What does that tell you about which features matter?
  3. Harder: deliberately cause leakage. Fit a StandardScaler and SimpleImputer on all of X before splitting, then train. Is the score different? On this small dataset the difference may be tiny. Explain why leakage still matters.

Hint for 2: drop it from both the X = df[[...]] line and the categorical list.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You call StandardScaler().fit(X) on the full dataset, then split into train and test. What is wrong?

  2. You try 20 hyperparameter settings and keep the one with the best test-set score. What is the problem?

  3. A fraud model is 99% accurate on data where 99% of transactions are legitimate. What should you check?

  4. Why use one-hot encoding for a column like embarked with values S, C and Q, instead of replacing them with 1, 2 and 3?

  5. In a Pipeline with a step named "model", how do you name the RandomForest's max_depth in a GridSearchCV grid?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

scikit-learn User Guide

scikit-learn · Intermediate · Free

Excellent documentation that doubles as a textbook, with explanations and examples for every algorithm.

Docs

scikit-learn: Getting Started

scikit-learn · Beginner · Free

A one-page tour of estimators, fit and predict, transformers, pipelines, cross-validation and parameter search.

Book

Hands-On Machine Learning (code notebooks)

Aurélien Géron · Beginner · notebooks free, book paid

A very practical bestselling book that covers scikit-learn through deep learning. All of its notebooks are free on GitHub.

Book

Python Data Science Handbook

Jake VanderPlas · 2016 · Beginner · Free

Free online book covering IPython and notebooks, NumPy, pandas, Matplotlib and scikit-learn, every chapter a runnable notebook.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/scikit-learn.md