Sub topic 2
Using `StandardScaler` and `MinMaxScaler`
Assume you know basic NumPy arrays, train/test splits, and scikit-learn estimators. A scaler learns statistics from feature columns and uses them to change their numeric ranges.
`fit`, `transform`, and `fit_transform`
StandardScaler standardizes each column using:
\[ z = \frac{x-\text{mean}}{\text{standard deviation}} \]
The result usually has mean 0 and standard deviation 1. MinMaxScaler maps each column to a chosen range, commonly 0 to 1:
\[ x' = \frac{x-\text{minimum}}{\text{maximum}-\text{minimum}} \]
Use fit to learn the required statistics. Use transform to apply those learned statistics. fit_transform performs both operations on the same data.
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
X = np.array([
[1.0, 200.0],
[2.0, 400.0],
[3.0, 600.0],
])
standard = StandardScaler()
X_standard = standard.fit_transform(X)
minimum_maximum = MinMaxScaler()
X_minmax = minimum_maximum.fit_transform(X)
print(X_standard)
print(X_minmax)
# Apply the already learned scaling to new rows.
new_rows = np.array([[2.5, 500.0]])
print(standard.transform(new_rows))
print(minimum_maximum.transform(new_rows))After fitting, the scaler stores values such as mean_, scale_, data_min_, and data_max_. Call transform, rather than fit_transform, for later data.
Fit on training data only
A scaler fitted on the complete dataset can learn information from the test set. This is data leakage: information that should be unavailable during training affects preprocessing.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
scaler = StandardScaler().fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)The test rows use the training mean and standard deviation. This gives evaluation results that better represent future data.
Pipelines and column-specific scaling
A Pipeline keeps preprocessing and prediction together. During cross-validation, scikit-learn refits the scaler inside each training fold.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000)
)
model.fit(X_train, y_train)Use ColumnTransformer when columns need different preprocessing.
from sklearn.compose import ColumnTransformer
preprocess = ColumnTransformer(
[
("standard", StandardScaler(), [0, 1]),
("minmax", MinMaxScaler(), [2, 3]),
],
remainder="passthrough",
)Exercise
Why should transform(X_test) be used instead of fit_transform(X_test)?
Show answer
The test data must use statistics learned from the training data. Fitting on the test data leaks information into evaluation.