Python for Machine Learning: The scikit-learn Workflow
After this lesson, you will be able to:
- Run the scikit-learn workflow: load data, split with a fixed seed, fit, predict and score
- Explain how the fit, predict and transform methods let you swap one model for another
- Scale features correctly by fitting a StandardScaler on training rows only
- Prevent leakage with a Pipeline and measure a model with cross-validation
- Write a small fit and transform class and save a trained model with joblib
Before you start
This is a bridge, not a machine learning course. It sits after NumPy, pandas and classes, and it teaches the Python side of scikit-learn. The algorithms themselves are taught in the Classical ML track, and each one is named below where you meet it.
#The scikit-learn workflow in one cell
X (one row per sample, one column per measurement) and a label vector y. Split the rows into a training part and a test part. Create a model. Call fit to learn from the training part. Call predict and score on the test part.from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
iris = load_iris()
X, y = iris.data, iris.target
print(X.shape, y.shape)
print(iris.feature_names)
print(iris.target_names)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(X_train.shape, X_test.shape)
model = DecisionTreeClassifier(max_depth=3, random_state=42)
model.fit(X_train, y_train)
print(model.predict(X_test[:5]), y_test[:5])
print(f"Accuracy: {model.score(X_test, y_test):.2%}")Output:
(150, 4) (150,)
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']
['setosa' 'versicolor' 'virginica']
(120, 4) (30, 4)
[1 0 2 1 1] [1 0 2 1 1]
Accuracy: 100.00%
test_size=0.2 holds back 20% of the rows, so 150 flowers become 120 for training and 30 for testing. random_state=42 fixes the shuffle: without it, every run splits differently and your numbers change between runs, so no one can reproduce your result. The labels are integers, 0 for setosa, 1 for versicolor and 2 for virginica; target_names maps them back to words.fit is the Decision Trees lesson's story. Here, treat fit as the step where the model learns from the training rows.#Estimators: why you can swap one model for another
fit(X, y). Models add predict(X), which returns outputs for new rows, and score(X, y), which runs predict and applies a default metric (accuracy for classifiers, R squared for regressors, which is how much of the variation the model explains). Preprocessing objects add transform(X) instead of predict. The learned numbers are stored on the object in attributes ending with an underscore, such as mean_ or coef_.Because the methods never change, a model is a replaceable part. This cell trains five different algorithms with one loop.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
models = {
"Decision Tree": DecisionTreeClassifier(max_depth=3, random_state=42),
"Logistic Regression": LogisticRegression(max_iter=200),
"Random Forest": RandomForestClassifier(n_estimators=100, random_state=42),
"SVM": SVC(),
"KNN (k=5)": KNeighborsClassifier(n_neighbors=5),
}
for name, model in models.items():
model.fit(X_train, y_train)
print(f"{name:20s} {model.score(X_test, y_test):.2%}")Five different algorithms train on the same 120 Iris rows and are scored on the same 30 test rows. How many reach 100% accuracy?
score hides, such as per-class errors.#Scaling the features, done correctly
StandardScaler: for each column it subtracts the column mean and divides by the column standard deviation. Those two numbers are learned by fit and stored as mean_ and scale_.The statistics must come from the training rows only. Fit on train, then transform both train and test with those same numbers.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
scaler = StandardScaler()
scaler.fit(X_train)
print("train mean:", scaler.mean_.round(3))
print("train std: ", scaler.scale_.round(3))
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
print("train columns centred:", abs(X_train_scaled.mean(axis=0)).max() < 1e-9)
print("scaled test mean: ", X_test_scaled.mean(axis=0).round(3))Output:
train mean: [5.809 3.062 3.727 1.183]
train std: [0.82 0.447 1.745 0.749]
train columns centred: True
scaled test mean: [ 0.208 -0.048 0.09 0.107]
The scaled training columns have mean 0 by construction (the check prints True). The scaled test columns do not, and they should not: the test rows are measured against the training yardstick, exactly as new data will be after deployment.
#The failing version
fit_transform on the test set too. It looks symmetrical, and it runs without any error.StandardScaler subtracts the column mean and divides by the column standard deviation. For a single test row (a 1 by 4 array) the standard deviation is 0, and scikit-learn replaces a zero scale with 1. What does StandardScaler().fit_transform(X_test[:1]) print?
Now the same mistake on the whole test set. A k-nearest-neighbors model predicts a row from the five training rows nearest to it by distance, so the scale of each column decides who counts as near. This mismatch lowers the score here, but a mismatch can move it either way, and the ordering mistake in the next sections raises it.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
scaler = StandardScaler().fit(X_train)
knn = KNeighborsClassifier().fit(scaler.transform(X_train), y_train)
right = scaler.transform(X_test)
wrong = StandardScaler().fit_transform(X_test)
print("single row:", StandardScaler().fit_transform(X_test[:1]))
print("test mean with its own scaler:", wrong.mean(axis=0).round(3))
print("accuracy, right:", round(knn.score(right, y_test), 4))
print("accuracy, wrong:", round(knn.score(wrong, y_test), 4))Output:
single row: [[0. 0. 0. 0.]]
test mean with its own scaler: [-0. 0. -0. 0.]
accuracy, right: 1.0
accuracy, wrong: 0.9667
#Leakage: when the test set reaches the fit
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
iris = load_iris()
X = iris.data
X_train, X_test = train_test_split(X, test_size=0.2, random_state=42)
leaky = StandardScaler().fit(X)
clean = StandardScaler().fit(X_train)
print("mean from all 150 rows:", leaky.mean_.round(3))
print("mean from 120 train rows:", clean.mean_.round(3))
print("difference:", (leaky.mean_ - clean.mean_).round(3))Output:
mean from all 150 rows: [5.843 3.057 3.758 1.199]
mean from 120 train rows: [5.809 3.062 3.727 1.183]
difference: [ 0.034 -0.004 0.031 0.016]
Scaling before the split mixes 30 test rows into those means. On Iris the numbers differ only in the second decimal place, so the score hardly moves. Leakage becomes dramatic when a step looks at the labels, and the end of the cross-validation section below shows that with numbers.
#Pipeline: the fix that cannot be forgotten
fit, predict and score. Calling fit on a pipeline fits each transformer on the training data only, passes the transformed data to the next step, and fits the model last. Calling predict only transforms.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
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
pipe = Pipeline([
("scale", StandardScaler()),
("knn", KNeighborsClassifier(n_neighbors=5)),
])
pipe.fit(X_train, y_train)
print("accuracy:", pipe.score(X_test, y_test))
print("scaler mean:", pipe.named_steps["scale"].mean_.round(3))Output:
accuracy: 1.0
scaler mean: [5.809 3.062 3.727 1.183]
fit_transform on the test set, because you never handle the scaler yourself. Since the pipeline is an estimator, it also drops into the loop from the second section: swap KNeighborsClassifier for any other model and nothing else changes.#Cross-validation in one cell
cross_val_score does this in one call, and because you pass the whole pipeline, the scaler is refitted on the four training folds each time.from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
pipe = Pipeline([
("scale", StandardScaler()),
("knn", KNeighborsClassifier(n_neighbors=5)),
])
scores = cross_val_score(pipe, X_train, y_train, cv=5)
print(scores.round(3))
print(f"mean {scores.mean():.3f}, std {scores.std():.3f}")Output:
[0.958 0.958 0.833 1. 0.917]
mean 0.933, std 0.057
The five folds disagree: one scores 0.833 and one scores 1.0. That spread is the honest message, and it is why one split is a weak basis for ranking models. Notice the cross-validation mean (0.933) is lower than the 100% on the held-out test rows; each fold here holds only 24 rows, so each number is noisy. Use the training rows for cross-validation while you compare and tune, and touch the test rows once at the end. Cross-Validation Strategies, in the Data track, covers stratified, grouped and time-ordered folds, and the Hyperparameter Tuning lesson uses this same call to pick settings.
#Leakage that inflates the score
SelectKBest(f_classif, k=20) keeps the 20 best. Doing it before cross-validation lets the held-out fold help pick the columns. make_pipeline(step, step) is a shorter way to write Pipeline([...]) that names the steps for you, and rng.integers(0, 2, size=100) makes 100 random labels of 0 or 1. The data below is 2,000 columns of pure random noise with random labels, so no model can do better than guessing.import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2000))
y = rng.integers(0, 2, size=100)
X_picked = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_picked, y, cv=5)
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=5)
print("leaky score: ", round(leaky.mean(), 2))
print("honest score:", round(honest.mean(), 2))Output:
leaky score: 0.78
honest score: 0.59
The leaky version selected columns using all 100 labels, then "validated" on the same rows. The honest one selects inside each training fold. These are example numbers from one seed on one machine. Random labels should score near 0.5, and the honest figure is close to that; the leaky figure shows 28 points of apparent skill that does not exist. Train/Val/Test and Data Leakage, in the Data track, covers more leaks, such as duplicate rows and features built from the target.
#Saving and loading a model with joblib
joblib writes a fitted object to a file and reads it back.import os
import joblib
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
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
pipe = Pipeline([("scale", StandardScaler()), ("knn", KNeighborsClassifier())])
pipe.fit(X_train, y_train)
joblib.dump(pipe, "iris-pipeline.joblib")
loaded = joblib.load("iris-pipeline.joblib")
print(loaded.predict(X_test[:5]), pipe.predict(X_test[:5]))
print("loaded accuracy:", loaded.score(X_test, y_test))
os.remove("iris-pipeline.joblib")Output:
[1 0 2 1 1] [1 0 2 1 1]
loaded accuracy: 1.0
mean_ and scale_ travel with it. Otherwise production would have to rebuild the scaling by hand.#Write your own Pipeline as a class
fit and transform. A pipeline is a class that holds a list of steps and calls those methods in order. Here is both, in about 35 lines, using NumPy for the arithmetic. One guard is worth noting: a column with zero spread (for example a single row) would divide 0 by 0 and give nan, so MiniScaler uses 1.0 as the spread there and returns zeros, as scikit-learn's StandardScaler does.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.preprocessing import StandardScaler
class MiniScaler:
"""Learn a mean and spread per column in fit, apply them in transform."""
def fit(self, X, y=None):
self.mean_ = X.mean(axis=0)
std = X.std(axis=0)
self.scale_ = np.where(std == 0, 1.0, std) # zero spread: avoid 0/0
return self
def transform(self, X):
return (X - self.mean_) / self.scale_
class MiniPipeline:
"""Run transformers in order, then one final model."""
def __init__(self, steps):
self.steps = steps # a list of (name, object) pairs
def fit(self, X, y):
for name, step in self.steps[:-1]:
X = step.fit(X, y).transform(X)
self.steps[-1][1].fit(X, y)
return self
def predict(self, X):
for name, step in self.steps[:-1]:
X = step.transform(X)
return self.steps[-1][1].predict(X)
def score(self, X, y):
return float((self.predict(X) == y).mean())
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.2, random_state=42
)
mine = MiniPipeline([("scale", MiniScaler()), ("knn", KNeighborsClassifier())])
mine.fit(X_train, y_train)
print("accuracy:", mine.score(X_test, y_test))
reference = StandardScaler().fit(X_train)
same = np.allclose(reference.transform(X_test), mine.steps[0][1].transform(X_test))
print("matches StandardScaler:", same)Output:
accuracy: 1.0
matches StandardScaler: True
fit closely. Every step except the last is fitted and then used to transform, and the last step is only fitted. predict never calls fit, so test data cannot change what the scaler learned. That one rule is the whole leakage protection. fit returns self so calls chain, as in step.fit(X, y).transform(X).Pipeline clones steps, validates names and supports get_params. When you write a transformer for use inside it, subclass BaseEstimator and TransformerMixin from sklearn.base: they add get_params, set_params and a free fit_transform.#Common mistakes
Beyond the preprocessing mistakes above, two more come up constantly.
This code scales the test rows with their own statistics. The model scores 0.9667 when it should score 1.0. Fix it so the test rows use the training statistics.
1.0
#Try it
MiniMinMax should rescale each column to the range 0 to 1 using the training minimum and range, then plug into MiniPipeline in place of MiniScaler.Tests: Expected output: test accuracy: 1.0, then test min and max: 0.0 1.059. If the maximum is exactly 1.0, check that transform uses the training min_ and range_ and does not refit on the test rows.
#Recap
fit, and models add predict and score while preprocessing objects add transform, so one loop can train any of them.A scaler must learn its mean and standard deviation from training rows only, then transform both parts. Fitting on the test rows is a train/test mismatch. Fitting on everything before the split is leakage, and it gets worse when a step looks at the labels.
Pipeline removes the choice: it fits on training data and only transforms at predict time. cross_val_score gives several scores instead of one, and joblib saves the whole fitted pipeline, but only load files you trust. A pipeline is a plain class that calls fit and transform in order, which you just wrote in about 35 lines.#Going further
ColumnTransformer and one-hot encoding, covered in "Categorical Encoding". Choosing metrics is in "Model Evaluation & Selection".A teammate writes X_scaled = StandardScaler().fit_transform(X) and then calls train_test_split(X_scaled, y). What is the precise problem?