Home β€Ί Curriculum β€Ί Machine Learning with scikit-learn
Updated for Python 3.12+ Β· November 2026

🧠 Machine Learning with scikit-learn
in Python

Learn scikit-learn step by step: train/test split, classification, regression, pipelines, cross-validation, metrics, overfitting, grid search and feature importance.

Advanced 9 lessonsβ‰ˆ 54 min read by Glenn Pansensoy

What this lesson is about

scikit-learn is the library most people reach for when they want to do classical machine learning in Python. It gives you dozens of models, such as logistic regression, decision trees, random forests and k-nearest neighbours, behind one very consistent interface. You can predict whether an email is spam, estimate a house price from its features, or group customers by behaviour, and the code for each looks almost the same.

That consistency is the real lesson. Almost every object in scikit-learn follows the same few verbs: fit learns from data, predict makes predictions, transform changes data, and score gives a quick quality number. Once you know that rhythm, a new model is a one-line change. What takes practice is the discipline around the code: splitting data honestly, scaling without leaking information, measuring with the right metric and noticing when a model has only memorised its training set.

I have arranged this page as a realistic workflow. We split data, train a classifier, fit a regressor, build a pipeline, validate with cross-validation, read a confusion matrix, watch overfitting happen on purpose, tune a model with a tiny grid search, and finally inspect feature importance and learn how models are saved. Every runnable example works in your browser through Pyodide, uses a fixed random_state so you get the same numbers I did, and prints rounded values rather than long model descriptions.

What you will learn

  • βœ“Follow the fit, predict, score pattern shared by every estimator
  • βœ“Split data into training and test sets and explain why that matters
  • βœ“Train a classifier and a regressor and read their results
  • βœ“Scale features and chain steps safely with a Pipeline
  • βœ“Estimate real-world performance with cross-validation
  • βœ“Read accuracy, precision, recall, F1 and a confusion matrix
  • βœ“Recognise overfitting and control it with model settings
  • βœ“Tune hyperparameters with GridSearchCV and inspect feature importance

Why programmers should learn this

  • β˜…Many real business problems, such as churn, fraud flags or price estimates, are tabular data problems where classical models are fast to train, easy to explain and hard to beat with something fancier.
  • β˜…scikit-learn's uniform API means you can compare five different algorithms on your data in an afternoon, which is the honest way to choose one.
  • β˜…The habits you learn here, holding out a test set, avoiding leakage and choosing the right metric, apply to every machine learning tool you will ever use, including deep learning.
  • β˜…Pipelines turn a notebook experiment into something repeatable that you can hand to another person or deploy, because preprocessing and model travel together.
  • β˜…Understanding the limits of a model, for example that 95 percent accuracy can be useless on imbalanced data, protects you from making confident but wrong claims.

The estimator pattern and why we split data

Every model in scikit-learn is an estimator: an object you create with settings, then train by calling fit(X, y). X is a two-dimensional table of features with one row per example and one column per feature. y is the answer you want the model to learn, with one value per row. After fitting, predict(X_new) returns answers for rows the model may never have seen.

The most important rule in machine learning is that a model must be judged on data it did not train on. If I show a student the exam questions and then test them on those same questions, a high mark tells me nothing about understanding. So we cut the data in two with train_test_split: the training part is used for fit, the test part is locked away until we want an honest score.

Notice random_state=42 below. The split is random, and without a fixed seed you would get different rows, and slightly different scores, every time you ran the code. stratify=y asks for the class proportions to be the same in both halves, which matters when some classes are rare. I use the built-in iris dataset, 150 flowers with four measurements each and three species, because it loads instantly with no network.

python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split

data = load_iris()
X, y = data.data, data.target
print(X.shape, y.shape)
print(list(data.feature_names))
print([str(n) for n in data.target_names])

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)
print(X_train.shape, X_test.shape)
print(sorted(set(y_test.tolist())), len(y_test))
Expected output
(150, 4) (150,)
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
['setosa', 'versicolor', 'virginica']
(112, 4) (38, 4)
[0, 1, 2] 38

