Foundations

How to Debug a Model That Will Not Learn Anything

A systematic routine for finding why training loss will not fall, from data checks and baseline losses to gradients and silent shape bugs.

Key takeaways

  • Compare the loss with what a constant prediction would score, so you know exactly what "not learning" means.
  • Look at the actual batch the model receives, after all preprocessing, next to its labels.
  • A model with enough capacity should be able to drive the loss on a few examples close to zero.
  • Check that gradients exist and weights change, then examine the learning rate.
  • Fix random seeds and change one thing at a time until the cause is found.

When a model does no better than guessing, assume a bug in the data or the training code before you blame the architecture. Work from the inputs forward: confirm that inputs and labels line up, compute what a no-skill model would score, then ask your model to memorize a tiny sample. Each result narrows the search.

The frustrating part is that most of these bugs raise no error. The code runs, the loss prints and nothing improves.

A debugging order that saves time

Narrowing down a model that will not learn
1 Baseline What loss does guessing give? 2 Inspect batch Inputs and labels as the model sees them. 3 Tiny overfit Can it memorize a few examples? 4 Gradients Present, finite and changing weights? 5 Settings Learning rate, scaling, regularization. 6 Scale up Restore pieces one at a time. Baseline What loss does guessing give? 1 Inspect batch Inputs and labels as the model sees them. 2 Tiny overfit Can it memorize a few examples? 3 Gradients Present, finite and changing weights? 4 Settings Learning rate, scaling, regularization. 5 Scale up Restore pieces one at a time. 6

Before starting, make runs comparable. Fix the random seed, turn off augmentation, dropout and weight penalties, and use a small, fixed subset of data.

Make the problem smaller and known

When a large system fails, shrink it until it works, then grow it back. Replace your architecture with the simplest model that could possibly learn the task, such as a linear layer. Use a few hundred examples. Remove learning rate schedules, mixed precision, distributed training and custom losses.

Better still, swap in a problem whose answer you know. Generate inputs at random and build targets from a simple rule, for example whether the first feature is positive. A healthy training loop learns that within moments. If it fails, the fault is in the loop. If it succeeds, put your real data loader back while keeping the simple model, and test again.

Each swap splits the suspects in half. Keep notes on which version worked and which did not. Under time pressure it is tempting to change three things at once; then a success leaves you unsure which change mattered, and a failure tells you almost nothing.

Version control helps here. If the model used to learn, find the last working commit and compare. Also compare library versions and the data snapshot, since either can change behavior without a line of your code moving.

Know the no-skill loss

For classification with K balanced classes, a model that assigns equal probability to every class has cross-entropy ln K, using the natural log. That is about 0.693 for two classes, 2.303 for ten and 6.908 for a thousand.

With imbalanced classes, predicting the class frequencies does better than uniform. For a positive rate p, the loss is −(p ln p + (1 − p) ln(1 − p)). At p = 0.1 this is about 0.325. A binary model stuck at 0.325 on such data has learned the base rate and nothing else.

For regression with squared error, predicting the target mean gives the target variance. Compute these numbers and print them next to your loss.

A neural classifier freshly initialized should usually start near the uniform value. A much larger starting loss suggests badly scaled initial outputs or a mismatch between labels and the loss.

Look at what goes in

Print or plot one batch immediately before it enters the model.

  • Do images look like images, with the expected value range?
  • Does decoded text read correctly, with sensible truncation?
  • Do labels match the inputs beside them? Shuffling one array and not the other is a classic error.
  • Are class indices in the expected range, starting where the library expects?
  • Are there NaNs, infinities or columns that are entirely constant?
  • Do features differ in scale by many powers of ten?

Check array shapes and data types as well. Integer division, a flipped axis or labels stored as floating point where indices are expected can all cause trouble.

A silent shape bug

Array libraries broadcast, stretching shapes to make operations fit. That is convenient and dangerous. Here a prediction of shape (200, 1) is subtracted from targets of shape (200,).

import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))          # rows are examples
y = X @ np.array([2.0, -1.0, 0.5])     # shape (200,)

def train(fix, steps=500, lr=0.1):
    w = np.zeros((3, 1))
    for _ in range(steps):
        pred = X @ w                   # shape (200, 1)
        if fix:
            pred = pred[:, 0]          # shape (200,)
            err = pred - y             # shape (200,)
            per_row = err[:, None]
        else:
            err = pred - y             # shape (200, 200)!
            per_row = err.mean(axis=1, keepdims=True)
        w -= lr * X.T @ per_row / len(y)
    return w.ravel().round(2), err.shape

