Choosing an Architecture
You have now built most of the standard architectures in NumPy and in PyTorch. Faced with a new problem, the question is which one to start with. No architecture is best in general. Each one builds in assumptions about the data, its inductive bias, and works best when those assumptions hold. The choice also depends on how much data and compute you have and on whether a pretrained model exists. This lesson turns the course into a decision guide, tests two of its claims with runnable code, and links back to every architecture lesson.
Inductive biases
| Architecture | What it assumes | Built-in property |
|---|---|---|
| MLP | nothing about the order of the inputs | none: any fixed permutation of the inputs gives an equivalent problem |
| CNN | nearby values belong together, and a pattern means the same thing anywhere | locality and weight sharing, so translation equivariance |
| RNN, LSTM, GRU | a sequence is processed in order, with state carried forward | a recurrence with the same weights at every step |
| transformer | relations between any two positions may matter, and position comes from an encoding | permutation equivariance plus positional encodings, content-based mixing |
| GNN | entities and their links matter, not any ordering of the nodes | permutation equivariance over nodes, messages along edges |
| gradient-boosted trees | features are separately meaningful, with thresholds and interactions | axis-aligned splits, insensitivity to feature scaling |
A strong bias that matches the data saves data and parameters. One that does not match costs accuracy. The weaker the bias, as in transformers and MLPs, the more data the model needs before it overtakes models with stronger priors. This is why Vision Transformers need large-scale pretraining before they beat CNNs.
Testing the claims
The first example compares three model families on tabular data (breast cancer, 30 measured features, 143 validation cases) and on Digits images (the course split, 360 validation images). The third row applies one fixed random shuffle to the 64 pixel positions of every image. A model with no spatial bias cannot tell the difference.
import numpy as np
from sklearn.datasets import load_breast_cancer, load_digits
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.neural_network import MLPClassifier
def splits():
Xc, yc = load_breast_cancer(return_X_y=True) # tabular: 30 measured features
a = train_test_split(Xc, yc, test_size=0.25, random_state=0, stratify=yc)
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tmp, X_te, y_tmp, 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_tmp, y_tmp, test_size=0.25, random_state=0, stratify=y_tmp)
perm = np.random.default_rng(0).permutation(64) # the same pixel shuffle for every image
return {"breast cancer (tabular)": (a[0], a[2], a[1], a[3]),
"digits (8x8 images)": (X_tr, y_tr, X_va, y_va),
"digits, pixels shuffled": (X_tr[:, perm], y_tr, X_va[:, perm], y_va)}
models = {
"logistic": lambda: make_pipeline(StandardScaler(), LogisticRegression(max_iter=2000)),
"gradient boosting": lambda: HistGradientBoostingClassifier(max_iter=50, random_state=0),
"MLP 64-64": lambda: make_pipeline(StandardScaler(), MLPClassifier((64, 64), max_iter=500, random_state=0)),
}
print(f"{'validation accuracy':26s}" + "".join(f"{m:>19s}" for m in models))
for name, (Xa, ya, Xb, yb) in splits().items():
row = []
for m in models.values():
row.append(m().fit(Xa, ya).score(Xb, yb))
print(f"{name:26s}" + "".join(f"{s:19.3f}" for s in row))validation accuracy logistic gradient boosting MLP 64-64
breast cancer (tabular) 0.958 0.930 0.951
digits (8x8 images) 0.972 0.964 0.972
digits, pixels shuffled 0.972 0.961 0.961
Two observations. On this small, clean tabular set, all three are within 0.03 of each other. With 143 validation cases, one case is 0.007, so these gaps are 1 to 4 cases and do not rank the models. On large, messy tabular data with heterogeneous features, gradient-boosted trees are usually the strongest baseline (Grinsztajn et al., 2022). Treat that as a reason to start there, not as a rule. On the digits, shuffling the pixels leaves logistic regression exactly unchanged (0.972) and moves the other two by about 0.01. That change comes from feature-order-dependent randomness in initialisation and tie-breaking, not from structure they lost: none of these models knew where pixels were in the first place. A CNN would be badly hurt by the shuffle, because its whole advantage is that neighbouring pixels are related. That is the inductive bias doing the work, and you can test it the same way with the models from A CNN in NumPy, then in PyTorch.
The second example counts parameters for the same three-way choice at three image sizes: an MLP with two hidden layers of 128, a CNN with two convolutions (16 and 32 channels), global average pooling and a linear head, and a 2-layer ViT with width 64. It uses the counting rules of Parameter and FLOP Counting.
def linear(n_in, n_out):
return n_in * n_out + n_out
def conv(c_in, c_out, k):
return c_in * c_out * k * k + c_out # independent of the image size
def mlp(h, w, c, classes=10):
return linear(h * w * c, 128) + linear(128, 128) + linear(128, classes)
def cnn(h, w, c, classes=10):
# conv 3x3 to 16 and to 32 channels, then global average pooling and a linear head
return conv(c, 16, 3) + conv(16, 32, 3) + linear(32, classes)
def vit(h, w, c, patch, d=64, layers=2, classes=10):
tokens = (h // patch) * (w // patch)
embed = linear(patch * patch * c, d) + (tokens + 1) * d + d # patch projection, positions, class token
block = 4 * linear(d, d) + linear(d, 4 * d) + linear(4 * d, d) + 2 * 2 * d # attention, MLP, 2 LayerNorms
return embed + layers * block + 2 * d + linear(d, classes), tokens
for h, w, c, patch in [(8, 8, 1, 2), (32, 32, 3, 4), (224, 224, 3, 16)]:
p_vit, tokens = vit(h, w, c, patch)
size = f"{h}x{w}x{c}"
print(f"input {size:>9s}: MLP {mlp(h, w, c):>10,} CNN {cnn(h, w, c):>6,} ViT {p_vit:>7,} ({tokens} tokens)")input 8x8x1: MLP 26,122 CNN 5,130 ViT 102,218 (16 tokens)
input 32x32x3: MLP 411,146 CNN 5,418 ViT 108,106 (64 tokens)
input 224x224x3: MLP 19,285,514 CNN 5,418 ViT 162,634 (196 tokens)
The MLP's first layer grows with the number of pixels, from 26,122 parameters at to 19,285,514 at . The CNN's parameters do not depend on the image size at all (5,418 for any 3-channel input), because a convolution's weights are shared across positions. The ViT changes only through its patch projection and position table (102,218 to 162,634). Its cost is in compute instead: attention over tokens costs , and 196 tokens is 12 times as many as 16. Parameters, compute and data needs are three separate budgets, and the architecture decides how they scale.
A decision guide
| Data | Start with | Then try | Lessons |
|---|---|---|---|
| tabular | gradient-boosted trees | an MLP with embeddings for categorical columns, or an ensemble of both | MLPs on Tabular Data, Embedding Layers |
| images | a pretrained CNN (ResNet family), fine-tuned | a pretrained ViT when data and compute are plentiful | CNN Architectures, ViT, Computer Vision |
| time series, signals | gradient boosting on lag features, or a 1-D CNN | LSTM or GRU, or a transformer for long contexts | RNN, LSTM and GRU |
| text | a pretrained transformer | fine-tuning with LoRA, or prompting a large model | Transformer Block, NLP and Transformers |
| graphs, molecules | a GCN | attention-based or edge-aware message passing | Message Passing, GCN in PyTorch |
| generate data | diffusion (images, audio), autoregressive transformer (text, code) | VAE for compact latents, GAN when one fast forward pass matters | the Generative Models lessons below |
Three questions refine the choice:
- Is there a pretrained model for this kind of data? If so, fine-tuning it usually beats training anything from scratch, often by a wide margin when labelled data is scarce. See Transfer Learning and Choosing a Training Strategy.
- How much labelled data is there? With hundreds to a few thousand examples, prefer strong inductive biases (trees, small CNNs) or pretrained features. Weakly biased models need far more data or pretraining.
- What are the limits at inference? Latency, memory and hardware can rule out large transformers or many-step diffusion samplers, whatever their accuracy. Measure them early, not after the model is chosen.
Whatever you choose, start with a simple baseline (logistic regression or gradient boosting), use the same validation split for every candidate, and keep the test set for the end (Holdout and k-Fold Validation).
The architectures of this course
- Building blocks: Neurons and Layers, Activation Functions, Output Layers and Losses, Backpropagation, Layer by Layer, A Small Autograd Engine, Training an MLP with Your Autograd.
- Making deep networks train: Weight Initialisation, Vanishing and Exploding Gradients, Batch Normalisation, Layer Normalisation and RMSNorm, Dropout, Residual Connections.
- MLPs and embeddings: MLPs on Tabular Data, Embedding Layers.
- Convolutional networks: Convolution Layers, Pooling, Stride and Receptive Fields, A CNN in NumPy, then in PyTorch, CNN Architectures: LeNet to ResNet.
- Recurrent networks: Recurrent Neural Networks, LSTM and GRU in Practice, Training Sequence Models.
- Attention and transformers: Attention from Scratch, Building a Transformer Block, Training a Tiny Character Transformer, Vision Transformers.
- Generative models: Autoencoders, Variational Autoencoders, GANs, Diffusion: The Noising Process, Diffusion: Training and Sampling.
- Graph networks: Message Passing, Node Classification with a GCN.
Pitfalls
- Choosing by fashion. A transformer on 500 rows of tabular data is rarely the right first model. Start from the data type and the amount of data.
- Comparing under different budgets. A tuned model against an untuned one, or 100 epochs against 10, says nothing about architectures. Give each candidate the same tuning effort and the same validation split.
- Reading small differences as rankings. On 143 validation cases, one case is 0.007. Use cross-validation or several seeds before you declare a winner.
- Ignoring the deployment budget. Parameters, compute per example and latency scale differently with input size, as the counts above show.
Practice
- Your data is 2,000 rows of customer records with 15 numeric and 5 categorical columns. Which model do you train first, and which second?
Answer
First, gradient-boosted trees (XGBoost, LightGBM or scikit-learn's histogram GBM), which handle mixed feature types and need little preprocessing. Second, an MLP with embeddings for the categorical columns and standardised numeric columns, compared on the same validation split. Averaging the two is often better than either alone.
- Using the parameter counts above, explain why an MLP on raw RGB images is a poor choice even before training.
Answer
Its first layer alone has about 19.3 million parameters for 128 hidden units, and it has no notion that neighbouring pixels are related or that a pattern can appear anywhere. It would need a huge amount of data to learn what a CNN gets from weight sharing with 5,418 parameters in its convolutional part.
- Why did shuffling the pixels leave logistic regression at exactly 0.972?
Answer
Logistic regression gives each input its own weight and has a convex loss with a unique optimum (with L2 regularisation). Permuting the inputs permutes the optimal weights in the same way, so the predictions, and the accuracy, are identical.
Test yourself
What is an inductive bias?
- A bug that biases predictions
- The assumptions about the data that an architecture builds in, such as locality and weight sharing in a CNN
- The bias term of a linear layer
- A preference for small learning rates
Which model family should you usually try first on a medium-sized tabular data set?
- A vision transformer
- Gradient-boosted trees
- A GAN
- An RNN
How does the number of parameters of a convolutional layer change when the input image grows from to ?
- It grows with the number of pixels
- It does not change, because the kernel weights are shared across positions
- It grows with the square root of the number of pixels
- It halves
You have 800 labelled X-ray images. What is the most promising start?
- Train a ViT from scratch
- Fine-tune a pretrained CNN (or use its features) with augmentation
- Train an MLP on raw pixels
- Train a GAN first