Sub topic 5
Simple Models as Strong Baselines
This chapter assumes you know scikit-learn's fit/predict API and have a metric and a held-out split from earlier chapters. It also assumes you can compare a score to a trivial baseline such as DummyClassifier. Here you build the next rung: a regularized linear model and a shallow decision tree.
Why the second baseline matters
A trivial baseline tells you whether a model learned anything. It does not tell you whether a complex model is worth its cost. A tuned linear model or a depth-limited tree often gets most of the achievable score with little code, fast training, and output you can inspect.
If a gradient-boosted ensemble beats the dummy by 30 points, that looks impressive. If a logistic regression beats the dummy by 28 points, the ensemble's real contribution is 2 points. The simple model is the baseline that puts that gain at its true size.
Both model families share useful properties:
- They train in seconds, so you can run repeated cross-validation freely.
- They have few hyperparameters, so there is little tuning to overfit.
- You can read their behavior from coefficients or tree rules, which helps you catch leakage and data bugs early.
Linear models
A linear model predicts from a weighted sum of the features. Use LogisticRegression for classification and Ridge or LinearRegression for regression. Regularization (a penalty on large weights) is on by default in LogisticRegression and Ridge, and it is sensitive to feature scale. Scale numeric features first.
Put the scaler inside a Pipeline. The pipeline refits the scaler on each training fold only. If you scale the whole dataset before cross-validation, statistics from the validation rows leak into training.
from sklearn.datasets import make_classification
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=2000, weights=[0.95, 0.05], random_state=0)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
models = {
"dummy": DummyClassifier(strategy="prior"),
"logreg": make_pipeline(
StandardScaler(), LogisticRegression(max_iter=1000)
),
"logreg balanced": make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000, class_weight="balanced"),
),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=cv, scoring="balanced_accuracy")
print(f"{name:16s} {scores.mean():.3f} +/- {scores.std():.3f}")The dummy scores 0.5 on balanced accuracy. The two logistic models are both clearly above it. With class_weight="balanced" the model trades some precision for recall on the rare class, which balanced accuracy rewards. That choice follows from the metric, so decide the metric first.
Mixed data types
Real tables have categories and missing values. A ColumnTransformer handles each column type inside the pipeline, so all preprocessing is fitted per fold.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyRegressor
from sklearn.impute import SimpleImputer
from sklearn.linear_model import Ridge
from sklearn.model_selection import KFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 600
df = pd.DataFrame(
{
"area": rng.normal(80, 20, n),
"rooms": rng.integers(1, 6, n).astype(float),
"city": rng.choice(["a", "b", "c"], n),
}
)
price = (
2.0 * df["area"]
+ 10 * df["rooms"]
+ df["city"].map({"a": 50, "b": 0, "c": -30})
+ rng.normal(0, 10, n)
)
df.loc[rng.random(n) < 0.1, "area"] = np.nan # missing values after the target is built
prep = ColumnTransformer(
[
(
"num",
make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
["area", "rooms"],
),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
]
)
cv = KFold(n_splits=5, shuffle=True, random_state=0)
for name, model in [
("median", DummyRegressor(strategy="median")),
("ridge", make_pipeline(prep, Ridge(alpha=1.0))),
]:
scores = cross_val_score(
model, df, price, cv=cv, scoring="neg_mean_absolute_error"
)
print(name, round(-scores.mean(), 2))handle_unknown="ignore" keeps the pipeline from failing when a validation fold contains a category the training fold never saw. Scikit-learn reports error metrics as negative scores so that higher is always better, which is why the code negates the mean.
Shallow decision trees
A decision tree predicts by asking a sequence of yes/no questions about the features. A tree with no depth limit memorizes the training data. Limit it with max_depth, min_samples_leaf, or both. A tree of depth 2 to 5 is a useful baseline because it can capture two things a linear model cannot: interactions between features and step-shaped effects.
Trees need no feature scaling. They do not extrapolate, though. A regression tree never predicts outside the range of target values it saw in training, which matters for trending data.
The next example uses a pattern where the label depends on the signs of two features together (an XOR). No straight line separates the classes.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(0)
X = rng.uniform(-1, 1, size=(1000, 2))
y = ((X[:, 0] > 0) ^ (X[:, 1] > 0)).astype(int)
flip = rng.random(1000) < 0.05 # 5% label noise
y = np.where(flip, 1 - y, y)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
candidates = [("logreg", LogisticRegression())]
for depth in [1, 2, 3, 6, None]:
candidates.append(
(f"tree depth={depth}", DecisionTreeClassifier(max_depth=depth, random_state=0))
)
for name, model in candidates:
scores = cross_val_score(model, X, y, cv=cv, scoring="accuracy")
print(f"{name:18s} {scores.mean():.3f}")Expect the logistic regression near 0.5 and the depth-1 tree similar, since one split cannot express an XOR. The depth-2 tree should be near 0.95, matching the 5% noise. Deeper trees add no real gain and start fitting the flipped labels. That plateau is what you look for when choosing depth.
Run both families. Each fails where the other works, so the pair shows what structure the data has.
Choosing between them
| Property | Regularized linear model | Shallow tree |
|---|---|---|
| Needs scaling | Yes | No |
| Captures interactions | Only if you add them | Yes, up to its depth |
| Extrapolates beyond training range | Yes | No |
| Handles unseen magnitudes | Smoothly | Flat beyond the last split |
| Main tuning knob | Regularization strength | `max_depth`, `min_samples_leaf` |
| Typical failure | Underfits nonlinear data | Unstable splits on small data |
Common errors
- Preprocessing outside the pipeline. Scaling, imputing, or encoding on the full dataset before splitting leaks information. Always fit these steps inside the cross-validation loop.
- Tuning the depth on the test set. Choose
max_depthwith cross-validation on the training data. Touch the test set once, at the end. - Comparing on different splits. Give every model the same
cvobject, as in the examples above. Different folds add noise to the comparison. - Ignoring convergence warnings. A
ConvergenceWarningfromLogisticRegressionmeans the fit is incomplete. Scale the features or raisemax_iter. - Under-tuning the baseline while over-tuning the candidate. Give the baseline a fair, small search over its one or two knobs. A weak baseline makes any candidate look good.
- Reading coefficients as importance without scaling. Coefficients are only comparable across features when the features share a scale.
Edge cases
Small datasets. With a few hundred rows, tree structure changes a lot between folds. Prefer a larger min_samples_leaf and report the spread across repeated folds, not one score.
Skewed regression targets. A linear model on a long-tailed target is dominated by a few large values. Consider TransformedTargetRegressor with a log transform. Score the final result in the original units, because that is what users see.
Time series. A linear model on lagged values (yesterday, a week ago) is a stronger baseline than the naive forecast and still cheap. Split by time, never at random, and keep every lag feature built only from the past. A tree cannot extrapolate a trend, so use it on detrended or differenced data, or expect flat forecasts.
Many features. With more features than rows, a linear model needs stronger regularization. Raise alpha for Ridge, or lower C for LogisticRegression, and choose it by cross-validation.
Exercise
A team reports that its gradient-boosted model scores 0.91 balanced accuracy and the majority-class dummy scores 0.50. A scaled logistic regression, run on the same folds, scores 0.90. What does this tell you, and what would you check before deciding the boosted model is worth shipping?
Show answer
The simple model captures nearly all of the gain over the dummy, so the boosted model adds only about 0.01. Check whether that 0.01 is larger than the run-to-run spread across repeated folds, and whether it justifies the extra training cost, maintenance, and loss of interpretability. Also confirm the logistic regression's preprocessing sits inside the pipeline, so its score is not inflated or deflated by leakage.
Exercise
You fit a depth-2 tree and a logistic regression on a dataset. The tree scores 0.95 and the logistic regression scores 0.52, where 0.50 is chance. What does the gap suggest about the data, and what is one error to rule out?
Show answer
The large gap suggests that the label depends on an interaction or threshold pattern that a single linear boundary cannot express. Rule out a scaling or preprocessing mistake that handicaps the linear model, such as unscaled features with strong regularization, or a missing interaction term you could add by hand.