Sub topic 2
Turning Columns into Model Inputs
Assume you know basic Python, pandas-style tables, mean and variance, and the idea of supervised learning. This chapter uses scikit-learn.
Turning columns into model inputs
A feature is an input column used to make a prediction. The target is the value the model learns to predict. Do not include the target in the feature table.
Numeric features can usually enter a model directly. Categorical features contain labels such as "basic" or "premium". One-hot encoding converts each category into a separate zero-or-one column. Missing values need an imputation rule, such as replacing a numeric value with the training median.
| Column kind | Common treatment | Example |
|---|---|---|
| Numeric | Impute, then optionally scale | age |
| Categorical | Impute, then one-hot encode | plan |
Pipelines: one path for training and prediction
A pipeline chains preprocessing steps and a final model. When you fit it, each preprocessing step learns from the training rows. When you predict, the same learned transformations are applied automatically.
Choosing evaluation metrics
A metric is a numerical summary of prediction quality. Accuracy is the fraction of correct predictions. Precision measures how many predicted positives are correct. Recall measures how many actual positives were found. F1 combines precision and recall.
Use accuracy when class errors have similar costs. Use recall when missing a positive is especially costly. Use precision when false alarms are costly. Use F1 when both types of error matter.
Setting a baseline
A baseline is a simple reference result. For classification, a majority-class baseline always predicts the most common class. A useful model should beat this reference on a metric that matches the real goal.
Training a model
The example compares a majority baseline with logistic regression. The pipeline standardizes numeric columns, trains on the training split, and evaluates both models on untouched test rows.
from sklearn.datasets import load_breast_cancer
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, f1_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
baseline = DummyClassifier(strategy="most_frequent")
baseline.fit(X_train, y_train)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
baseline_pred = baseline.predict(X_test)
model_pred = model.predict(X_test)
print("Baseline F1:", f1_score(y_test, baseline_pred))
print("Model F1:", f1_score(y_test, model_pred))
print(classification_report(y_test, model_pred))Exercise
Why should the test rows be excluded when the scaler learns its mean and variance?
Show answer
The test rows represent future, unseen data. Using them during preprocessing leaks information into training and can make the reported score look better than real-world performance.