Neural-net foundations14 / 15

Lesson 14 · Practical engineering

Choosing an architecture

The problem

The pizza company has three new projects:

  1. Late deliveries. Predict which orders will be late from the order table: 20 columns (prices, distances, times, categories) and 5,000 past orders.
  2. Burnt pizzas. Spot burnt pizzas in photos from the oven camera. Someone has labelled 800 photos.
  3. Complaints. Sort customer messages into complaint types. There are 2,000 labelled messages.

Each project could use a neural network. For some of them, that would be a mistake. This lesson is a practical guide to the choice: when a network is the right tool, which one, and what to try instead.

Start with a baseline

Whatever you pick, first build a baseline: the simplest sensible model, such as logistic regression on the raw columns. It takes minutes. It tells you what "good" means for this problem, and it catches bugs. If a fancy network can't beat it, something is wrong with the network, or the data has little more to give.

Compare every model on the same held-out data (see train, validation and test sets). With small data, use cross-validation, so one lucky split can't decide for you.

When to use what

The primitive map matched each shape of data to a building block. In practice, two more questions matter as much: how many labelled examples you have, and whether someone has already trained a model on similar data. Answer the three questions below.

1. What is one example?
2. How many labelled examples?
3. Is there a pretrained model for this kind of data?

Try first

Gradient-boosted trees

Tables have no grid or order for a network to exploit, and trees handle mixed columns well.

Baseline to beat

Logistic or linear regression

Later

An MLP rarely beats the trees here. Spend the time on better columns.

Rules of thumb, not laws. Whatever you pick, compare it with the baseline on the same validation data.

A decision guide. Answer three questions about a project; it suggests what to try first, the baseline to beat, and what to try later. These are rules of thumb, explained in the rest of the lesson.

The same guide as a table, for the most common cases:

DataTry firstBaseline to beat
TableGradient-boosted treesLogistic or linear regression
ImagesA pretrained CNN, fine-tunedFrozen pretrained model plus logistic regression
TextA pretrained language modelBag of words plus logistic regression
Time seriesTrees on recent values"Tomorrow equals today"
GraphA GNNTrees on node features plus neighbour averages

Three rules of thumb sit behind this table. The next sections show where each one comes from.

  1. For tables, start with gradient-boosted trees.
  2. For images and text, start from a pretrained model.
  3. Train a network from scratch only with lots of data, or an input nobody has pretrained on.

Tables: trees first

A table has no grid and no order. Its columns are a mix of numbers, yes/no flags and categories, each with its own meaning. None of the network building blocks has an assumption that fits this well. An MLP can learn it, but it needs data to make up for the missing assumption.

How much data does each model need? Here are three models on the deliveries table from ML fundamentals: distance, traffic, rain, hour, number of items and driver, with "late" as the label. Each one trains on a random set of rows and is tested on 1,200 fresh deliveries.

Predict first

The MLP starts behind the trees. At about how many training rows does it catch up with them?

25501002004008001600320075%80%85%90%training rowstest accuracybest possible 90.6%
Logistic regressionBoosted treesMLP

At 100 rows, logistic regression wins.

Logistic regression: 86.2% · Boosted trees: 84.5% · MLP: 84.8%

Each point averages 5 random training sets of that size, tested on the same 1,200 fresh deliveries.

Test accuracy against the number of training rows, for logistic regression, gradient-boosted trees (XGBoost, 200 small trees) and an MLP with two hidden layers of 64 units. Precomputed in Python; each point averages 5 random training sets.

Things to notice:

  • Up to 100 rows, logistic regression wins (86.2% at 100 rows, against 84.5% for the trees and 84.8% for the MLP). A straight line has few weights, so it learns fast from little data.
  • At 200 rows, the trees draw level, and from 400 rows they lead. By 800 rows they're at 89.2%. Logistic regression stops at about 87.8%, even with 3,200 rows.
  • The MLP catches up with the trees only at 1,600 rows or more. At 3,200 rows, both are at about 90%, close to the best possible 90.6%.

Why does logistic regression stop at 87.8%?

Deliveries sent out between 18:00 and 19:59 take about 5 minutes longer. That's a bump in the middle of the evening. A straight line in the hour can't make a bump, so it can't follow it. Trees can split the hour at 18 and at 20. A logistic regression given a "rush hour: yes or no" column could follow it too: that's feature engineering.

Why can't any model reach 100%? The deliveries have random variation, a few minutes either way, so some orders near 30 minutes are late by chance. No model can predict that part.

DigressionCase study: trees against networks on 45 tablesA 2022 benchmark found trees still ahead on medium-sized tables, and gave three reasons. · 3 min