Line by line

  1. 1-2Import the dataset loader and the splitting helper.
  2. 4-5load_iris() returns an object holding data (the feature table) and target (the species number for every row). I name them X and y by convention.
  3. 6-8Print the shapes and the names so you know what each column and class means: 150 rows, 4 features, 3 classes.
  4. 10-12Split into 75 percent train and 25 percent test. The seed makes the split repeatable and stratify=y keeps species balanced in both parts.
  5. 13-14Check the sizes of the two parts and confirm the test set contains all three classes.
πŸ’‘

Capital X and lowercase y is a convention from mathematics: a matrix of inputs and a vector of outputs. Following it makes your code instantly readable to other people.

Your first classifier

Classification means predicting a category. I will start with k-nearest neighbours because the idea fits in one sentence: to classify a new flower, look at the k most similar flowers in the training data and take a vote. There is almost no maths to hide behind, which makes it a good first model, and the fit/predict/score code is exactly what you will write for far more complicated models.

score on a classifier returns accuracy, the fraction of predictions that were exactly right. I compute it on both the training and the test data on purpose. Training accuracy tells you how well the model fits what it has seen; test accuracy estimates how it will do on new data. The gap between the two is one of the first things I look at, and we will return to it in the overfitting section.

Notice that predict returns an array of class numbers, not names. Use data.target_names[...] to turn them back into readable labels when you show results to a person. A good habit is to print a handful of predictions next to the truth, because a single accuracy number can hide silly mistakes such as predictions that are all the same class.

python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    data.data, data.target, test_size=0.25, random_state=42, stratify=data.target
)

model = KNeighborsClassifier(n_neighbors=5)
model.fit(X_train, y_train)

print("train accuracy:", round(model.score(X_train, y_train), 3))
print("test accuracy:", round(model.score(X_test, y_test), 3))

pred = model.predict(X_test[:5])
print("predicted:", [str(data.target_names[i]) for i in pred])
print("actual:   ", [str(data.target_names[i]) for i in y_test[:5]])
Expected output
train accuracy: 0.973
test accuracy: 0.974
predicted: ['setosa', 'versicolor', 'versicolor', 'versicolor', 'setosa']
actual:    ['setosa', 'versicolor', 'versicolor', 'versicolor', 'setosa']

Line by line

  1. 1-3Import the data loader, the splitter and the k-nearest-neighbours classifier.
  2. 5-8Load the data and split it exactly as before, with a fixed seed.
  3. 10-11Create the model with n_neighbors=5 and train it. For this model, fit mostly just stores the training rows.
  4. 13-14score returns accuracy. I round it to three decimals so the output is tidy and stable.
  5. 16-18Predict the first five test flowers and convert class numbers into species names so a person can compare them with the true labels.

Regression: predicting a number

When the answer is a number rather than a category, the task is regression. The estimator pattern is identical: fit, predict, score. For regressors score returns R squared, which compares your model to the laziest possible model that always predicts the average. A value of 1.0 is perfect, 0.0 means no better than the average, and it can even go negative on test data if the model is worse than that.

To make the example transparent I create synthetic data with a known rule: price = 3 * size + 20 * rooms + 50 plus a little random noise. Because I know the truth, I can check whether LinearRegression finds it. The learned coef_ array holds one weight per feature and intercept_ holds the baseline, and they should land close to 3, 20 and 50.

Real data never comes with a known rule, but this trick is how I test a new method: if it cannot recover a pattern I planted, I should not trust it on a pattern I did not plant. For regression I also report MAE, the mean absolute error, because it is in the same units as the target: an MAE of 4 means predictions are off by about 4 price units on average, which is easier to explain than R squared.

python
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split

rng = np.random.default_rng(0)
size = rng.uniform(30, 120, 200)
rooms = rng.integers(1, 6, 200)
price = 3 * size + 20 * rooms + 50 + rng.normal(0, 5, 200)
X = np.column_stack([size, rooms])

