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
- Builds on
- 9 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 9 concepts before this one
- What Is AI?
- Vectors
- Python for AI
- How Machines Learn
- Matrices and Matrix Multiplication
- Pandas and Working with Data
- Supervised, Unsupervised and Reinforcement Learning
- NumPy and Array Thinking
- Supervised Learning
- 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:
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.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.
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.
StandardScalersubtracts 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.
SimpleImputerfills 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.
OneHotEncoderturns a column likeembarkedwith 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:
- No data leakage. Preprocessing statistics are always computed on the training portion only, even inside cross-validation.
- One object to save and deploy. The whole recipe, from raw columns to prediction, travels together. Deploying Models relies on this.
Model selection: cross-validation and grid search
A single train/test split gives a noisy estimate. Cross-validation is more reliable. It splits the training data into parts (folds), trains times, each time holding out a different fold for evaluation, and averages the scores.
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 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
fitandpredict. 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. Usehandle_unknown="ignore", as above. - Shapes.
ymust be 1-D. Passing a one-column DataFrame produces aDataConversionWarning. Usedf["col"], notdf[["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
- The algorithms in the ML part of this guide, such as Linear Regression, Decision Trees, Random Forests and Bagging, Support Vector Machines and k-Means Clustering, all have scikit-learn implementations with this interface.
- For the strongest results on tabular data, gradient-boosting libraries such as XGBoost, LightGBM and CatBoost offer scikit-learn-compatible estimators. See Gradient Boosting: XGBoost and LightGBM.
- Hyperparameter Tuning goes beyond grid search, to random search and Bayesian optimisation.
joblib.dump(grid.best_estimator_, "model.joblib")saves a fitted pipeline. Deploying Models covers serving it.- When the data are images, audio or text, move on to PyTorch.
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
- In the Titanic project, add a third model to the comparison loop,
GradientBoostingClassifier()fromsklearn.ensemble. Does it beat the forest?- Remove
"sex"from the features and rerun. How much does cross-validated accuracy drop? What does that tell you about which features matter?- Harder: deliberately cause leakage. Fit a
StandardScalerandSimpleImputeron all ofXbefore 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 thecategoricallist.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
scikit-learn User Guide
Excellent documentation that doubles as a textbook, with explanations and examples for every algorithm.
scikit-learn: Getting Started
A one-page tour of estimators, fit and predict, transformers, pipelines, cross-validation and parameter search.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
Hands-On Machine Learning (code notebooks)
A very practical bestselling book that covers scikit-learn through deep learning. All of its notebooks are free on GitHub.
Kaggle Learn: Intro to Machine Learning
A short hands-on course that builds your first scikit-learn models on real data, with validation and random forests.
Python Data Science Handbook
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