Grinsztajn, Oyallon and Varoquaux compared tree models and deep networks on a standard set of 45 tables. Their paper is "Why do tree-based models still outperform deep learning on tabular data?" (NeurIPS 2022, Datasets and Benchmarks track). The tables were medium-sized, about 10,000 rows. Every model got a large hyperparameter search, about 20,000 hours of computing in all.

Tree-based models (XGBoost and random forests) remained the best on these tables, even before counting their faster training. The authors then changed the data on purpose to find out why. They point to three differences in inductive bias:

  • Useless columns. Real tables often have columns that don't matter, like the driver id in the deliveries data. Networks were hurt more by them than trees.
  • Each column has its own meaning. A tree splits on one column at a time. An MLP mixes all the columns from its first layer. When the authors mixed up the columns on purpose, by rotating them, the MLP-style networks were unaffected and the trees fell behind them. So trees use the columns' own meanings, and those networks don't.
  • Jagged patterns. Networks tend to learn smooth functions. Tables often have sudden jumps, like the rush-hour bump, which trees capture with a couple of splits.

The question isn't settled. In 2025, Hollmann and colleagues described TabPFN in Nature: a transformer pretrained on more than 100 million made-up tables. They report that it beats the previous methods on tables of up to 10,000 rows. Pretrained models may change this advice, but trees remain the standard first try.

Images and text: start from a pretrained model

A network trained on a million photos has already learned to detect edges, textures and shapes. Those are useful for burnt pizzas too. So instead of starting from random weights, start from that network:

  1. Take a pretrained model: one trained on a big dataset, often by someone else, with its weights published.
  2. Replace its last layer with a new one that outputs your classes, such as "burnt" and "fine".
  3. Train on your data. With few labels, freeze the pretrained layers (stop their weights from changing) and train only the new layer. With more labels, also adjust the pretrained layers a little, with a small learning rate. That's called fine-tuning.

Reusing what a model learned on one task for another task is called transfer learning. The pretrained layers already turn pixels into useful features. Your 800 labels only have to teach the last step. That's closer to fitting logistic regression on good features than to training a network from scratch.

DigressionCase study: skin cancer from photos, and the pen marksA pretrained network matched dermatologists. Another learned that ink means cancer. · 3 min

In 2017, Esteva and colleagues at Stanford published "Dermatologist-level classification of skin cancer with deep neural networks" in Nature. They did not design a new network. They took Google's Inception v3, pretrained on about 1.28 million everyday photos in 1,000 categories (the ImageNet dataset). Then they fine-tuned it on 129,450 photos of skin covering 2,032 diseases.

They tested it against 21 board-certified dermatologists on two questions. The first was common skin cancers against a harmless lookalike; the second was melanoma, the deadliest skin cancer, against harmless moles. The network did as well as the dermatologists on both.

What went wrong elsewhere.

In 2019, Winkler and colleagues tested a commercial skin-cancer network in JAMA Dermatology. It was also built on a pretrained network (Inception-v4) and trained on more than 120,000 images.

Doctors often mark a mole with purple ink before removing it. On 130 moles photographed without marks, the network correctly cleared 84.1% of the harmless ones. Photographed again with ink marks, it cleared only 45.8%. The ink pushed its cancer scores up, most likely because ink marks went with worrying moles in the kind of photos it learned from.

The lesson: a model learns whatever separates the labels in the training data, including things that only travel with the label. Check what a model looks at, and test it on data like the data it will see in use.

Text works the same way. In 2018, Howard and Ruder pretrained a language model on general text, then fine-tuned it to sort texts. Their paper is "Universal Language Model Fine-tuning for Text Classification" (ULMFiT).

They report that with only 100 labelled examples, it matched training from scratch on 100 times more data. Today's pretrained language models go much further. The Transformers and Large language models courses cover them.

Train from scratch only when:

  • your input is unusual and no pretrained model fits it, like readings from a special sensor, or
  • you have a huge labelled dataset, and the compute to use it.

Trade-offs

Accuracy is one column of several. The table below compares the usual choices. These are rules of thumb, not measurements, and every project has exceptions.

Labels neededTraining costServing costExplaining it
Linear modelFewSecondsTinyEasy: one weight per column
Boosted treesHundreds+Seconds to minutesSmallMedium: which columns it splits on
Small network from scratchThousands+Minutes to hoursSmallHard
Fine-tuned pretrained modelHundreds+Minutes to hours on a GPULargeHard
Large model through an APINone to fewNoneA fee per callHard

Things the table leaves out:

  • Speed of answers. A fraud check has to answer in milliseconds; a weekly report can take an hour.
  • Maintenance. A big model needs GPUs, monitoring and retraining. A linear model is a few numbers in a file.
  • Explaining decisions. If someone needs to know why an order was flagged, a linear model or a small tree is far easier to explain.

