Neural networks for tables
Hidden units combine straight lines into curves. Train small and deeper networks, keep them from memorizing, and decide when deep learning is worth it for your data.
What runs in CodeSplash
- Neural network (MLP) Verified in Python and R
- Deep neural network (torch MLP) Verified in Python and R
You will be able to
- Describe how hidden units and activations build non-linear boundaries
- Control a network with weight decay, early stopping and its size
- Decide when a network will or won't beat trees on tabular data
Read first
Lines combined
ReadA hidden unit computes a weighted sum, then bends it with an activation, such as ReLU or tanh. One unit draws one soft line. A layer of them combines lines into regions, and more layers combine regions.
Without an activation, stacking layers would give one big linear model. Training is gradient descent on the weights, with backpropagation computing the gradient.
How many units for a ring?
ExploreThe data here is a ring around a core. How few Units per hidden layer will classify it above 0.9 on new data? Each unit draws one line. Press one hidden unit to see what one line can't do.
DExplorable · Neural network playground
How do hidden units combine straight lines into curved boundaries?
Each hidden unit can draw one straight line. How accurate will this network be on new data?
Data
Activation
Commit your prediction above to see the result
Make your prediction to see the result.
Now switch Data to Two spirals, and try wider, then deeper. Raise Weight decay when the boundary gets jagged, and watch Training accuracy against New-data accuracy.
Worth it on a table?
PredictPredict first
Pima, seven numeric features, 426 training rows. A logistic model has AUC 0.857. Where do you expect a small network with a strong penalty, and a deeper one trained with Adam, to land?
Reveal
About the same, or a little behind. The small network gets 0.856 and the deeper one 0.837. A one-layer sigmoid net with balanced weights on four features gets 0.860. Without a lot of rows, extra layers have little to learn and plenty to memorize.
Keeping it honest
ReadNetworks can memorize anything given enough units, so use their brakes:
- L2 penalty: keeps weights small.
- Early stopping: stops when a held-back share stops improving.
- Small size first: grow only if a learning curve says the model is too rigid.
Inputs must be scaled, as a badly scaled column stretches the loss surface. Ozone shows the risk: with so few rows, a deeper net with early stopping has RMSE 24.6, a small one 19.8, and a forest 19.0.
Two learners, two guarantees
ReadNeural network (MLP) has one hidden layer and quasi-Newton training: scikit-learn in Python and nnet in R. They start from the same weights, but their optimizers differ, so agreement is on quality, not on digits.
Deep neural network (torch MLP) has several layers, trained with Adam on torch in both. Same weights, same batches, same stopping rows: the trained networks agree to about seven significant digits.
On penguins, log loss is 0.0748 and 0.0282.
When deep learning earns it
Reflect| Data | Reasonable first choice |
|---|---|
| Tables | Boosting or linear; networks if rows are many |
| Text, images, audio | Pretrained embeddings, then a simple model |
| Long sequences | A forecasting model, or a recurrent net with plenty of data |
Beyond MLPs, the Experimental learners include a CNN for small images stored as pixel columns and the FT-Transformer for tables. For text, Text to embed turns free text into features with a local model, which covers many practical cases. Which row is your data in, and how many rows would a deep model need to beat your current best?
Check your understanding
CheckpointCheck yourself
What would a multi-layer network with no non-linear activation amount to?
Show the answer
Answer: a
A composition of linear maps is linear. The activation is what buys curves.
Check yourself
Why do the network cards say standardizes inputs?
Show the answer
Answer: b
The same stretched bowl from the gradient descent lesson. The app applies the scaling inside each fold.
Check yourself
Which network should you pick if Python and R must agree closely, digit for digit?
Show the answer
Answer: a
Both engines run torch from the same weights and batches. The MLP uses two different optimizers.
Train both
In the appIn the Learners step, select Neural network (MLP) and Deep neural network (torch MLP) next to a linear model. Set Hidden units or Hidden layers (units), then L2 penalty. Check Diagnostics for a learning curve before growing the network.
import pandas as pd
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 StandardScaler
df = pd.read_csv("pima.csv")
X, y = df.drop(columns="diabetic"), df["diabetic"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
for size, alpha in [((4,), 1.0), ((16, 8), 0.01)]:
m = make_pipeline(StandardScaler(), MLPClassifier(size, alpha=alpha, max_iter=800, solver="lbfgs", random_state=1))
print(size, cross_val_score(m, X, y, cv=cv, scoring="roc_auc").mean().round(3))library(nnet)
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
num <- setdiff(names(df), "type")
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
auc <- sapply(1:5, function(k) {
tr <- df[fold != k, ]; te <- df[fold == k, ]
m <- colMeans(tr[num]); s <- apply(tr[num], 2, sd)
tr[num] <- scale(tr[num], m, s); te[num] <- scale(te[num], m, s)
fit <- nnet(type ~ ., tr, size = 4, decay = 1, maxit = 800, trace = FALSE)
as.numeric(pROC::auc(te$type, as.vector(predict(fit, te)), quiet = TRUE))
})
round(mean(auc), 3)Recap
Recap- Hidden units with non-linear activations build curved boundaries from lines.
- Use small networks first, with penalties, early stopping and scaled inputs.
- On tables with few rows, networks rarely beat linear models or boosting. Embeddings cover much of what deep learning is used for here.
Concepts in this lesson