X_train, X_test, y_train, y_test = train_test_split(X, price, test_size=0.25, random_state=1)

model = LinearRegression().fit(X_train, y_train)
print("weights:", np.round(model.coef_, 2))
print("intercept:", round(float(model.intercept_), 2))

pred = model.predict(X_test)
print("R2:", round(model.score(X_test, y_test), 3))
print("MAE:", round(mean_absolute_error(y_test, pred), 3))
Expected output
weights: [ 3.01 19.79]
intercept: 50.29
R2: 0.997
MAE: 3.931

Line by line

  1. 1-4Import NumPy, the regressor, an error metric and the splitter.
  2. 6-10Create 200 fake houses with a size and a room count, then build prices from a known rule plus noise (a standard deviation of 5). column_stack joins the two features into a table.
  3. 12Split the rows into training and test sets with a fixed seed.
  4. 14-16Fit the model (fit returns the model, so I can chain it) and print the learned weights. They should be near 3 and 20, with an intercept near 50.
  5. 18-20Predict on the held-out rows, then print R squared and the mean absolute error to see how close the predictions are.
ℹ️

The noise level limits what any model can achieve. With noise of 5, an MAE around 4 is about as good as it gets, because that noise is genuinely unpredictable.

Scaling features and building a Pipeline

Many models are sensitive to the scale of features. If one column is measured in thousands and another between 0 and 1, distance-based models such as k-nearest neighbours let the big numbers dominate. Standardisation fixes this by shifting each feature to mean 0 and spreading it to standard deviation 1. In scikit-learn that is StandardScaler, a *transformer*: it learns the mean and spread with fit, then applies them with transform.

Here is the trap that catches almost everyone. If you scale the whole dataset first and split afterwards, the test rows have quietly influenced the mean and spread, so information from the test set has leaked into training. The scaler must learn its numbers from the training data only, and then apply those same numbers to the test data. Doing this by hand is easy to get wrong.

A Pipeline solves it by chaining steps into a single estimator. Calling pipe.fit(X_train, y_train) fits the scaler on training data, transforms it, then fits the model; calling pipe.predict(X_test) applies the already-learned scaling and then predicts. The pipeline also plugs straight into cross-validation and grid search, so the leak-free behaviour is automatic. I now build a pipeline for nearly everything. The example fakes a feature on a huge scale to make the effect obvious.

python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

data = load_iris()
X = data.data.copy()
X[:, 0] = X[:, 0] * 1000   # make one feature enormous on purpose
y = data.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

plain = KNeighborsClassifier().fit(X_train, y_train)
print("without scaling:", round(plain.score(X_test, y_test), 3))

pipe = Pipeline([
    ("scale", StandardScaler()),
    ("knn", KNeighborsClassifier()),
])
pipe.fit(X_train, y_train)
print("with scaling:   ", round(pipe.score(X_test, y_test), 3))

scaler = pipe.named_steps["scale"]
print("learned means:", np.round(scaler.mean_, 1))
Expected output
without scaling: 0.684
with scaling:    0.921
learned means: [5.8777e+03 3.1000e+00 3.8000e+00 1.2000e+00]

Line by line

  1. 1-6Import everything we need, including Pipeline and StandardScaler.
  2. 8-11Load iris and multiply the first feature by 1000 so it dwarfs the others. The .copy() avoids changing the original dataset.
  3. 13-15Split the data with a fixed seed.
  4. 17-18Train a k-NN model directly on the badly scaled data. Distances are now almost entirely decided by feature 0.
  5. 20-25Build a pipeline with two named steps, scale then classify, and fit it on the training data only. The scaler learns its means from training rows alone.
  6. 27-28Reach into the fitted pipeline by step name and print what the scaler learned. Feature 0 has a mean in the thousands because of my change.
⚠️

Never call fit or fit_transform on the test set. Only call transform (or predict on a pipeline) there. This is the single most common source of over-optimistic results.

Cross-validation: a steadier estimate

