Sub topic 1
The estimator API: fit, predict, transform
Prerequisites
Assume you know basic Python, NumPy or pandas, supervised learning, and train/test splits. An estimator is a scikit-learn object that learns from data. Most estimators follow a small API:
fit(X, y)learns from featuresXand labelsy.predict(X)produces predictions for new rows.transform(X)changes features and is used by a transformer, an estimator that prepares data.fit_transform(X)learns the transformation and applies it in one operation.
A classifier usually has fit and predict. A scaler, imputer, or encoder usually has fit and transform.
Transformers: scaling, imputing, and encoding
StandardScaler centers numeric columns and scales them to comparable ranges. SimpleImputer fills missing values, such as with a column median. OneHotEncoder converts categories into indicator columns, such as city_Oslo and city_Bergen.
Transformers learn statistics during fit. For example, a scaler learns a mean and standard deviation. It then reuses those values during transform.
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
X = [[10.0], [20.0], [None]]
imputer = SimpleImputer(strategy="mean")
scaler = StandardScaler()
X_filled = imputer.fit_transform(X)
X_scaled = scaler.fit_transform(X_filled)
print(X_scaled)Why preprocessing outside a pipeline leaks information
Data leakage occurs when information from evaluation data influences training. For example, fitting a scaler on the complete dataset lets the test rows affect the mean and standard deviation. The model then receives information it would not have at prediction time.
Fit preprocessing only on training data. A pipeline makes this rule easier to enforce, especially during cross-validation, where each fold needs its own fitted transformer.
flowchart TD
A[Raw training features] --> B[Fit scaler]
B --> C[Transform training features]
D[Raw test features] --> E[Use same fitted scaler]
E --> F[Transform test features]
C --> G[Fit classifier]
F --> H[Predict]Building your first Pipeline
A Pipeline chains steps. Every step except the last must be a transformer. The final step is normally a predictor.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000)
)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))The pipeline fits the scaler before fitting the classifier. Later, model.predict(X_test) applies the fitted scaler automatically.
Exercise
Which method should a fitted scaler use on test features?
Show answer
transform, because its settings must come only from the training features.