Sub topic 1
Start with the Question: What Are You Predicting and Why?
Prerequisites
Assume you know basic Python, pandas, supervised learning, and scikit-learn’s fit and predict interface. You should understand features, labels, and train/test splits.
Define the prediction task
Start with the decision the model will support. A target is the value you want to predict.
- Classification predicts a category, such as whether a customer will cancel.
- Regression predicts a number, such as next month’s revenue.
The decision determines the data split, metric, and acceptable errors. For example, a fraud detector may prioritize finding fraud, while a loan system may prioritize calibrated risk estimates.
What makes tabular data different
Tabular data stores observations in rows and variables in columns. Columns often mix numeric values, categories, missing values, and different measurement scales.
This mix creates preprocessing work. Numeric columns may need imputation, which fills missing values. Categorical columns need encoding, which converts labels such as "west" into numeric features. Some models also benefit from scaling numeric values to comparable ranges.
Choose a metric that matches the goal
A metric turns model predictions into a score.
| Goal | Useful metric |
|---|---|
| Penalize large regression errors | Mean absolute error or root mean squared error |
| Balance classification errors | Accuracy or F1 score |
| Rank positive cases | ROC AUC or average precision |
Accuracy can hide poor performance when one class is rare. Choose the metric before comparing models. Otherwise, you may select a model that optimizes a score unrelated to the real decision.
Validate without leakage
Validation estimates performance on unseen data. Cross-validation repeatedly splits the data into training and validation folds.
Data leakage occurs when information from a validation fold influences training. Fitting an imputer or scaler on the complete dataset before cross-validation is leakage. The validation fold has then affected preprocessing statistics.
A pipeline keeps preprocessing inside each fold:
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 300
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50_000, 15_000, n),
"city": rng.choice(["east", "west", "north"], n),
})
X.loc[rng.choice(n, 20, replace=False), "income"] = np.nan
y = ((X["age"] > 45) & (X["city"] == "west")).astype(int)
preprocess = ColumnTransformer([
("num", make_pipeline(
SimpleImputer(strategy="median"), StandardScaler()
), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(f"ROC AUC: {scores.mean():.3f} +/- {scores.std():.3f}")Exercise
Why should a scaler be inside the cross-validation pipeline instead of fitted before cross-validation?
Show answer
Fitting it before cross-validation lets validation-fold values influence the scaling statistics, causing data leakage and an overly optimistic score.