Sub topic 11
When neural networks are worth trying
This chapter assumes you can build a scikit-learn pipeline, score models with cross-validation, and have a baseline and a gradient-boosted model from earlier chapters. Here you decide whether a neural network deserves a place in the comparison.
The default expectation
On typical tabular data, gradient-boosted trees match or beat neural networks, and they usually need less tuning. Trees handle mixed column types, skewed values, and irrelevant features without much help. A neural network expects scaled numeric inputs. It is sensitive to learning rate and architecture, and its results vary more from run to run.
So a neural network is not the first model you reach for. It is a candidate you add when the data or the deployment setting gives a reason.
Situations that justify a try
- Large datasets. With hundreds of thousands of rows or more, a network has enough data to learn smooth, flexible functions. On a few thousand rows it tends to overfit or underperform trees.
- High-cardinality categories. A column like user ID or product ID can be given a learned embedding, which is a dense vector the network trains for each category. One-hot encoding such a column is wasteful.
- Multiple data types in one model. If rows also carry text, images, or sequences, a network can combine them with the tabular columns.
- Multiple outputs or custom losses. One network can predict several targets at once, or optimize a loss that tree libraries do not support.
- Smooth relationships. Where the target changes smoothly with the inputs, a network can fit it better than piecewise-constant trees.
- Ensemble diversity. A network's errors often differ from a tree model's, so averaging the two can help.
A fair first test
Start with scikit-learn's MLPClassifier. It needs scaled numeric inputs, so it reuses the same kind of preprocessing pipeline. The code below is self-contained and scores the network against boosting on identical folds.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.impute import SimpleImputer
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.neural_network import MLPClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
models = {
"hist_gb": make_pipeline(preprocess, HistGradientBoostingClassifier(random_state=0)),
"mlp": make_pipeline(
preprocess,
MLPClassifier(hidden_layer_sizes=(64, 32), early_stopping=True,
max_iter=500, random_state=0),
),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(f"{name}: {scores.mean():.3f} +/- {scores.std():.3f}")early_stopping=True holds out part of each training fold to decide when to stop. That keeps the test fold untouched.
Common errors
- Skipping scaling. Unscaled inputs make training slow or unstable.
- Comparing a tuned tree model with an untuned network. Give both a similar tuning budget, as covered in the tuning chapter.
- Ignoring seed variance. Different random seeds give different networks. Compare the spread across folds and seeds, not a single score.
- Choosing the network for its reputation. If the gain is within one standard deviation, the simpler model wins.
Exercise
You have 3,000 rows, 20 mostly numeric columns, and a tuned gradient-boosting model with an AUC of 0.91. A colleague suggests a neural network. Is it worth trying, and how would you judge the result?
Show answer
It is a low-priority experiment. The dataset is small, with no high-cardinality IDs and no mixed data types, so boosting is likely to hold up. If you try it, build the network inside the same preprocessing pipeline, score it on the same folds and metric, and give it a comparable tuning budget. Keep it only if its mean AUC beats 0.91 by more than the standard deviation across folds, or if an averaged ensemble of the two clearly improves the score.