A single train/test split gives one score, and that score depends on which rows happened to land in the test set. With a small dataset, a lucky or unlucky split can swing the result by several points. K-fold cross-validation reduces that luck. It cuts the data into k folds, trains on k-1 of them, tests on the remaining one, and repeats until every fold has been the test fold once. You get k scores and can look at their mean and spread.

The mean is your best estimate of future performance; the spread tells you how stable the model is. If five folds give 0.96, 0.97, 0.95, 0.96 and 0.97, I am comfortable. If they give 0.70, 0.95, 0.80, 0.99 and 0.65, the model's behaviour depends heavily on which rows it sees, and I want to find out why before trusting it.

cross_val_score does everything in one call and works with any estimator, including a full pipeline, so scaling is redone correctly inside each fold. For classification, passing cv=StratifiedKFold(...) with shuffle=True and a seed keeps class proportions in every fold and makes the result repeatable. I use cross-validation to compare candidate models, and I keep the final test set for one last check at the end.

python
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier

X, y = load_iris(return_X_y=True)
folds = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

candidates = {
    "knn": make_pipeline(StandardScaler(), KNeighborsClassifier()),
    "logreg": make_pipeline(StandardScaler(), LogisticRegression(max_iter=500)),
    "tree": DecisionTreeClassifier(random_state=0),
}

for name, model in candidates.items():
    scores = cross_val_score(model, X, y, cv=folds)
    print(name, [round(float(s), 2) for s in scores],
          "mean", round(float(scores.mean()), 3),
          "std", round(float(scores.std()), 3))
Expected output
knn [0.97, 1.0, 0.93, 0.97, 0.9] mean 0.953 std 0.034
logreg [0.97, 0.97, 0.97, 0.97, 0.93] mean 0.96 std 0.013
tree [0.97, 0.97, 0.87, 0.97, 0.9] mean 0.933 std 0.042

Line by line

  1. 1-7Import three different models, the cross-validation tools and the scaler.
  2. 9return_X_y=True gives the features and labels directly as a tuple.
  3. 10Make five stratified folds, shuffled with a seed so every run uses the same folds.
  4. 12-16Put three candidates in a dictionary. make_pipeline builds a pipeline and names the steps for me. The tree does not need scaling.
  5. 18-22Loop over the candidates, get five scores for each with cross_val_score, and print the individual scores, their mean and their standard deviation, all rounded.

Metrics beyond accuracy

Accuracy is easy to understand and often misleading. Imagine a fraud detector where only 1 transaction in 100 is fraud. A model that always says 'not fraud' is 99 percent accurate and completely useless. For problems like this you need metrics that look at each kind of mistake separately.

Start with the confusion matrix, a table where each row is the true class and each column is the predicted class. For two classes it holds four counts: true negatives, false positives, false negatives and true positives. From those come precision (of everything I flagged, how much was really positive?) and recall (of everything that was really positive, how much did I catch?). F1 is a single number combining the two, and it is low if either one is low.

Which metric matters depends on the cost of each mistake. A cancer screening test wants high recall, because missing a case is worse than a false alarm. A spam filter that hides real email wants high precision. The example builds an imbalanced dataset and shows how the lazy majority-class model looks excellent on accuracy but scores zero on recall, while a real model is honestly measured.

python
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (accuracy_score, confusion_matrix,
                             f1_score, precision_score, recall_score)
from sklearn.model_selection import train_test_split

X, y = make_classification(n_samples=1000, weights=[0.95, 0.05],
                           n_informative=4, random_state=3)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=3, stratify=y
)

def report(name, model):
    pred = model.fit(X_train, y_train).predict(X_test)
    print(name)
    print("  accuracy :", round(accuracy_score(y_test, pred), 3))
    print("  precision:", round(precision_score(y_test, pred, zero_division=0), 3))
    print("  recall   :", round(recall_score(y_test, pred), 3))
    print("  f1       :", round(f1_score(y_test, pred), 3))
    print("  matrix   :", confusion_matrix(y_test, pred).tolist())

