Section 3 · Lesson 3

Decision trees and ROC-AUC

See how trees split data and which features they rely on, then compare models across every threshold with the ROC curve and AUC.

45 min 2 practice tasks
ROC and AUC, Clearly Explained! by StatQuest with Josh Starmer on YouTube

Logistic regression draws one smooth boundary through the data. A decision tree carves the data into boxes with a sequence of yes/no questions. Trees also power the strongest tabular models (random forests and gradient boosting) that you’ll meet in the last section, so it pays to understand them.

How a tree is grown

At each step the tree considers every feature and every possible cut-off (“cart_adds_30d ≤ 0.5?”, “days_since_last_visit ≤ 3.5?”) and picks the split that makes the two resulting groups purest. Purity is usually measured with Gini impurity:

Gini = 1 - p0² - p1²

A group that is all buyers or all non-buyers has Gini 0, and a 50/50 group has Gini 0.5. The tree repeats this inside each group until it hits a stopping rule: max_depth, a minimum number of rows per leaf (min_samples_leaf), or pure leaves. Each leaf predicts the share of buyers among the training rows that landed in it.

Strengths: no scaling needed, natural handling of thresholds and interactions (“recent and added to cart”), and rules a marketer can read. Weaknesses: deep trees overfit (you saw a fully grown tree lose to the baseline), small changes in the data can produce a very different tree, and a depth-4 tree can output at most 16 different probabilities.

feature_importances_ adds up how much each feature reduced impurity across all its splits. On our data the depth-4 tree leans hardest on cart_adds_30d, then recency.

Comparing models without picking a threshold

The last lesson showed that precision and recall depend on the threshold. To compare two models fairly you want a measure that covers all thresholds at once.

The ROC curve plots, for every possible threshold:

  • the true positive rate (recall), the share of buyers flagged, on the y-axis
  • the false positive rate, the share of non-buyers flagged, on the x-axis

A threshold of 1 flags nobody, the point (0, 0). A threshold of 0 flags everybody, the point (1, 1). A useless model runs along the diagonal and a perfect one hugs the top-left corner.

The area under the curve (AUC) sums this up in one number. It also has a neat meaning: AUC is the probability that a randomly chosen buyer gets a higher score than a randomly chosen non-buyer. 0.5 is coin-flipping, 1.0 is perfect ranking.

from sklearn.metrics import roc_auc_score, roc_curve

roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])   # pass probabilities, not labels
fpr, tpr, thresholds = roc_curve(y_test, model.predict_proba(X_test)[:, 1])

Our two models

Model Test ROC-AUC
Logistic regression (scaled) 0.800
Decision tree, depth 4 0.769

The logistic model ranks visitors better. If you mistakenly feed roc_auc_score the 0/1 output of predict, the logistic model scores only about 0.59, because you’ve thrown away its ranking and kept a single threshold.

Reading the ROC curve gives business answers directly. If you’re willing to show ads to 10% of the non-buyers, the logistic model reaches about half of the eventual buyers.

Caveats

  • AUC measures ranking, not calibration. A model can rank perfectly and still report probabilities that are all too high.
  • With very rare positives, the ROC curve can look flattering. The precision–recall curve and its summary, average precision (average_precision_score), focus on the positive class.
  • AUC averages over all thresholds, but you’ll operate at one. Once a model is chosen, go back to precision, recall and costs at the threshold you’ll actually use.

Practice

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

1

What does the tree look at?

Fit a DecisionTreeClassifier(max_depth=4, random_state=42) on the training data.

  • tree: the fitted tree
  • importances: a Series of tree.feature_importances_ indexed by features, sorted from

most to least important

  • top_feature: the name of the most important feature
  • tree_auc: the tree's ROC-AUC on the test set, using its probabilities

(tree.predict_proba(X_test)[:, 1]), rounded to 4 decimals

Need a hint?
  1. pd.Series(tree.feature_importances_, index=features) pairs each importance with its feature name.
  2. roc_auc_score(y_test, scores) takes the true labels first, then the predicted probabilities.
Python 3
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_score

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_train, X_test, y_train, y_test = train_test_split(
    audience[features], audience["converted"], test_size=0.25, random_state=42,
    stratify=audience["converted"],
)

tree = None
importances = None
top_feature = None
tree_auc = None
print(importances, tree_auc)
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

Compare models with ROC-AUC

The starter fits the logistic pipeline lr and the depth-4 tree from the previous task.

  • lr_auc: the logistic model's test ROC-AUC from its probabilities, rounded to 4 decimals
  • auc_from_labels: the AUC you get by mistake if you pass lr.predict(X_test) (hard 0/1

labels) instead of probabilities, rounded to 4 decimals

  • better_model: the string "logistic" or "tree", whichever has the higher AUC from probabilities
  • tpr_at_10: from roc_curve(y_test, lr_proba), the highest true positive rate whose false

positive rate is at most 0.10, rounded to 4 decimals

Need a hint?
  1. roc_curve returns three arrays: fpr, tpr, thresholds = roc_curve(y_test, lr_proba).
  2. Boolean indexing picks the points you can afford: tpr[fpr <= 0.10].max().
Python 3
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_score, roc_curve

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_train, X_test, y_train, y_test = train_test_split(
    audience[features], audience["converted"], test_size=0.25, random_state=42,
    stratify=audience["converted"],
)
lr = make_pipeline(StandardScaler(), LogisticRegression()).fit(X_train, y_train)
tree = DecisionTreeClassifier(max_depth=4, random_state=42).fit(X_train, y_train)
lr_proba = lr.predict_proba(X_test)[:, 1]
tree_auc = roc_auc_score(y_test, tree.predict_proba(X_test)[:, 1])

lr_auc = None
auc_from_labels = None
better_model = None
tpr_at_10 = None
print(lr_auc, auc_from_labels, better_model, tpr_at_10)
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