Sizing a network

When a network is the right choice, how big should it be? A safe order of work:

  1. Start small. For the rush-hour data, 2-16-16-2 is enough.
  2. Grow it until it can fit the training data. If the training loss stays high, the network is too small: add width or depth.
  3. Then fight overfitting. If the training loss is low but the validation loss is much higher, add weight decay or dropout, stop early, or get more data.

Keep an eye on size as you go. Count the parameters, and work out the memory.

Worked example

Parameters and memory

  1. A 2-16-16-2 MLP. Each layer has (inputs × outputs) weights plus one bias per output: (2×16+16)+(16×16+16)+(16×2+2)=48+272+34=354(2 \times 16 + 16) + (16 \times 16 + 16) + (16 \times 2 + 2) = 48 + 272 + 34 = 354 parameters.

DigressionA made-up case: the 3-million-parameter MLPA cautionary tale. The company and numbers are invented; the mistakes are common. · 2 min

This story is made up to illustrate common mistakes.

A team had 2,000 rows of customer data with 15 columns and wanted to predict who would cancel. They built an MLP with four hidden layers of 1,024 units: about 3.2 million parameters, or 1,600 per row of data.

Training accuracy reached 100%. On held-out customers, it was 71%. A logistic regression that took two minutes to fit scored 84%, and boosted trees scored 86%.

What went wrong:

  • No baseline first. They found out about the 84% only after a week of tuning.
  • Far too big for the data. With 1,600 parameters per row, the MLP could memorise every customer. Its capacity was far beyond what 2,000 rows can pin down.
  • The wrong primitive. The data was a small table, the case where trees are the usual first choice.

Pitfalls checklist

The mistakes that cost the most, roughly in order:

  • No baseline. You can't tell whether 84% is good until you know what logistic regression gets.
  • A network on a small table. Try boosted trees first.
  • Training from scratch when a pretrained model exists. You throw away millions of examples' worth of learning.
  • Comparing models on different data, or choosing a model by its test score. Tune on validation data, and look at the test set once, at the end.
  • Trusting one run. Results vary with the random seed and the split. Use several seeds or cross-validation before claiming one model is better.
  • Shortcuts in the data. Ink marks, rulers, or a column that is filled in only after the outcome (data leakage). Check what the model relies on.
  • Unscaled inputs to a network. Trees don't care about column scales; networks do (feature scaling).
  • Ignoring serving cost. A model that is 0.5% more accurate but 100 times slower may be the wrong choice.

In PyTorch

The three models from the data-size figure. Logistic regression and the trees come from scikit-learn and XGBoost. The MLP uses the Lesson 4 template's make_mlp, fit and evaluate unchanged.

Two things are new. A fifth of the training rows is held out so fit can pick its best epoch. The columns are standardised with the training rows' mean and spread.

Three models for one table
def logistic_regression(x: np.ndarray, y: np.ndarray):
    """The linear baseline: standardise the columns, then fit a straight boundary."""
    return make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(x, y)


def boosted_trees(x: np.ndarray, y: np.ndarray, seed: int = 0):
    """Gradient-boosted trees with common settings: 200 small trees, each correcting the last."""
    model = XGBClassifier(n_estimators=200, max_depth=3, learning_rate=0.1, random_state=seed)
    return model.fit(x, y)


