Section 1 · Lesson 2

Train/test splits and baselines

Hold out data the model never sees, stratify imbalanced labels, and always compare a model with a simple baseline.

40 min 2 practice tasks
Comparing machine learning models in scikit-learn by Data School on YouTube

A model that has seen the answers will look better than it really is. Some models can memorize their training rows almost perfectly, so scoring them on those same rows rewards memory, not insight. The question that matters is: how well does the model do on visitors it has never seen?

Hold out a test set

Split the labeled data once, before any modeling:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)
  • test_size=0.25 keeps a quarter of the rows (1,250 visitors) for testing. 20–30% is typical.
  • random_state=42 makes the shuffle repeatable, so everyone gets the same split.
  • stratify=y keeps the share of converters the same in both parts. With only about 15% positives, an unlucky random split could leave the test set with noticeably more or fewer converters than the training set.

Think of the test set as a final exam. You fit, compare and tune using the training data, and look at test performance once at the end. If you keep adjusting until the test score improves, the test set has quietly become training data and its score is optimistic again.

Always have a baseline

A baseline is the score you get with no real model at all. For classification, the simplest is “always predict the most common class”:

from sklearn.dummy import DummyClassifier

baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
baseline.score(X_test, y_test)   # accuracy ≈ 0.847

Predicting that nobody converts is right about 84.7% of the time, because about 84.7% of visitors don’t convert. A logistic regression on the behavior features scores about 85.8%. That’s only about one percentage point better, and the model flags fewer than 5% of visitors as likely buyers.

Does that make the model useless? No. Accuracy is the wrong yardstick when one class is rare. The model ranks visitors well; it just rarely becomes more than 50% sure of a conversion. In the classification section you’ll measure it with precision, recall and ROC-AUC instead. The lesson for now: a number only means something next to a baseline. For regression the usual baseline is “always predict the training mean” (DummyRegressor).

Leakage: when the test set isn’t really unseen

  • Preprocessing on all rows. If you compute scaling statistics or fill missing values using the full dataset before splitting, the test rows have influenced training. Fit preprocessing on the training data only. Pipelines, covered later, do this for you.
  • Duplicates. The same customer appearing in both sets lets the model recognize rather than predict.
  • Time. When you’ll predict the future, split by time instead: train on January and February, test on March. A random split lets the model peek at the future.

In Python

from sklearn.linear_model import LogisticRegression

model = LogisticRegression(max_iter=1000).fit(X_train, y_train)
model.score(X_test, y_test)          # accuracy on unseen rows
model.predict(X_test).mean()         # share predicted to convert

max_iter=1000 gives the solver enough steps to converge on unscaled features. You’ll scale features properly when logistic regression gets its own lesson.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

A stratified train/test split

Split X and y with train_test_split(X, y, test_size=0.25, random_state=42, stratify=y).

  • X_train, X_test, y_train, y_test: the four pieces, in that order
  • train_rate, test_rate: the conversion rate in y_train and in y_test, each rounded

to 4 decimals

Because of stratify=y, both rates match the full dataset's rate.

Need a hint?
  1. train_test_split returns four objects; unpack them as X_train, X_test, y_train, y_test = ....
  2. The mean of a 0/1 Series is the share of 1s.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X = audience[features]
y = audience["converted"]

X_train = X_test = y_train = y_test = None
train_rate = None
test_rate = None
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
2

Beat the baseline

Using the split from the previous task:

  • baseline: a DummyClassifier(strategy="most_frequent") fitted on the training data
  • baseline_acc: its accuracy on the test set, rounded to 4 decimals
  • model: a LogisticRegression(max_iter=1000) fitted on the training data
  • model_acc: its accuracy on the test set, rounded to 4 decimals
  • share_flagged: the share of test visitors the model predicts will convert

(model.predict(X_test).mean()), rounded to 4 decimals

.score(X, y) returns a classifier's accuracy. How much better than the baseline is the model?

Need a hint?
  1. Both models use the same API: .fit(X_train, y_train), then .score(X_test, y_test).
  2. model.predict(X_test) is an array of 0s and 1s, so its mean is the share predicted to convert.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression

audience = pd.read_csv("audience.csv")
features = ["sessions_30d", "pages_viewed_30d", "minutes_on_site_30d", "cart_adds_30d",
            "days_since_last_visit", "past_purchases", "email_subscriber", "ad_impressions_7d"]
X = audience[features]
y = audience["converted"]
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, random_state=42, stratify=y
)

baseline = None
baseline_acc = None
model = None
model_acc = None
share_flagged = None
print(baseline_acc, model_acc, share_flagged)
Files in the working directory
audience.csv (5,000 rows)
user_id, age, country, device, source, sessions_30d, pages_viewed_30d, minutes_on_site_30d, cart_adds_30d, days_since_last_visit, past_purchases, email_subscriber, ad_impressions_7d, converted
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status