report("always majority", DummyClassifier(strategy="most_frequent"))
report("logistic regression", LogisticRegression(max_iter=500))
Expected output
always majority
  accuracy : 0.943
  precision: 0.0
  recall   : 0.0
  f1       : 0.0
  matrix   : [[283, 0], [17, 0]]
logistic regression
  accuracy : 0.947
  precision: 0.545
  recall   : 0.353
  f1       : 0.429
  matrix   : [[278, 5], [11, 6]]

Line by line

  1. 1-6Import a data generator, a baseline model, a real model and the metric functions.
  2. 8-9make_classification fabricates a dataset where only about 5 percent of rows belong to class 1, which imitates a rare-event problem.
  3. 10-12Split with stratification so the test set also contains rare positives.
  4. 14-21A small helper that trains a model, predicts on the test set and prints the four common metrics plus the confusion matrix as a nested list. zero_division=0 avoids a warning when a model never predicts the positive class.
  5. 23-24Compare the do-nothing baseline with logistic regression. The baseline's accuracy looks fine, but its recall exposes it.
πŸ’‘

Always compare against a dummy baseline. If your clever model barely beats DummyClassifier, you have learned something important before spending days on tuning.

Overfitting: when a model memorises

A model overfits when it learns the quirks and noise of the training data instead of the general pattern. It then scores brilliantly on data it has seen and poorly on data it has not. The opposite problem, underfitting, is a model too simple to capture the pattern at all, so it does badly on both.

Decision trees make the idea easy to see. A tree allowed to grow without limit keeps splitting until every training row sits in its own pure leaf, which gives perfect training accuracy and often mediocre test accuracy. The setting max_depth limits how many questions the tree may ask in a row. A very shallow tree underfits, a very deep tree overfits, and the best test score tends to be somewhere in the middle.

I plot or print train and test scores together as a setting changes. That is a validation curve, and it is how I choose model complexity. The example uses noisy data on purpose, with 20 percent of the labels flipped, because noise is what a flexible model will happily memorise. Watch the training score climb to 1.0 while the test score stalls.

python
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier

X, y = make_classification(n_samples=600, n_features=10, n_informative=4,
                           flip_y=0.2, random_state=5)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=5
)

print("depth  train  test")
for depth in [1, 2, 3, 5, 8, None]:
    tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
    tree.fit(X_train, y_train)
    tr = round(tree.score(X_train, y_train), 3)
    te = round(tree.score(X_test, y_test), 3)
    print(f"{str(depth):>5}  {tr:.3f}  {te:.3f}")
Expected output
depth  train  test
    1  0.774  0.756
    2  0.812  0.761
    3  0.850  0.806
    5  0.879  0.800
    8  0.940  0.800
 None  1.000  0.767

Line by line

  1. 1-3Import the data generator, the splitter and a decision tree.
  2. 5-6Make 600 rows with 10 features of which only 4 matter; flip_y=0.2 randomly corrupts 20 percent of the labels to add noise.
  3. 7-9Split into train and test sets.
  4. 11Print a header for the table of results.
  5. 12-17Train one tree for each depth, where None means unlimited, and print train and test accuracy side by side. str(depth):>5 right-aligns the value in five characters.

Read the table from top to bottom. As depth grows, training accuracy heads towards 1.0 because the tree can carve out every row, but test accuracy does not follow it. That widening gap is overfitting made visible. The fixes are the ones in the table itself: limit complexity, get more data, remove useless features, or use an ensemble such as a random forest that averages many trees.

Tuning with GridSearchCV

A hyperparameter is a setting you choose before training, such as n_neighbors or max_depth, as opposed to a parameter, which the model learns itself, such as a regression weight. Choosing hyperparameters by hand is guesswork, so GridSearchCV automates it: you list candidate values, and it trains and cross-validates every combination, then keeps the best.

Keep grids small. A grid of 5 values for each of 3 settings is 125 combinations, and each is trained once per fold. Start with a coarse, tiny grid and refine around the winner. The search runs on the training data only, using cross-validation inside it; the test set stays untouched until the very end, so its score remains an honest report.

