Learning path: Prepare Data for a Machine Learning Model · Step 5 of 7
Pipelines and ColumnTransformer: All Preprocessing and the Model in One Object
Pack imputing, encoding, scaling and the model into one scikit-learn Pipeline with two ColumnTransformer lanes. One fit on the train rows, 21 columns in, 115 out, 0.849 test accuracy, and a raw row with a blank predicted directly.
What you will learn
- Build a number lane and a text lane as small Pipelines
- Join the lanes with ColumnTransformer and make_column_selector
- Fit the whole line with one call on the train rows, and prove the test rows taught it nothing
- Predict straight from a raw row, blanks and text included
Before you start
- Handling Missing Data
- Encoding Categorical Data
- Feature Scaling
Imagine a juice factory. Raw fruit goes in at one end. It's washed, peeled and pressed, and juice comes out at the other. Nobody carries the fruit from station to station by hand. The belt does it, and the stations are the same, in the same order, every time.
Your data needs the same kind of line. Raw rows go in. The gaps are filled, the text is encoded, the numbers are scaled, and the model gives a prediction. In scikit-learn, that whole line is one Pipeline.
You already know the stations one by one: SimpleImputer, OneHotEncoder and StandardScaler. Now we put them on a single belt.
Two lanes, joined for one model
Numbers and text need different care, so the line has two lanes. A ColumnTransformer sends each group of columns down its own lane and joins the results side by side.
Load, then split first
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.linear_model import LogisticRegression
df = pd.read_csv("weatherAUS.csv")
X = df.drop(columns=["Date", "RISK_MM", "RainTomorrow"])
y = df["RainTomorrow"]
print(X.shape)
(142193, 21)
RISK_MM holds tomorrow's rain, so it would give the answer away. (Train-Test Split and Data Leakage shows why.) Then the split, before any step has seen the data:
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X_train.shape, X_test.shape)
(113754, 21) (28439, 21)
Pick the lanes
make_column_selector picks columns by their type, so you never type 21 column names by hand:
num_cols = make_column_selector(dtype_include="number")
cat_cols = make_column_selector(dtype_exclude="number")
print(len(num_cols(X_train)), "number columns")
print(len(cat_cols(X_train)), "text columns")
16 number columns
5 text columns
Then one small pipeline per lane. Each step is a (name, object) pair, and the steps run in order:
numeric_steps = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
categorical_steps = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
])
handle_unknown="ignore" means a town the model never saw won't crash anything.
Join the lanes, add the model
ColumnTransformer takes a list of (name, steps, columns). The num lane gets the number columns, the cat lane gets the text columns:
preprocess = ColumnTransformer([
("num", numeric_steps, num_cols),
("cat", categorical_steps, cat_cols),
])
Then the full line: preprocess followed by clf, a logistic regression. One fit on the train rows runs every station. One score on the raw test rows:
model = Pipeline([
("preprocess", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
model.fit(X_train, y_train)
acc = model.score(X_test, y_test)
print("Test accuracy:", round(acc, 3))
Test accuracy: 0.849
How many columns does the model actually see?
pre = model.named_steps["preprocess"]
cols_in = X_test.shape[1]
cols_out = pre.transform(X_test).shape[1]
print(cols_in, "columns in,", cols_out, "columns out")
21 columns in, 115 columns out
The one-hot encoder turned the 5 text columns into one column per value, so 21 columns became 115.
What fit and score really do
fit(X_train, y_train): X_train rides through the line. The number lane learns the medians and the means, the text lane learns the most frequent values and the list of categories, and the model learns its weights.score(X_test, y_test): X_test rides the same line, but every station only applies what it already learned. The model only predicts.
So X_test is only ever used to score. It never teaches a single station.
Proof: the scaler learned from the train rows only
Open the number lane inside the fitted pipeline and ask its scaler what it learned for Rainfall (the third number column):
lane = pre.named_transformers_["num"]
fill, scale = lane["impute"], lane["scale"]
cols = num_cols(X_train)
train_rain = fill.transform(X_train[cols])[:, 2]
test_rain = fill.transform(X_test[cols])[:, 2]
print(cols[2])
print("scaler learned:", round(scale.mean_[2], 4))
print("train rows mean:", round(train_rain.mean(), 4))
print("test rows mean: ", round(test_rain.mean(), 4))
Rainfall
scaler learned: 2.3373
train rows mean: 2.3373
test rows mean: 2.2845
The scaler's mean, 2.3373, matches the train rows exactly. The test rows average 2.2845: they taught the scaler nothing, and we didn't have to think about it. That's the big win of a pipeline. The fit-on-train rule is built in.
Predict straight from a raw row
Take one raw row from the test set. The town is text and Sunshine is blank:
new_day = X_test.iloc[[0]]
show = ["Location", "MinTemp", "Sunshine", "RainToday"]
new_day[show]
Location MinTemp Sunshine RainToday
47620 Canberra 15.1 NaN No
print(model.predict(new_day))
print(model.predict_proba(new_day).round(2))
print(model.classes_)
['No']
[[0.91 0.09]]
['No' 'Yes']
The answer is No, with probability 0.91 for No and 0.09 for Yes (the order comes from classes_). The pipeline filled the gap, encoded the town and scaled the numbers by itself. We didn't write one line of preprocessing for this row.
Common mistakes
- Preprocessing outside the pipeline and then fitting only the model. You lose the built-in protection, and you have to repeat every step by hand at prediction time.
- Calling
fiton the test rows. Usescoreorpredicton them. - Forgetting
handle_unknown="ignore"in the text lane, so a new town crashes prediction. - Typing column lists by hand and missing one.
make_column_selectorpicks by type.
Quick recap
| Piece | Code | Here |
|---|---|---|
| Split first | train_test_split(..., stratify=y) | 113,754 train, 28,439 test |
| Two lanes | Pipeline([...]) per type | 16 number, 5 text |
| Join the lanes | ColumnTransformer | 21 columns in, 115 out |
| Add the model | Pipeline([("preprocess", ...), ("clf", ...)]) | test accuracy 0.849 |
| No leak | one fit(X_train, y_train) | scaler mean 2.3373 = train mean |
| Raw rows in | model.predict(new_day) | No, 0.91 |
Try it yourself
Swap the model and keep the line: model.set_params(clf=RandomForestClassifier(random_state=42)) (import it from sklearn.ensemble), then fit and score again. Only the last step changes.
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
Next →Feature Selection and the Curse of Dimensionality: Keep the Columns That Matter
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Train-Test Split and Data Leakage: Split First, Learn After
Why the train-test split comes before everything else: an 80/20 split with stratify and random_state, a scaler that leaks test rows, and a column that secretly holds the answer. Shown on Rain in Australia.
Handling Missing Data: Count the Blanks, Then Fill Them with SimpleImputer
Count the blanks with isnull().sum(), see why dropna() would throw away 60% of the rows, and fill the gaps with SimpleImputer: median for numbers, most frequent for text, learned from the train rows only. Shown on Rain in Australia.
Encoding Categorical Data: OrdinalEncoder, OneHotEncoder and LabelEncoder
Models only understand numbers. Encode T-shirt sizes with OrdinalEncoder, colours with OneHotEncoder, avoid the dummy variable trap, handle a colour the encoder never saw, tame a date with 3,436 values, and encode the answer with LabelEncoder.
Feature Scaling: StandardScaler, MinMaxScaler and Which Models Care
Put features on the same scale so each one gets a fair say. StandardScaler and MinMaxScaler fitted on the train rows, the formula checked by hand, and a wine test where KNN jumps from 0.806 to 0.972 while a decision tree stays at 0.944.