def mlp(x: np.ndarray, y: np.ndarray, seed: int = 0, epochs: int = 100) -> nn.Module:
    """A 6-64-64-2 MLP, trained with the Lesson 4 template. A fifth of the rows is held out so fit can pick its best epoch."""
    seed_everything(seed)
    mean, std = x.mean(axis=0), x.std(axis=0) + 1e-8  # networks need standardised inputs; trees don't
    n_val = max(len(x) // 5, 2)
    order = np.random.default_rng(seed).permutation(len(x))
    val, train = order[:n_val], order[n_val:]

    def loader(idx: np.ndarray, shuffle: bool) -> DataLoader:
        xs = torch.tensor((x[idx] - mean) / std, dtype=torch.float32)
        ds = TensorDataset(xs, torch.tensor(y[idx], dtype=torch.long))
        return DataLoader(ds, batch_size=32, shuffle=shuffle, generator=torch.Generator().manual_seed(seed))

    model = make_mlp([len(COLUMNS), 64, 64, 2])
    fit(model, loader(train, True), loader(val, False), epochs=epochs, lr=0.01, device=torch.device("cpu"))
    model.scaling = (mean, std)  # remember the training rows' scaling for prediction
    return model


def mlp_accuracy(model: nn.Module, x: np.ndarray, y: np.ndarray) -> float:
    mean, std = model.scaling
    ds = TensorDataset(torch.tensor((x - mean) / std, dtype=torch.float32), torch.tensor(y, dtype=torch.long))
    _, acc = evaluate(model, DataLoader(ds, batch_size=512), nn.CrossEntropyLoss(), torch.device("cpu"))
    return acc

The experiment draws training sets of each size, fits all three, and scores them on the same fresh rows:

Accuracy against training-set size
def data_size_curve(sizes: list[int], repeats: int = 5, epochs: int = 100) -> dict[str, list[float]]:
    """Test accuracy of each model, averaged over `repeats` random training sets of each size."""
    pool_x, pool_y = delivery_table(range(100, 111))  # 3,300 rows to draw training sets from
    test_x, test_y = delivery_table(range(200, 204))  # 1,200 fresh rows, never trained on
    scores: dict[str, list[float]] = {"logistic": [], "trees": [], "mlp": []}
    for n in sizes:
        runs = {k: [] for k in scores}
        for r in range(repeats):
            idx = np.random.default_rng(1000 * n + r).choice(len(pool_x), size=n, replace=False)
            x, y = pool_x[idx], pool_y[idx]
            runs["logistic"].append(logistic_regression(x, y).score(test_x, test_y))
            runs["trees"].append(boosted_trees(x, y, seed=r).score(test_x, test_y))
            runs["mlp"].append(mlp_accuracy(mlp(x, y, seed=r, epochs=epochs), test_x, test_y))
        for k in scores:
            scores[k].append(float(np.mean(runs[k])))
    return scores

Counting parameters uses model.parameters(), and numel() gives each tensor's number of entries:

Parameters and memory
def count_parameters(model: nn.Module) -> int:
    return sum(p.numel() for p in model.parameters())


def training_memory_mb(n_params: int, bytes_per_number: int = 4) -> dict[str, float]:
    """Rough memory for the numbers AdamW keeps per weight (activations not included)."""
    mb = n_params * bytes_per_number / 1e6
    return {"weights": mb, "gradients": mb, "adam_state": 2 * mb, "total": 4 * mb}

To fine-tune, freeze the pretrained part with requires_grad_(False), so autograd stops computing its gradients. Then give the optimiser only the parameters that still train:

Freeze a backbone, train a new head
def prepare_fine_tuning(backbone: nn.Module, n_features: int, n_classes: int) -> tuple[nn.Module, torch.optim.Optimizer]:
    """Freeze a pretrained backbone and put a new, trainable head on top."""
    for p in backbone.parameters():
        p.requires_grad_(False)  # keep what it learned on the big dataset
    model = nn.Sequential(backbone, nn.Linear(n_features, n_classes))  # the new head starts random
    trainable = [p for p in model.parameters() if p.requires_grad]  # only the head's weight and bias
    return model, torch.optim.AdamW(trainable, lr=1e-3)

The pretrained part (often called the backbone) usually comes from a library, such as torchvision.models for images or Hugging Face's transformers for text. Neither is part of this book's environment. So the test file freezes a small stand-in, and checks that one training step moves only the new final layer.

Running the file takes about two minutes. It trains 120 models and prints the table behind the figure.

Common misconceptions

"Neural networks are the most accurate model for every problem." On small and medium tables, gradient-boosted trees usually match or beat them. They also need far less tuning.

"A bigger network is always better." Only with enough data. A network much bigger than its data can pin down memorises the training set.

"Fine-tuning needs as much data as training from scratch." It needs far less. The pretrained layers have already learned general features, so your labels only teach the last step.

"If the test accuracy is high, the model has learned the right thing." It may have learned a shortcut, like ink marks on skin photos. Check what it relies on, and test on data like the data it will see in use.

"Pick the model with the best accuracy." Also weigh how much data it needs, and its training and serving cost. Ask, too, whether you have to explain its decisions.

Recap

  • Always build a simple baseline first, and compare every model on the same held-out data.
  • For tables, start with gradient-boosted trees. Networks catch up only with lots of rows; logistic regression is often best with only a few.
  • For images and text, start from a pretrained model. Freeze it and train a new last layer, or fine-tune it all if you have more labels.
  • Train from scratch only with lots of data, or an input nobody has pretrained on.
  • Weigh accuracy against labels needed, training and serving cost, and how easy the model is to explain. These are rules of thumb.
  • Size a network by starting small, growing it until it fits the training data, then regularising. Count parameters: 4 bytes each to store, about 16 to train with AdamW.
  • PyTorch names used: model.parameters(), Tensor.numel, requires_grad_, nn.Sequential, nn.Linear, torch.optim.AdamW; plus scikit-learn's LogisticRegression and XGBoost's XGBClassifier.