This is Module 3 of the Machine Learning Engineer path. Most tabular problems in industry are handled by a short list of model families: linear and logistic models, random forests and gradient-boosted trees. Knowing when each one wins matters more than knowing every algorithm. This module compares them on two problems where we know the true answer, so you can see not just which model scored higher, but how close each came to the best possible score.

You’ll build: one script that compares four models and a baseline on two churn problems, using the cross-validation habits from Module 1 and the pipelines from Module 2.

You need: Python with scikit-learn and numpy (pip install scikit-learn numpy).

The experiment

The data is synthetic, so for every customer we know the true probability of leaving. Ranking customers by that true probability gives the best possible ROC AUC: no model can beat it on average, so it tells you how much room is left. Save this as compare.py:

# Three model families on two problems: one where risk changes steadily with each input, one where it is U-shaped.
import time
import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, StandardScaler

rng = np.random.default_rng(7)
n = 5_000
tenure = rng.integers(1, 60, n)
tickets = rng.poisson(1.5, n)
spend = rng.uniform(10, 100, n)
X = np.column_stack([tenure, tickets, spend])

problems = {
    # Each extra ticket raises the odds of leaving, each month of tenure lowers them, by a fixed amount.
    "steady": -1.0 + 0.45 * tickets - 0.05 * tenure,
    # Customers on the cheapest and the most expensive plans leave most; the middle is stable.
    "U-shaped": -2.0 + 0.0015 * (spend - 55) ** 2 + 0.3 * tickets,
}

def add_curve(X):
    """The feature a person adds after plotting churn against spend: distance from the middle price, squared."""
    return np.column_stack([X, (X[:, 2] - 55) ** 2])

models = {
    "baseline (most frequent)": DummyClassifier(strategy="prior"),
    "logistic regression": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
    "logistic + one feature": make_pipeline(FunctionTransformer(add_curve), StandardScaler(),
                                            LogisticRegression(max_iter=1000)),
    "random forest": RandomForestClassifier(n_estimators=300, min_samples_leaf=20, random_state=0, n_jobs=1),
    "gradient boosting": HistGradientBoostingClassifier(random_state=0),
}
for name, logit in problems.items():
    p = 1 / (1 + np.exp(-logit))
    y = (rng.random(n) < p).astype(int)
    # The best any model could do: rank customers by their true probability.
    print(f"\n{name} problem (churn rate {y.mean():.1%}, best possible ROC AUC {roc_auc_score(y, p):.3f})")
    for label, model in models.items():
        t0 = time.perf_counter()
        auc = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
        print(f"  {label:26} ROC AUC {auc.mean():.3f}   {time.perf_counter() - t0:4.1f} s")

Running it prints:

steady problem (churn rate 17.6%, best possible ROC AUC 0.761)
  baseline (most frequent)   ROC AUC 0.500    0.0 s
  logistic regression        ROC AUC 0.761    0.0 s
  logistic + one feature     ROC AUC 0.761    0.0 s
  random forest              ROC AUC 0.747    2.8 s
  gradient boosting          ROC AUC 0.715    0.7 s

U-shaped problem (churn rate 38.1%, best possible ROC AUC 0.754)
  baseline (most frequent)   ROC AUC 0.500    0.0 s
  logistic regression        ROC AUC 0.577    0.0 s
  logistic + one feature     ROC AUC 0.753    0.0 s
  random forest              ROC AUC 0.740    2.6 s
  gradient boosting          ROC AUC 0.721    0.5 s

Your timings will differ; the scores should match closely.

1. When risk changes steadily, the simple model wins

In the first problem, every extra support ticket raises the odds of leaving by the same amount, and every month of tenure lowers them by the same amount. That is exactly the shape logistic regression assumes, and it reached the best possible score, 0.761, in a fraction of a second.

The tree ensembles did worse, not better: 0.747 for the random forest and 0.715 for gradient boosting. Trees approximate a smooth trend with steps, and with noisy data and default settings that costs accuracy as well as time. This is the practical reason behind Rule #4 of Google’s Rules of Machine Learning: “Keep the first model simple and get the infrastructure right.”

2. When the effect is curved, trees find it on their own

In the second problem, customers on the cheapest and the most expensive plans leave most often, and the middle is stable: a U shape. Logistic regression can only draw a straight line through spend, so it misses almost all of the pattern, scoring 0.577 against a possible 0.754.

The random forest found the curve without being told, scoring 0.740. That’s the main strength of tree ensembles: they pick up curves, thresholds and interactions automatically, which is why they are so widely used on tabular data.

Gradient boosting scored a little lower than the random forest in both problems, with default settings on 5,000 noisy rows. Tuning might change that, and that’s the point: treat “the best model” as something you measure on your data, not a reputation. (When data grows to tens of thousands of rows or more, scikit-learn’s histogram-based boosting is the one to reach for: its guide notes it can be orders of magnitude faster than the classic implementation at that scale, with built-in handling of missing values.)

3. One good feature closes the gap

The third row is the most instructive. A person who plots churn rate against spend sees the U shape and adds one feature: the squared distance from the middle price. With it, the same logistic regression scored 0.753, essentially the best possible, while staying instant to train and easy to explain: each coefficient still says how much one input moves the odds.

That’s the real choice in practice:

Linear or logistic model Tree ensembles
Finds curves and interactions Only the ones you add as features Automatically
Speed to train and serve Very fast Slower, larger models
Explaining a prediction Coefficients read directly Needs extra tools
Risk on small, noisy data Low Can fit noise without tuning

How to choose, in order

  1. Baseline first. The most-frequent-class baseline scores 0.5 ROC AUC by construction; every model has to beat it clearly.
  2. Logistic or linear regression next. If it’s close to what you need, you have a fast, explainable model and you’re done.
  3. Plot errors against each input. Curves, thresholds or groups where the model is consistently wrong are structure it can’t express.
  4. Then either add a feature or switch to trees. A feature keeps the model simple when you understand the pattern; a random forest or boosted trees find patterns you haven’t spotted.
  5. Compare on held-out data, and on cost. A gain of 0.01 ROC AUC may not justify a model that’s 100 times slower to train or harder to explain to the people who use it.

Project

Take the pipeline you built in Module 2. Add a random forest and a gradient-boosting version of it, compare all three with 5-fold cross-validation, and write down the score, training time and model file size for each. Then plot the logistic model’s errors against each input, add one feature for the biggest pattern you find, and see whether the simple model catches up.

Next: Module 4: Packaging and Serving a Model, putting your pipeline behind an HTTP endpoint that logs and tests every request.