When you search over a pipeline, name the setting as stepname__parametername, with two underscores. GridSearchCV also refits the best model on all the training data by default, so search.best_estimator_ is ready to use and search.score evaluates it on the held-out set. Inspect cv_results_ too: if many combinations score almost the same, the setting does not matter much and you can pick the simplest.

python
from sklearn.datasets import load_wine
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=7, stratify=y
)

pipe = Pipeline([("scale", StandardScaler()), ("knn", KNeighborsClassifier())])
grid = {
    "knn__n_neighbors": [1, 3, 5, 9],
    "knn__weights": ["uniform", "distance"],
}

search = GridSearchCV(pipe, grid, cv=5)
search.fit(X_train, y_train)

print("best settings:", search.best_params_)
print("best CV score:", round(search.best_score_, 3))
print("test score:   ", round(search.score(X_test, y_test), 3))
print("combinations tried:", len(search.cv_results_["params"]))
Expected output
best settings: {'knn__n_neighbors': 5, 'knn__weights': 'uniform'}
best CV score: 0.963
test score:    0.956
combinations tried: 8

Line by line

  1. 1-5Import the wine dataset, the search tool, a classifier, a pipeline and the scaler.
  2. 7-10Load 178 wines with 13 chemical measurements and split them, keeping a test set aside.
  3. 12Build a scale-then-classify pipeline.
  4. 13-16Describe the grid. The double underscore targets the n_neighbors and weights settings of the step named knn. That gives 4 times 2, which is 8 combinations.
  5. 18-19Run the search with five-fold cross-validation on the training data only.
  6. 21-24Print the winning settings, their cross-validated score, the final score on the untouched test set, and how many combinations were evaluated.

Feature importance and saving a model

Once a model works, people ask why. Tree ensembles such as RandomForestClassifier expose feature_importances_, a set of numbers that add up to 1 showing how much each feature contributed to the splits. It is a quick way to see which columns matter and which you could drop. It is not a causal statement: correlated features share credit, and a feature can look important simply because it has many distinct values. Treat it as a clue to investigate, not a verdict.

The example plants a trap you can check. I build data where only the first two columns carry signal and the rest are random noise. A sensible importance ranking should put the two real columns at the top. I sort the printed result so the output is stable and easy to read.

The second half of the job is saving a trained pipeline so an application can load it later without retraining. The standard tool is joblib, which is installed alongside scikit-learn. I show it as a static example because writing model files is something you do on your own machine or server. Remember two rules: load a file only if you trust where it came from, because loading can execute code, and load it with the same scikit-learn version that saved it, because internal formats can change between releases.

python
import numpy as np
from sklearn.ensemble import RandomForestClassifier

rng = np.random.default_rng(11)
n = 400
signal_a = rng.normal(size=n)
signal_b = rng.normal(size=n)
noise = rng.normal(size=(n, 3))
y = (signal_a + 0.5 * signal_b > 0).astype(int)
X = np.column_stack([signal_a, signal_b, noise])
names = ["signal_a", "signal_b", "noise_1", "noise_2", "noise_3"]

forest = RandomForestClassifier(n_estimators=100, random_state=0)
forest.fit(X, y)

ranked = sorted(zip(names, forest.feature_importances_), key=lambda p: -p[1])
for name, score in ranked:
    print(f"{name:9s} {score:.3f}")
print("sum:", round(float(forest.feature_importances_.sum()), 3))
Expected output
signal_a  0.613
signal_b  0.250
noise_1   0.050
noise_2   0.050
noise_3   0.037
sum: 1.0

Line by line

  1. 1-2Import NumPy and the random forest, an ensemble of many decision trees.
  2. 4-10Build 400 rows. The label depends on signal_a and signal_b only, with the first counting twice as much. Three extra columns are pure noise.
  3. 11Give the columns names so the output is readable.
  4. 13-14Train a forest of 100 trees with a fixed seed.
  5. 16-19Pair each name with its importance, sort from largest to smallest, and print them. The importances add up to 1.
