MLDay 14 of 50Supervised and Unsupervised Learning
Prepare Messy Tabular Data
Day 8's model predicted 317 rentals at 23:00, when the real average was 119.
Day 8's model predicted 317 rentals at 23:00, when the real average was 119. It read the hour as an amount, so every later hour looked busier. Real tables also arrive with blank cells, and a model can't learn from a blank. Both problems are fixed before the model sees the data.
The idea
A model needs a table of numbers with no gaps. Getting there takes up to three jobs.
- Impute the gaps. Imputation fills each missing cell with a stand-in learned from its column: the mean, the median (the middle value), or the most frequent value. The median is the safer default for numbers, since one extreme value drags the mean but not the median.
- One-hot encode the categories. A category is a label, like a weather type or an hour of the day. Stored as codes (1, 2, 3), it looks like an amount, with an order and equal steps. One-hot encoding gives each category its own 0/1 column instead, so each one gets its own weight.
- Scale the numbers, as in Day 9.
Each job learns something from the data: a median, a list of categories, a mean and a spread. It must learn them from the training rows only, then apply them unchanged to the test rows. Learning them from all rows leaks test data into training (Day 6).
scikit-learn's ColumnTransformer sends each column to its own step and joins the results side by side.
Put it in a Pipeline (Day 11) with the model, and one
fit on the training rows learns everything at once.
A tiny example
Four hours at a dock, with one wind reading lost:
| Hour | Wind (km/h) | Weather |
|---|---|---|
| 1 | 2 | clear |
| 2 | 4 | rain |
| 3 | (missing) | mist |
| 4 | 10 | clear |
- Mean fill: (2 + 4 + 10) / 3 = 5.33. The gusty hour pulls it up.
- Median fill: sort the known values, 2, 4, 10, and take the middle one: 4.
One-hot turns the weather column into 3 columns, one per category. Each row has a single 1:
| Hour | clear | mist | rain |
|---|---|---|---|
| 1 | 1 | 0 | 0 |
| 2 | 0 | 0 | 1 |
| 3 | 0 | 1 | 0 |
| 4 | 1 | 0 | 0 |
Try it
Fill the gaps, then encode the weather
A model needs a number in every cell. Choose how to fill the gaps (—), then turn on one-hot encoding to turn each category into 0/1 columns.
| temp (°C) | wind (km/h) | weather |
|---|---|---|
| 12 | 2 | clear |
| 15 | 4 | rain |
| 14 | missing | mist |
| missing | 10 | clear |
| 16 | 30 | rain |
| 13 | 3 | clear |
| temp (°C) | wind (km/h) | weather |
|---|---|---|
| 12 | 2 | clear |
| 15 | 4 | rain |
| 14 | 9.8 (filled) | mist |
| 14 (filled) | 10 | clear |
| 16 | 30 | rain |
| 13 | 3 | clear |
gaps filled 2temp (°C) ← mean 14wind (km/h) ← mean 9.8columns 3 → 3
Two cells are blank. It starts on mean: the missing wind becomes 9.8 km/h, pulled up by the one 30 km/h gust. Switch to median and it drops to 4, while the temperature stays at 14 either way. Then turn one-hot on and watch one weather column become three.
In code
The same six hours, with np.nan marking the blanks. The imputer handles the numbers and the encoder handles
the weather.
# script_id: day_014_tabular_preprocessing/tiny
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
hours = pd.DataFrame({
"temp_c": [12, 15, 14, np.nan, 16, 13],
"wind_kmh": [2, 4, np.nan, 10, 30, 3],
"weather": ["clear", "rain", "mist", "clear", "rain", "clear"],
})
prep = ColumnTransformer([
("num", SimpleImputer(strategy="median"), ["temp_c", "wind_kmh"]), # the default is "mean"
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["weather"]),
], verbose_feature_names_out=False).set_output(transform="pandas") # keep column names
print(prep.fit_transform(hours).to_string(index=False)) # fit on these rows only
print("medians learned:", prep.named_transformers_["num"].statistics_)
new = pd.DataFrame({"temp_c": [np.nan], "wind_kmh": [50.0], "weather": ["snow"]})
print(prep.transform(new).to_string(index=False))
temp_c wind_kmh weather_clear weather_mist weather_rain
12.0 2.0 1.0 0.0 0.0
15.0 4.0 0.0 0.0 1.0
14.0 4.0 0.0 1.0 0.0
14.0 10.0 1.0 0.0 0.0
16.0 30.0 0.0 0.0 1.0
13.0 3.0 1.0 0.0 0.0
medians learned: [14. 4.]
temp_c wind_kmh weather_clear weather_mist weather_rain
14.0 50.0 0.0 0.0 0.0
fit learned two medians and three weather names. The new hour reuses them: its blank temperature becomes
the training median, 14. Its "snow" was never seen, so all three weather columns are 0. Without
handle_unknown="ignore", that row raises a ValueError. sparse_output=False returns an ordinary table;
pandas output needs it.
Now the real fix for Day 8. The script refits Day 8's 12-feature model with the same time-ordered split. First every column is a number, then the hour and the weather become categories.
# script_id: day_014_tabular_preprocessing/bikes
import os
from pathlib import Path
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
from sklearn.metrics import root_mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
train, test = train_test_split(df, test_size=0.25, shuffle=False) # oldest 75% to train
features = ["season", "yr", "mnth", "hr", "holiday", "weekday", "workingday",
"weathersit", "temp", "atemp", "hum", "windspeed"] # no casual/registered leak
for cats in [[], ["hr"], ["hr", "weathersit"]]:
prep = ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), cats),
("num", StandardScaler(), [f for f in features if f not in cats]),
])
model = make_pipeline(prep, LinearRegression()).fit(train[features], train["cnt"])
pred = model.predict(test[features])
rmse = root_mean_squared_error(test["cnt"], pred)
print(f"categories: {str(cats):<20} columns {len(prep.get_feature_names_out()):>2} test RMSE {rmse:.1f}")
by_hour = test.assign(pred=pred).groupby("hr")[["cnt", "pred"]].mean()
print(by_hour.loc[[3, 8, 17, 23]].round().astype(int).to_string())
categories: [] columns 12 test RMSE 183.5
categories: ['hr'] columns 35 test RMSE 136.5
categories: ['hr', 'weathersit'] columns 38 test RMSE 136.2
cnt pred
hr
3 15 102
8 491 414
17 618 500
23 119 169
The first row matches Day 8. One-hot turns the hour into 24 columns, and the RMSE falls from 183.5 to 136.5. Each hour now has its own weight, so in the last model the 8:00 prediction rises from 211 to 414, and 23:00 falls from 317 to 169. The weather adds little on top. Scaling doesn't change a plain linear regression's predictions, but it costs nothing here, and Day 15 needs it.
A number column that needs both gets a small pipeline as its step:
make_pipeline(SimpleImputer(strategy="median"), StandardScaler()).
Quick check
Quick check
1. A column holds 2, 4, (missing) and 30. What does median imputation put in the gap?
2. Why one-hot encode the hour instead of using hr = 0…23 as a number?
3. Which rows should the imputer learn its median from?
Next
Day 15: Predict by Distance: k-Nearest Neighbours makes predictions from the most similar rows, where unscaled columns decide who counts as "near".
Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.