print(train(fix=False))
print(train(fix=True))

The fixed version recovers weights of 2, −1 and 0.5. The broken one compares every prediction with every target, so each row is pushed toward the average target, and the weights stay near zero. Nothing crashes. An assertion such as assert pred.shape == y.shape would have caught it. See shapes and broadcasting.

Overfit a tiny sample

Take perhaps 10 to 50 examples with correct labels and train on them alone, with regularization off. A neural network of reasonable size should reach nearly zero loss. If it cannot, the problem lies in the model, loss, gradients or optimizer, not in the amount of data.

If it can memorize but fails on the full set, the machinery works. Look then at data quality, capacity, learning rate and whether the labels are predictable from the inputs at all. The single-batch check has the details.

For a rigid model such as linear regression, memorizing is not expected. Instead, generate synthetic targets from known weights, as above, and confirm you recover them.

Check gradients and updates

Print the size of the gradient for each layer, and compare weights before and after a step.

Observation Likely cause
Gradient missing or exactly zero Layer disconnected, frozen or a non-differentiable step
Tiny in early layers Vanishing gradients
Huge or NaN Learning rate or inputs too large, log of zero, division by zero
Gradients fine, weights unchanged Parameters not given to the optimizer, or no step taken
Many units always output zero Dead rectified linear units

If you wrote gradients by hand, compare them with a finite difference: nudge one weight by a small amount up and down, and divide the change in loss by twice the nudge. In frameworks such as PyTorch, gradients accumulate across backward passes unless cleared, so confirm your loop resets them. More tools are in gradient and activation statistics.

Loss and output mismatches

Match the final layer to the loss. Some loss functions expect raw scores, called logits, and apply softmax or sigmoid internally; feeding them probabilities applies the squashing twice and weakens learning. Others expect probabilities. Read the documentation for the exact function you call.

Also check the sign and the target format. You should be minimizing a loss, not a score where higher is better. A multilabel problem needs an independent output per label, not a single softmax. A regression output should not pass through an activation that cannot produce the target range.

The learning rate and scaling

If the checks pass, try learning rates spanning several powers of ten, such as 1, 0.1, 0.01 and so on downward. Divergence points to a rate that is too large, and a nearly flat line to one that is too small. Learning rates explains the behavior.

Standardize numeric inputs using training statistics. Initialize weights with the library's recommended scheme; setting all weights in a hidden layer to the same value leaves its units identical forever. And confirm that the model is in training mode while training and evaluation mode while evaluating, since some layers behave differently.

Classical models fail to learn too

Not every stuck model is a neural network. A tree ensemble or linear model that matches the baseline has its own usual suspects.

  • A very strong penalty has pushed every coefficient to zero.
  • A tree's minimum leaf size is larger than the number of positive cases can support.
  • With rare positives, predicted probabilities all fall below 0.5, so every hard label is negative even though the ranking is informative. Check the scores before the labels.
  • Features were scaled or encoded differently at training and scoring time.
  • A join dropped or reordered rows, so features belong to other examples.
  • An identifier or constant column crowds out the useful inputs.

The third item is worth a pause. A model can look completely dead under accuracy or recall at the default threshold while ranking cases well. Look at the distribution of scores and at a threshold-free measure such as area under the ROC curve. If that is clearly above 0.5, the model has learned something, and your task is choosing a threshold. If it is far below 0.5, look for flipped labels or the wrong probability column.

When the code is right

Sometimes there is nothing to learn. If a simple baseline, a flexible model and a careful human all fail, the inputs may not predict the target, or the labels may be close to random. Check how labels were produced and whether two labelers agree.

A quick control: shuffle the labels and train again. Performance should fall to the no-skill level on held-out data. If your real run looks identical to the shuffled one, your pipeline is extracting no signal. If the shuffled run still scores well on validation data, you have a leak. Once the bug is found, add a test for it, then restore regularization and augmentation one at a time.

Written for 4MachineLearning with AI writing tools and not reviewed line by line by a person. Check anything you rely on against a textbook or primary source. Report an error.

Keep reading

All 42 articles in Foundations →

Latest news on this topic