Saving and loading a model (run on your computer)run on your computer
import joblib
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=500))
model.fit(X, y)

joblib.dump(model, "iris_model.joblib")      # save to disk

# ... later, in your app or another script ...
loaded = joblib.load("iris_model.joblib")    # only load files you trust
print(loaded.predict([[5.1, 3.5, 1.4, 0.2]]))

Line by line

  1. 1-5Import joblib and the pieces of a small iris pipeline.
  2. 7-9Train a scaler-plus-logistic-regression pipeline on the whole dataset.
  3. 11dump serialises the entire fitted pipeline, scaler statistics included, into one file.
  4. 13-15In a different program, load restores it and predict works immediately on a new measurement, with no retraining and no manual scaling.
⚠️

A .joblib or pickle file can run arbitrary code when loaded. Never load one downloaded from an untrusted source, and record the scikit-learn version used to create it.

Common mistakes

❌ Scaling before splitting

Fitting a scaler or imputer on the full dataset lets test-set statistics leak into training and inflates your score. Put the preprocessing inside a Pipeline so it is learned from training data only.

❌ Judging a model on its training data

A model that scores 1.0 on rows it has seen can be useless on new rows. Always report a score from a held-out test set or from cross-validation.

❌ Trusting accuracy on imbalanced data

If 95 percent of the rows are one class, always guessing that class is 95 percent accurate. Check precision, recall, F1 and the confusion matrix, and compare with a dummy baseline.

❌ Forgetting random_state

Without a seed, splits, forests and shuffles change on every run, so you cannot tell whether a score changed because of your edit or because of luck. Fix the seed while you experiment.

❌ Tuning on the test set

If you try many settings and keep the one with the best test score, the test set has become part of training and the number is optimistic. Tune with cross-validation on the training data and touch the test set once.

Quick quiz

Tap an answer. I explain every one, right or wrong.

Q1. What does fit(X, y) do on an estimator?

Q2. Why do we keep a test set that the model never trains on?

Q3. What is the benefit of putting a StandardScaler inside a Pipeline?

Q4. A fraud model is 99% accurate when 99% of transactions are legitimate. What is the best conclusion?

Q5. Training accuracy is 1.00 but test accuracy is 0.72 for a deep tree. What is the most likely cause?

Q6. In a GridSearchCV over a pipeline with a step named svc, how do you refer to its C setting?

Frequently asked questions

Not really. It focuses on classical machine learning for tabular data. For neural networks on images, text or audio, use a framework such as PyTorch. Many projects use both: scikit-learn for preprocessing, baselines and evaluation, and a deep learning framework for the heavy model.

There is no single number. Simple models can work with a few hundred rows, while noisy or high-dimensional problems need far more. Cross-validation scores and learning curves, which show score against training size, tell you whether more data would help.

Start with a dummy baseline, then a simple model such as logistic regression or a random forest. Compare them with cross-validation and pick by results on your data rather than reputation.

Parameters are learned during fit, such as the weights of a linear model. Hyperparameters are chosen by you beforehand, such as the depth of a tree, and are tuned by searching and validating.

Different random seeds, different scikit-learn versions or different data splits all change numbers a little. Fix random_state, and focus on whether your conclusions, such as which model wins, stay the same.

Key takeaways

  • βœ“Every scikit-learn estimator shares fit, predict and score, so trying a new model is usually a one-line change.
  • βœ“Split your data and judge the model on rows it never trained on; use cross-validation for a steadier estimate.
  • βœ“Put scaling and other preprocessing inside a Pipeline to prevent data leakage.
  • βœ“Choose metrics to match the cost of mistakes, and always compare with a dummy baseline.
  • βœ“Overfitting shows up as a growing gap between train and test scores; limit model complexity to control it.
  • βœ“Tune with a small GridSearchCV, inspect feature importance carefully, and save trained pipelines with joblib.