Part 03 / Stage 1
Working with data
Goal: Load, explore, clean and split a dataset without fooling yourself — most model problems are data problems. Time: ~2.5 hours · Needs: Parts 1–2
What you will learn
- pandas essentials: loading, selecting, filtering, grouping
- Exploring a dataset: shapes, types, summary statistics, class balance
- Missing values: detecting and imputing them
- Train, validation and test splits — and stratification
- Data leakage: the most common way to fool yourself
- Baselines: the number every model must beat
Topics in this part
Practice
Run from the repo root with PYTHONPATH=tools so ailab imports, e.g.
PYTHONPATH=tools .venv/bin/python stage-1-foundations/part-03-working-with-data/solutions/ex01.py
Exercise 1: Group insight
On the churn data, print the churn rate by has_internet, and the average support_calls for churned vs not-churned customers. One sentence: which signal looks stronger?
Show the solution to Exercise 1
# Exercise 1: Group insight
from ailab import make_churn
df = make_churn()
print("churn rate by has_internet:")
print(df.groupby("has_internet")["churned"].mean().round(3).to_string())
print()
print("average support calls by churned:")
print(df.groupby("churned")["support_calls"].mean().round(2).to_string())
# Support calls separate the groups clearly; internet barely moves the rate.
Exercise 2: Missing-value plan
Count the missing monthly_charges, then show the median of that column computed (a) over all rows and (b) over an 80% training split only. Print both medians — they differ, which is exactly why the order matters.
Show the solution to Exercise 2
# Exercise 2: Missing-value plan
from sklearn.model_selection import train_test_split
from ailab import make_churn
df = make_churn()
print("missing monthly_charges:", int(df["monthly_charges"].isna().sum()))
median_all = df["monthly_charges"].median()
train, test = train_test_split(df, test_size=0.2, random_state=42, stratify=df["churned"])
median_train = train["monthly_charges"].median()
print("median over all rows: ", median_all)
print("median over train only: ", median_train)
# They differ: computing it over all rows would bake test-set information
# into the value used during training.
Exercise 3: Stratified vs not
Split the data 80/20 ten times without stratify (random_state 0–9) and print the test churn rate each time; then once with stratify. How much did the unstratified rate wobble?
Show the solution to Exercise 3
# Exercise 3: Stratified vs not
from sklearn.model_selection import train_test_split
from ailab import make_churn
df = make_churn()
rates = []
for seed in range(10):
_, test = train_test_split(df, test_size=0.2, random_state=seed)
rates.append(float(round(test["churned"].mean(), 3)))
print("unstratified test churn rates:", rates)
print("spread:", min(rates), "to", max(rates))
_, test = train_test_split(df, test_size=0.2, random_state=0, stratify=df["churned"])
print("stratified test churn rate: ", round(test["churned"].mean(), 3))
Exercise 4: Spot the leak
You are given candidate features: tenure_months, refund_issued_after_cancellation, support_calls, last_month_of_service. Write a comment per feature saying KEEP or LEAK and why; print your verdicts.
Show the solution to Exercise 4
# Exercise 4: Spot the leak
verdicts = {
"tenure_months": "KEEP — known for every active customer at prediction time.",
"refund_issued_after_cancellation": "LEAK — only exists after the customer cancelled; it encodes the answer.",
"support_calls": "KEEP — observable history, available before any churn decision.",
"last_month_of_service": "LEAK — defined by the churn event itself; unknown for active customers.",
}
for feature, verdict in verdicts.items():
print(f"{feature:35s} {verdict}")
Mini-project: Churn data report
Write a script that prints a short data report: shape, missing counts, churn rate, churn by contract, churn by internet — and the majority-class baseline every later model must beat. Handle missing values with split-then-impute.
A complete version is in solutions/mini_churn_report.py.
Stretch: wrap the cleaning in a reusable function with unit tests, so new data exports go through the same steps.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Imputing/scaling before splitting | Test statistics leak into training | Split first; fit preprocessing on train only |
No stratify on an imbalanced target |
Splits get different class rates; metrics wobble | stratify=y |
| Using features recorded after the outcome | Target leakage — great test score, useless model | Ask: known at prediction time? |
| Skipping the baseline | "80% accuracy" might be worse than doing nothing | Majority-class first, always |
Trusting .head() as exploration |
Misses missing values, imbalance, outliers | isna().sum(), describe(), class balance |
Quick recap
- DataFrames let you select, filter and
groupby(...).mean()your way to insight before any model exists. - Explore every new dataset the same way: shape, types, missing counts and class balance.
- Split first, then impute from training data only.
- Stratify splits on the target; keep the test set untouched until the end.
- Leakage is answer information reaching training; split early and think it through feature by feature.
- The majority-class baseline is the number every model must beat: here, 0.701.
Checklist
- I can select, filter and group a DataFrame.
- I ran the first-look example and can state rows, missing values, churn rate.
- I can explain why imputation must come after the split.
- I can name three kinds of leakage.
- I computed the majority-class baseline and will quote it with every model score.
Read more: pandas in 10 minutes · Missing data · scikit-learn: common pitfalls