Exercises
Fifteen exercises covering the whole course, from cleaning to leakage-free pipelines. Try each one before opening the answer. Several answers include a program you can run and change; the lessons linked in each answer are the place to reread if you get stuck.
| # | Exercise | Practises |
|---|---|---|
| 1 | Two date formats, one column | cleaning: dates and time zones |
| 2 | What does zero mean? | imputation, "don't fill with zero" |
| 3 | Imputer from scratch | fitted on training data only |
| 4 | Pick the scaler | linear scalers and transforms |
| 5 | A false order | one-hot, ordinal and label encoding |
| 6 | Target encoding gone wrong | target encoding inside folds |
| 7 | Hours on a circle | date and time features |
| 8 | Is the flip allowed? | augmentation and label preservation |
| 9 | Where does SMOTE go? | imbalance, training data only |
| 10 | Focal loss by hand | focal loss |
| 11 | PCA before or after scaling | dimensionality reduction |
| 12 | Choose the split | split strategies |
| 13 | Find the leaks | the leakage rules |
| 14 | One pipeline for a mixed table | Pipeline, ColumnTransformer, FunctionTransformer |
| 15 | Prepare by data type | images, text, audio, time series, video |
Exercise 1: Two date formats, one column
A column visit holds "07/08/2026 09:30" from a clinic in Hanoi (day first, local time UTC+7) and "07/08/2026 09:30 AM" from a clinic in New York (month first, local time). Which two instants in UTC do these strings stand for, and how far apart are they?
Answer
Parse each source with its own format and time zone (Dates, Times and Units):
import pandas as pd
hanoi = pd.to_datetime("07/08/2026 09:30", format="%d/%m/%Y %H:%M").tz_localize("Asia/Ho_Chi_Minh")
ny = pd.to_datetime("07/08/2026 09:30 AM", format="%m/%d/%Y %I:%M %p").tz_localize("America/New_York")
print(hanoi.tz_convert("UTC"))
print(ny.tz_convert("UTC"))
print(hanoi.tz_convert("UTC") - ny.tz_convert("UTC"))2026-08-07 02:30:00+00:00
2026-07-08 13:30:00+00:00
29 days 13:00:00
The same text means 7 August in Hanoi and 8 July in New York; in UTC the Hanoi visit is 29 days and 13 hours later than the New York one.
Exercise 2: What does zero mean?
A fitness app's table has steps_today (missing when the phone was off), cigarettes_per_day (missing when the question was skipped) and account_balance (missing for accounts opened today). For each, is fillna(0) acceptable? What would you do instead?
Answer
steps_today: no. Zero steps is a real (and rare) value; a phone being off says nothing about steps. Median imputation plus a missing indicator.cigarettes_per_day: no. Zero means non-smoker, a large and meaningful group; skipping the question may itself be informative (MNAR). Use a constant outside the range or a separate "unknown" category, plus an indicator.account_balance: possibly yes, if the documentation says a new account starts at 0. Then zero is the true value, not a guess. Record that rule in the cleaning log.
See Deleting, Mean, Median, Mode and Constant Imputation and Missing-Value Indicators.
Exercise 3: Imputer from scratch
Write a ModeImputer with fit and transform for a pandas Series of categories. fit learns the most frequent value of the training data; transform fills missing values with it and must not change when applied to a test series with a different mode.
Answer
import pandas as pd
class ModeImputer:
def fit(self, s):
counts = s.dropna().value_counts()
self.mode_ = sorted(counts[counts == counts.max()].index)[0] # ties: alphabetical, reproducible
return self
def transform(self, s):
return s.fillna(self.mode_)
train = pd.Series(["card", "cash", "card", None, "card", "transfer"])
test = pd.Series(["cash", None, "cash", "cash"])
imp = ModeImputer().fit(train)
print("learned:", imp.mode_)
print(imp.transform(test).tolist())learned: card
['cash', 'card', 'cash', 'cash']
The test series is mostly cash, but the gap is filled with card, the training mode. Ties are broken alphabetically so that two runs give the same answer.
Exercise 4: Pick the scaler
For each column, choose a scaler or transform and say why: (a) pixel intensities 0 to 255 for a small neural network; (b) house prices with a long right tail for a linear model; (c) the number of times each of 20,000 words appears in a document (sparse); (d) a sensor reading with a few huge glitches you have decided to keep.
Answer
(a) Divide by 255 (min-max with known bounds; no fitting needed), then often standardise per channel with training means. (b) A log or Yeo-Johnson transform, then standardise. (c) MaxAbsScaler or TF-IDF, which keep sparsity; or Normalizer per document if direction matters. (d) RobustScaler (median and IQR ignore the glitches) or a quantile transform. See Min-Max, Z-Score, Robust and Max-Abs Scaling and Unit Norm, Log, Power and Quantile Transforms.
Exercise 5: A false order
A colleague encodes colour (red, green, blue) as 0, 1, 2 with LabelEncoder and trains a linear regression. Explain what the model assumes, and show the difference in the design matrix with one-hot encoding.
Answer
The integer code makes the model assume that green lies exactly halfway between red and blue and that the effect grows linearly from red to blue, an order that does not exist. One-hot encoding gives each colour its own coefficient. LabelEncoder is meant for target labels (One-Hot, Ordinal and Label Encoding).
import numpy as np
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
colour = np.array(["red", "green", "blue", "green"])
print("label codes:", LabelEncoder().fit_transform(colour).tolist())
ohe = OneHotEncoder().fit(colour.reshape(-1, 1))
print(ohe.get_feature_names_out(["colour"]).tolist())
print(ohe.transform(colour.reshape(-1, 1)).toarray().astype(int).tolist())label codes: [2, 1, 0, 1]
['colour_blue', 'colour_green', 'colour_red']
[[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 0]]
Note that LabelEncoder sorts the categories alphabetically, so the codes are not even in the order the colleague might expect.
Exercise 6: Target encoding gone wrong
A dataset has a customer_id column with 1,000 distinct values, each appearing twice, and a label that is pure noise. Someone replaces each ID by the mean label of that ID computed on all rows, then cross-validates a model on this single feature. What score do you expect, and what should it be?
Answer
The leaky encoding contains each row's own label (half of a two-row mean), so the model scores far above chance even though the label is noise. The honest score is chance level. scikit-learn's TargetEncoder avoids this with internal cross fitting (Target Encoding Inside Folds):
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import TargetEncoder
rng = np.random.default_rng(0)
ids = np.repeat(np.arange(1000), 2)
y = rng.integers(0, 2, ids.size)
means = np.bincount(ids, weights=y) / np.bincount(ids)
leaky_feature = means[ids].reshape(-1, 1)
leaky = cross_val_score(LogisticRegression(), leaky_feature, y, cv=5, scoring="roc_auc").mean()
honest = cross_val_score(make_pipeline(TargetEncoder(random_state=0), LogisticRegression()),
ids.reshape(-1, 1).astype(str), y, cv=5, scoring="roc_auc").mean()
print(f"leaky ROC AUC {leaky:.3f} inside folds {honest:.3f}")leaky ROC AUC 0.863 inside folds 0.526
The leaky feature reaches an AUC of 0.863 on pure noise; encoded inside the folds, the same column scores 0.526, chance level.
Exercise 7: Hours on a circle
Encode the hour of day so that 23:00 and 01:00 are as close as 01:00 and 03:00. Give the formula and compute the distance between the encodings of hours 23 and 1, and of hours 1 and 3.
Answer
Map the hour onto a circle (Date and Time Features):
import numpy as np
def enc(h):
a = 2 * np.pi * h / 24
return np.array([np.sin(a), np.cos(a)])
print(round(float(np.linalg.norm(enc(23) - enc(1))), 4), round(float(np.linalg.norm(enc(1) - enc(3))), 4))
print("raw difference:", abs(23 - 1), "vs", abs(1 - 3))0.5176 0.5176
raw difference: 22 vs 2
Both pairs are two hours apart on the circle and get the same distance; as raw numbers, 23 and 1 look 22 hours apart.
Exercise 8: Is the flip allowed?
For which of these tasks is a horizontal flip a label-preserving augmentation? (a) cat vs dog photos; (b) recognising handwritten digits; (c) classifying chest X-rays where the heart's side matters; (d) detecting a "turn left" road sign vs "turn right"; (e) satellite images of fields.
Answer
(a) Yes. (b) No: a flipped digit is not a valid digit (and some become other symbols). (c) No: a flip creates an anatomy that is rare (situs inversus) and changes what the label means. (d) No: it turns one class into the other; you could flip and swap the labels, but only on purpose. (e) Yes, and rotations by 90 degrees too, since there is no "up" in a top-down view. See Image Augmentation.
Exercise 9: Where does SMOTE go?
Put these steps in a correct order for 5-fold cross-validation and say which object makes it automatic: SMOTE, StandardScaler, SimpleImputer, LogisticRegression, splitting into folds.
Answer
Split into folds first; then, inside each training fold only: impute, scale, SMOTE, fit the model. Validation folds are imputed and scaled with the training-fold statistics and are never resampled. imblearn.pipeline.Pipeline (or make_pipeline) does this: samplers run during fit only. SMOTE should come after imputation (it cannot interpolate NaN) and usually after scaling (its nearest neighbours depend on distances). See Undersampling, Oversampling, SMOTE and ADASYN and Threshold Adjustment and the Training-Data-Only Rule.
Exercise 10: Focal loss by hand
Compute the binary cross-entropy and the focal loss with (no weighting) for a positive example predicted with and one predicted with . By what factor does focal loss shrink each?
Answer
For a positive example, cross-entropy is and focal loss is (Class Weights, Focal Loss and Balanced Batches):
import numpy as np
for p in [0.9, 0.3]:
ce = -np.log(p)
fl = -(1 - p) ** 2 * np.log(p)
print(f"p={p}: cross-entropy {ce:.4f} focal {fl:.4f} factor {(1 - p) ** 2:.2f}")p=0.9: cross-entropy 0.1054 focal 0.0011 factor 0.01
p=0.3: cross-entropy 1.2040 focal 0.5899 factor 0.49
The well-classified example () is down-weighted 100 times, the hard one () only about twice, so training focuses on hard examples.
Exercise 11: PCA before or after scaling
The wine data has 13 features, one of which (proline) has values in the hundreds to over a thousand. How much variance does the first principal component explain without and with standardisation, and what does the difference tell you?
Answer
from sklearn.datasets import load_wine
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, _ = load_wine(return_X_y=True)
raw = PCA(2).fit(X)
scaled = make_pipeline(StandardScaler(), PCA(2)).fit(X)
print("raw: ", raw.explained_variance_ratio_.round(3).tolist())
print("scaled:", scaled[-1].explained_variance_ratio_.round(3).tolist())
print("largest loading of raw PC1 is feature", int(abs(raw.components_[0]).argmax()))raw: [0.998, 0.002]
scaled: [0.362, 0.192]
largest loading of raw PC1 is feature 12
Without scaling, PC1 explains almost all the variance and points almost entirely along feature 12 (proline): PCA has only found the column with the largest units. After standardising, the variance is spread over several components that combine many features. See PCA and Truncated SVD.
Exercise 12: Choose the split
Choose a split strategy for each: (a) predicting next week's sales per store from three years of history; (b) diagnosing a disease from several scans per patient; (c) a spam classifier with 2% spam and 50,000 emails; (d) choosing hyperparameters and reporting an unbiased score with only 300 rows.
Answer
(a) A time-based split (train on the past, test on the most recent period; TimeSeriesSplit for CV). (b) A group split by patient (GroupKFold or StratifiedGroupKFold). (c) A stratified split, so both sides keep about 2% spam. (d) Nested cross-validation: an inner CV tunes, an outer CV estimates. See Random, Stratified, Group and Time-Based Splits and Nested Cross-Validation.
Exercise 13: Find the leaks
Find every leak in this plan: "Load all data. Standardise all columns. Select the 50 features most correlated with the label. Oversample the minority class with SMOTE. Split 80/20 at random. Tune the threshold to get the best F1 on the 20%. Report that F1."
Answer
Four leaks: (1) the scaler is fitted on all rows, including the future test rows (small effect, still wrong); (2) feature selection uses the test labels (large effect, see the lab in The Leakage Rules); (3) SMOTE before the split puts synthetic copies of test points into training; (4) the threshold is tuned on the test set, so the reported F1 is the best of many tries on it. Fix: split first; put scaler, selector and SMOTE in an imblearn pipeline; tune the threshold on validation folds; touch the test set once.
Exercise 14: One pipeline for a mixed table
Build one pipeline for a table with numeric age and income (missing values, income skewed), categorical city (unknown cities will appear in production) and a free-text note, and score it with 5-fold cross-validation.
Answer
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 400
df = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.lognormal(10.5, 0.7, n),
"city": rng.choice(["Hanoi", "Hue", "Da Nang", "Can Tho"], n),
"note": rng.choice(["late payment", "loyal customer", "asked about upgrade", "complained twice"], n),
})
y = ((df["note"].str.contains("late|complained")) ^ (rng.random(n) < 0.15)).astype(int)
df.loc[rng.random(n) < 0.1, "income"] = np.nan
pre = ColumnTransformer([
("age", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age"]),
("income", make_pipeline(FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
SimpleImputer(strategy="median", add_indicator=True), StandardScaler()), ["income"]),
("city", OneHotEncoder(handle_unknown="ignore"), ["city"]),
("note", TfidfVectorizer(), "note"), # a single column name: the vectorizer gets 1-D text
])
pipe = make_pipeline(pre, LogisticRegression(max_iter=1000))
print(f"5-fold accuracy {cross_val_score(pipe, df, y, cv=5).mean():.3f}")
pipe.fit(df, y)
print(len(pipe[0].get_feature_names_out()), "features, e.g.", pipe[0].get_feature_names_out()[[0, 1, 2, 3]].tolist())5-fold accuracy 0.812
16 features, e.g. ['age__age', 'income__income', 'income__missingindicator_income', 'city__city_Can Tho']
Note "note" passed as a string, not a list: TfidfVectorizer expects a 1-D sequence of texts. The log comes first (log1p keeps NaN as NaN), so the median is taken on the log scale and the missing indicator stays a clean 0/1 column. See Pipelines, ColumnTransformer and FunctionTransformer.
Exercise 15: Prepare by data type
For each data type, name the one splitting rule that most often prevents leakage, and one preparation step that must use statistics from the training data only: images, text, audio, time series, video.
Answer
| Type | Split rule | Learned from training data only |
|---|---|---|
| images | by subject, camera or source (near-duplicate photos together) | per-channel mean and std for normalisation |
| text | by document, author or source | the vocabulary / tokenizer vocabulary, TF-IDF weights |
| audio | by speaker or recording session | feature normalisation (mean and variance of log-Mel bands) |
| time series | by time (train on the past) | scalers and any rolling statistics; lags only from the past |
| video | by whole video or session (frames of one clip are near-duplicates) | per-channel statistics, frame-feature scalers |
See the section Preparation by Data Type, starting at Preparing Tabular Data.
Test yourself
Which of these may be computed on the full dataset before splitting?
- The median used to fill missing values
- A fixed unit-conversion table from pounds to kilograms
- The 20 features most correlated with the label
- SMOTE synthetic samples
A tuned threshold, chosen to maximise F1 on the test set, is reported with that F1. What is wrong?
- Nothing
- The test set was used for a choice, so the reported F1 is optimistic
- F1 cannot be tuned
- Thresholds must be 0.5
Which split is right for several photos per patient?
- Random split by photo
- Stratified split by photo
- Group split by patient
- Time split