MLPs on Tabular Data
Most data in companies is a table: one row per customer, loan, patient or machine, a few dozen columns of numbers and categories, a few thousand to a few million rows. A multilayer perceptron can learn from such a table, and it is the natural part of a larger network (a recommender, a model that also reads text or images). But on plain tables it has strong competitors: regularised linear models and gradient-boosted trees, which are fast, need little tuning and are often more accurate. This lesson trains an MLP on a real table the right way (scaling fitted on the training rows only, validation for every choice, the test set once), compares it honestly with logistic regression and gradient boosting, and shows in a controlled experiment when and why MLPs lose.
The building blocks are from earlier lessons: the MLP forward pass, training loop, dropout and weight decay. The data handling is from Machine Learning: Data Preparation: scalers, one-hot and ordinal encoding, leakage rules.
What an MLP needs from a table
An MLP computes for the whole row at once. Two consequences:
- Scale. Every feature enters the same dot products. A column in the thousands next to one in the hundredths makes the first one dominate the initial pre-activations and the gradients, so the optimiser zigzags. Standardise each numeric column, , with and computed on the training rows only, then apply the same transform to validation and test rows. Trees, by contrast, only compare a feature with thresholds and do not care about scale.
- Encoding. Categories must become numbers: one-hot columns for few categories, or a learned embedding vector per category for many (Embedding Layers). Missing values need an explicit treatment (an imputed value plus a "was missing" indicator column), because NaN propagates through every matrix product.
The comparison on a real table
The Wisconsin breast cancer table that ships with scikit-learn: 569 rows, 30 numeric features computed from cell-nucleus images, a binary label (malignant or benign). 20 % is held back as a test set; the remaining 455 development rows are compared with stratified 5-fold cross-validation, where every pipeline is refitted on each fold, scaler included. The MLP has hidden layers of 64 and 32 ReLU units and an L2 penalty alpha=1.0; it is shown with and without scaling.
import warnings
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.exceptions import ConvergenceWarning
warnings.simplefilter("ignore", ConvergenceWarning)
X, y = load_breast_cancer(return_X_y=True)
X_dev, X_te, y_dev, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
print("development rows:", len(y_dev), " test rows:", len(y_te), " features:", X.shape[1])
print("feature ranges: smallest max", round(float(X_dev.max(0).min()), 4), " largest max", round(float(X_dev.max(0).max()), 1))
models = {
"logistic (scaled)": make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
"MLP, no scaling": MLPClassifier(hidden_layer_sizes=(64, 32), max_iter=500, random_state=0),
"MLP (scaled)": make_pipeline(StandardScaler(),
MLPClassifier(hidden_layer_sizes=(64, 32), alpha=1.0, max_iter=500,
random_state=0)),
"gradient boosting": HistGradientBoostingClassifier(random_state=0),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
for name, model in models.items():
res = cross_validate(model, X_dev, y_dev, cv=cv, scoring=("accuracy", "neg_log_loss"))
acc, ll = res["test_accuracy"], -res["test_neg_log_loss"]
print(f"{name:19s} accuracy {acc.mean():.3f} +- {acc.std():.3f} log loss {ll.mean():.3f}")
final = models["logistic (scaled)"].fit(X_dev, y_dev) # chosen by cross-validation, refit on all dev rows
print(f"test accuracy of the chosen model, measured once: {final.score(X_te, y_te):.3f}")development rows: 455 test rows: 114 features: 30
feature ranges: smallest max 0.0219 largest max 4254.0
logistic (scaled) accuracy 0.978 +- 0.010 log loss 0.079
MLP, no scaling accuracy 0.921 +- 0.031 log loss 0.199
MLP (scaled) accuracy 0.974 +- 0.019 log loss 0.074
gradient boosting accuracy 0.963 +- 0.026 log loss 0.127
test accuracy of the chosen model, measured once: 0.982
The columns' maxima range from 0.0219 to 4254, five orders of magnitude. Without scaling the MLP reaches 0.921 accuracy with a large spread between folds (0.031); with the scaler in the pipeline it reaches 0.974 and the best log loss, 0.074. Logistic regression is just as good (0.978, log loss 0.079) with a tenth of the tuning, and gradient boosting is a little behind on this small, smooth problem (0.963). The differences between the scaled models are within one fold standard deviation: on 455 rows, a 1-point difference is about one patient per fold. The simplest model, logistic regression, was therefore chosen, refitted on all development rows, and scored once on the test set: 0.982.
Note: the scaler is part of the pipeline, so
cross_validatefits it on the four training folds and applies it to the fifth. Scaling all 455 rows first and then cross-validating would leak the held-out fold's means and standard deviations into training (Data Leakage).
When MLPs lose
Benchmarks over many tabular datasets (for example Grinsztajn, Oyallon and Varoquaux, 2022) found tree ensembles ahead of MLPs on typical medium-sized tables and traced it to three properties of such data:
- Uninformative columns. Tables often contain many features that do not matter. Trees ignore a column they never split on; an MLP mixes every input into every hidden unit, and must learn to drive the weights of useless columns to zero from noisy gradients.
- Irregular targets. Business rules, thresholds and tariffs make the target a step function of the features. Trees are piecewise constant, the right shape; MLPs are smooth and have a bias towards smooth functions.
- Meaningful columns. Each column of a table is a separate quantity. An MLP's first layer is invariant to rotating the feature space (it can learn any linear mix), which wastes capacity on mixtures that mean nothing, while trees work on one column at a time.
The second experiment isolates the first two. The target is a set of threshold rules on two uniform features (an axis-aligned, step-shaped boundary); 0, 10 or 40 columns of pure noise are added. 1000 rows train each model, 500 others measure it.
import warnings
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.exceptions import ConvergenceWarning
warnings.simplefilter("ignore", ConvergenceWarning)
rng = np.random.default_rng(0)
n = 1500
base = rng.uniform(-1, 1, (n, 2))
# an irregular, axis-aligned target made of thresholds, typical of rules in business data
x0, x1 = base[:, 0], base[:, 1]
y = (((x0 > 0.2) & (x1 < 0.5)) | (x0 < -0.6) | ((x1 > 0.8) & (x0 < 0.5))).astype(int)
print("class balance:", round(float(y.mean()), 3))
for n_noise in (0, 10, 40):
X = np.hstack([base, rng.normal(0, 1, (n, n_noise))]) # informative columns + useless ones
X_tr, X_va, y_tr, y_va = X[:1000], X[1000:], y[:1000], y[1000:]
mlp = make_pipeline(StandardScaler(), MLPClassifier(hidden_layer_sizes=(128, 64), max_iter=400, random_state=0))
gbm = HistGradientBoostingClassifier(random_state=0)
scores = [m.fit(X_tr, y_tr).score(X_va, y_va) for m in (mlp, gbm)]
print(f"{n_noise:2d} useless features: MLP {scores[0]:.3f} gradient boosting {scores[1]:.3f}")class balance: 0.574
0 useless features: MLP 0.986 gradient boosting 0.994
10 useless features: MLP 0.884 gradient boosting 0.994
40 useless features: MLP 0.646 gradient boosting 0.992
With only the two informative columns both models do well (0.986 and 0.994). Add 10 noise columns and the MLP falls to 0.884 while gradient boosting stays at 0.994; with 40 noise columns the MLP is at 0.646, barely above always predicting the majority class (0.574), and boosting still at 0.992. With 1000 rows the MLP cannot tell which of the 42 inputs matter, and every noise column adds variance to every hidden unit. Feature selection, stronger weight decay or many more rows narrow the gap; a tree ensemble just does not have it.
When an MLP is the right choice for tabular data:
- the table is part of a larger network (images or text plus metadata, a recommender with user and item embeddings), so everything is trained end to end;
- there are many high-cardinality categorical columns, where learned embeddings beat one-hot encodings;
- the data is large (millions of rows) and smooth, or you need a differentiable model (for example to optimise inputs or to fine-tune with other losses);
- you want to share representations across tasks or pre-train on unlabelled rows.
Otherwise start with gradient boosting (XGBoost, LightGBM, CatBoost) and a regularised linear model as baselines, and make a neural network beat them on validation data before using it. Specialised architectures for tables (TabNet, FT-Transformer, and pretrained models such as TabPFN for small tables) close some of the gap, but the baseline rule stays.
The same MLP in PyTorch
The recorded version (PyTorch 2.14.1 on CPU) splits the development rows again into 341 training and 114 validation rows, fits the scaler on the 341, trains a 30-64-32-1 MLP with dropout 0.2 and AdamW (weight decay 0.01) using BCEWithLogitsLoss, stops early when the validation loss has not improved for 20 epochs, restores the best weights, and evaluates the test set once.
import copy
import torch
from torch import nn
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
X_dev, X_te, y_dev, y_te = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_tr, X_va, y_tr, y_va = train_test_split(X_dev, y_dev, test_size=0.25, random_state=0, stratify=y_dev)
scaler = StandardScaler().fit(X_tr) # fitted on the training rows only
to_t = lambda a: torch.tensor(a, dtype=torch.float32)
X_tr, X_va, X_te = (to_t(scaler.transform(a)) for a in (X_tr, X_va, X_te))
y_tr, y_va, y_te = (to_t(a) for a in (y_tr, y_va, y_te))
print("train", len(y_tr), " validation", len(y_va), " test", len(y_te))
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(30, 64), nn.ReLU(), nn.Dropout(0.2),
nn.Linear(64, 32), nn.ReLU(), nn.Dropout(0.2), nn.Linear(32, 1))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)
loss_fn = nn.BCEWithLogitsLoss()
def evaluate(X, y):
model.eval()
with torch.no_grad():
logits = model(X).squeeze(1)
return loss_fn(logits, y).item(), ((logits > 0).float() == y).float().mean().item()
best, best_state, patience, wait = float("inf"), None, 20, 0
gen = torch.Generator().manual_seed(0)
for epoch in range(1, 301):
model.train()
for idx in torch.randperm(len(y_tr), generator=gen).split(32):
loss = loss_fn(model(X_tr[idx]).squeeze(1), y_tr[idx])
opt.zero_grad(); loss.backward(); opt.step()
val_loss, val_acc = evaluate(X_va, y_va)
if val_loss < best - 1e-4:
best, best_state, best_epoch, wait = val_loss, copy.deepcopy(model.state_dict()), epoch, 0
else:
wait += 1
if wait == patience:
break
print(f"stopped at epoch {epoch}, best epoch {best_epoch}, best val loss {best:.4f}")
model.load_state_dict(best_state)
print("val loss {:.4f} acc {:.3f}".format(*evaluate(X_va, y_va)))
print("test loss {:.4f} acc {:.3f} (measured once)".format(*evaluate(X_te, y_te)))train 341 validation 114 test 114
stopped at epoch 69, best epoch 49, best val loss 0.0246
val loss 0.0246 acc 0.991
test loss 0.1350 acc 0.956 (measured once)
Training stopped at epoch 69 with the best validation loss 0.0246 at epoch 49, and 0.991 validation accuracy. The test set tells a less flattering story: loss 0.1350, accuracy 0.956, below the 0.982 of logistic regression. Part of the gap is luck of the split (114 test rows, one row is 0.009), part is selection: the epoch was chosen because it did best on those 114 validation rows, so the validation score is optimistic. This is why the test set is touched once, and why the cross-validated comparison above is a better basis for choosing between model families than one validation split.
Tips that matter for tabular MLPs
- Scale and clip. Standardise; for heavy-tailed columns (incomes, counts) apply a log or a quantile transform first. Clip extreme values on new data to the training range.
- Small and regularised. Two or three hidden layers of 64 to 512 units, dropout 0.1 to 0.3, weight decay, early stopping. Bigger is rarely better on small tables.
- Batch normalisation or a residual structure helps deeper tabular MLPs train (Residual Connections).
- Categoricals as embeddings with dimension around for categories (a common heuristic, not a law), concatenated with the scaled numeric columns (Embedding Layers).
- Ensembling several seeds of the MLP, or the MLP with a boosted model, often gains more than tuning either.
Pitfalls
- Fitting the scaler on all rows. Small but real leakage; it also hides problems with new data whose range differs from training.
- Comparing a tuned MLP with default baselines. Tune all candidates on the same validation data, or the comparison measures your effort, not the models.
- One split, one seed. On a few hundred rows, differences of a point or two are noise; use cross-validation and several seeds.
- Forgetting that trees need nothing. If the MLP needs a long preprocessing pipeline to match a boosted model on raw columns, count that maintenance cost too.
- Integer-coded categories fed as numbers. Category 7 is not "more" than category 3; an MLP will treat it as such. Use one-hot or embeddings.
Practice
- Why does the unscaled MLP do worse, even though a linear layer could in principle learn to rescale each column?
Answer
It could, but gradient descent has to get there. With columns from 0.02 to 4254, the large columns dominate the initial pre-activations (many ReLUs start saturated or dead) and the loss surface is badly conditioned: a learning rate small enough for the large-scale weights is far too small for the others. Standardising gives every column a comparable scale at the start.
- In the noise-column experiment, what accuracy would always predicting the majority class give, and how does the MLP with 40 noise columns compare?
Answer
The class balance is 0.574, so predicting class 1 always gives about 0.574 (on the validation rows the share is similar). The MLP's 0.646 is only about 7 points better, while boosting reaches 0.992.
- Write the scikit-learn pipeline for a table with numeric columns
numand categorical columnscat, scaled numbers and one-hot categories, feeding anMLPClassifier.
Answer
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import make_pipeline
from sklearn.neural_network import MLPClassifier
prep = ColumnTransformer([
("num", StandardScaler(), num),
("cat", OneHotEncoder(handle_unknown="ignore"), cat),
])
model = make_pipeline(prep, MLPClassifier(hidden_layer_sizes=(64, 32), alpha=1e-3, random_state=0))Everything inside the pipeline is fitted on the training folds only.
Test yourself
On which rows must the standardisation of an MLP's inputs be fitted?
- All rows, including the test set
- The training rows only, then applied to validation and test
- The test rows
- It does not matter for MLPs
In the experiment with 40 useless noise columns, what happened?
- Both models stayed near 0.99
- The MLP fell to 0.646 while gradient boosting stayed at 0.992
- Gradient boosting fell to chance
- The MLP improved
Which situation favours an MLP over gradient boosting on tabular data?
- 500 rows of smooth numeric data with many irrelevant columns
- The table is one input of a larger network trained end to end, or has many high-cardinality categorical columns
- Targets defined by threshold rules
- When no time is available for preprocessing
The PyTorch MLP had 0.991 validation accuracy but 0.956 on the test set. What is the most likely explanation?
- A bug in the test evaluation
- The best epoch was selected on the 114 validation rows, so the validation score is optimistic, and 114 rows are a noisy measurement
- The test set is from another hospital
- Dropout was on during the test