Sub topic 11
When Neural Networks Are Worth Trying
This chapter assumes you can already build a scikit-learn pipeline, run cross-validation, and read the scores of a linear model, a random forest, and a gradient-boosted model on the same folds. Here you will learn when a neural network deserves a place in that comparison, how to give it a fair trial, and when to leave it out.
The default expectation
On rows-and-columns data, gradient-boosted trees are usually the model to beat. Studies that compare methods on many medium-sized tabular datasets keep finding that tree ensembles match or beat neural networks, and they take far less tuning. A neural network is therefore a challenger, not a starting point. You try one when you have a specific reason to expect it to help.
Trees do well on tabular data for a few reasons:
- Columns often have different meanings and scales. A tree splits each column on its own and does not care about units.
- Many columns are uninformative. Trees mostly ignore them. A network has to learn to give them near-zero weight.
- Target functions often have sharp thresholds, such as "age over 65" or "balance equals zero". Trees represent these directly. Networks produce smooth functions and need more data to approximate a step.
- Rare category levels and skewed numeric columns hurt networks unless you preprocess them carefully.
Images, audio, and text have spatial or sequential structure that neural architectures exploit. Tabular rows usually have no such structure, so a network has less to exploit.
When a network is worth a trial
Run the experiment when at least one of these holds:
| Situation | Why a network may help |
|---|---|
| Very large dataset (hundreds of thousands of rows or more) | Networks keep improving with data, and the gap to trees can narrow. |
| High-cardinality categorical columns (user IDs, product IDs) | Learned embeddings give each level a dense vector and let levels share information. |
| Text, images, or sequences sit next to the tabular columns | One network can combine all inputs and train end to end. |
| Several targets to predict at once | A network can share hidden layers across targets (multi-task learning). |
| You must update the model online or in small batches | Networks train with incremental gradient steps. |
| Predictions must be smooth in the inputs | Trees give step-shaped outputs. A network gives a smoother surface. |
| You want to reuse a pretrained component | Embeddings from another model can be features here. |
If none of these applies, a network is unlikely to repay the extra tuning and maintenance. If the dataset has fewer than a few thousand rows, skip it unless you have a strong reason, because networks overfit small tables easily.
What a network needs from your pipeline
Preprocessing matters more for a network than for trees, because gradient descent is sensitive to input scale and to missing values.
- Scale numeric columns. Use
StandardScaler. For heavy-tailed columns such as income, apply a log transform orQuantileTransformerfirst. - Impute missing values. Networks cannot take NaN. Consider adding a missing-indicator column, since "missing" is often informative.
- Encode categories. One-hot works for low cardinality. For high cardinality, use learned embeddings in a deep-learning library. A one-hot layer with thousands of columns is wasteful.
- Fit all of this inside the fold. The pipeline from earlier chapters already does this. Keep using it so the scaler never sees validation rows.
A first fair trial with scikit-learn
MLPClassifier is a plain multilayer perceptron (a stack of fully connected layers). It is enough to test whether a network is competitive at all before you invest in a deep-learning framework. The script below is self-contained. It builds the same synthetic table and folds as earlier chapters, and it scores the network next to a gradient-boosted model.
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)
mlp = make_pipeline(
preprocess,
MLPClassifier(
hidden_layer_sizes=(64, 32),
alpha=1e-3,
early_stopping=True,
n_iter_no_change=10,
max_iter=500,
random_state=0,
),
)
hist_gb = make_pipeline(preprocess, HistGradientBoostingClassifier(random_state=0))
for name, model in [("mlp", mlp), ("hist_gb", hist_gb)]:
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(f"{name}: {scores.mean():.3f} +/- {scores.std():.3f}")Three settings in the network deserve attention:
early_stopping=Trueholds out 10% of each training fold as an internal validation set and stops when its score stops improving. This guards against overfitting without touching the outer validation fold.alphais an L2 penalty on the weights. Raise it if the training score is far above the validation score.random_statefixes the weight initialization. A network trained from different seeds can give noticeably different scores, so see the next section.
Fair-comparison traps specific to networks
A network introduces sources of variance that trees mostly lack.
- Seed variance. Run the network with several seeds, for example 5, and report the mean and spread. If one lucky seed beats the boosted model, that tells you nothing.
- Tuning budget. Networks have more sensitive hyperparameters: learning rate, width, depth, weight decay, batch size. Give the network a tuning budget comparable to the one you gave the trees, using nested cross-validation as in the tuning chapter. A network with default settings losing to a tuned forest is an unfair result.
- Early stopping inside the fold. Never choose the stopping epoch by looking at the outer validation fold. That leaks information. Use an internal split, as
early_stopping=Truedoes. - Same folds, same metric. Keep the
cvobject andscoringidentical across all candidates. - Compare against the noise. If a network's mean AUC is 0.004 above boosting and the fold standard deviation is 0.02, that is a tie. Treat a tie as a win for the simpler model.
Where scikit-learn stops
MLPClassifier has no GPU support, no embedding layers, no custom losses, and no mini-batch pipelines for data that does not fit in memory. When your trial suggests a network is promising, or when you need embeddings for high-cardinality categories, move to PyTorch or Keras. Some tabular-specific architectures exist, including attention-based models and networks designed to resemble trees. They can be competitive on large datasets, but they add dependencies and tuning, so treat them as further challengers and not defaults.
Moving off scikit-learn changes the evaluation too. Keep the same fold indices and the same metric. Save the fold assignments, for example with list(cv.split(X, y)), and reuse them in the other framework so the comparison stays fair.
Cost of choosing a network
Even a winning network brings costs, which the practical-constraints chapter covers in detail:
- Training takes longer, and needs a GPU for large inputs.
- Predictions are harder to explain than a linear model's coefficients or a tree's split rules.
- Retraining is less repeatable because of random initialization.
- Serving needs a framework runtime in addition to, or instead of, scikit-learn.
A small gain in the metric rarely justifies all four. A large gain on a high-value problem might.
Summary
Treat a neural network as a challenger to a tuned gradient-boosted model. Try it when you have lots of data, high-cardinality categories, mixed input types, or multiple targets. Scale and impute inputs inside the pipeline, run several seeds, give it a tuning budget equal to the trees', and compare on identical folds. Accept it only if the improvement clearly exceeds fold noise and the added cost is acceptable.
Exercise
A colleague reports that a neural network scored 0.912 AUC and a tuned gradient-boosted model scored 0.908 on the same 5 folds, whose standard deviation is about 0.015. The network was trained once with a single seed, and its early-stopping epoch was chosen by looking at the validation fold's score. List the problems with this comparison and say what you would do next.
Show answer
There are three problems. First, the 0.004 gap is far smaller than the fold standard deviation of 0.015, so the result is a tie. Second, a single seed hides the network's seed variance, and one run may be lucky. Third, choosing the stopping epoch with the validation fold leaks information from that fold into training and inflates the network's score. Next, I would use an internal split for early stopping (early_stopping=True or a nested validation set), train the network with about five seeds, report the mean and spread, and give it a tuning budget comparable to the boosted model's. If the difference still falls inside the noise, I would keep the simpler gradient-boosted model.