Skip to main content
LearnMLAcademy
Advanced10 min read

Training and Debugging a Neural Network

Construct robust PyTorch training loops with validation and gradient tracking, with tensor walkthroughs, gradient calculations, and PyTorch practice.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Deep Learning · Beginner Lesson

Training a Neural Network: The Complete Loop From Data to Better Predictions

Creating a neural network only gives us a collection of layers with untrained weights. A training loop is the repeated procedure that shows the network examples, measures its mistakes, corrects its weights and checks whether those corrections also help on unseen data. This lesson follows one batch through every operation and explains what should happen at the end of an epoch.

What Does “Training” Actually Mean?

Imagine a factory camera that must label a product as acceptable or defective. At first, its weights are random, so its answers are poor. Training does not give the camera one long instruction. It performs thousands of small correction cycles:

examples → predictions → measured mistakes → gradients → corrected weights

The word loop matters because the same operations are repeated. One repetition for one batch is a training step. Repeating steps until the complete training set has been used once creates an epoch. Repeating epochs gives the weights many opportunities to improve.

The six operations repeated for every training batchLoad a batch, clear old gradients, perform the forward pass, calculate the loss, perform the backward pass, and update the weights. Then repeat with the next batch.1Load a batchimages + correct labels2Clear gradientsremove values from last batch3Forward passmodel makes predictions4Calculate lossmeasure this batch’s mistakes5Backward passcalculate every gradient6Update weightsoptimizer takes one steprepeat with the next batch until the epoch is complete
Figure 1: One training step is a six-part correction cycle performed on one batch.

Essential Terms Before We Build the Loop

Training example

One input together with its correct target, such as one product image and its defect label.

Batch

A small group of examples processed together before one weight update.

Training step / iteration

One complete batch cycle: predict, calculate loss, backpropagate and update.

Epoch

One pass through all examples in the training set.

Validation set

Separate examples used to measure the current model without changing its weights.

Metric

A human-readable measurement such as accuracy or MAE, reported alongside the training loss.

What Happens to One Batch?

Suppose a batch contains 16 product images and 16 correct labels. The six operations below form one meaningful unit. Each step exists because the next one depends on it.

1

Load inputs and targets

The data loader supplies image tensors and their correct labels. Inspect their shape, value range and labels before trusting the loop.

2

Clear gradients from the previous batch

PyTorch normally adds new gradients to existing ones. optimizer.zero_grad() removes the old values so this batch produces a fresh correction.

3

Run the forward pass

The batch travels through the current network. The model produces raw output scores called logits. No weights change yet.

4

Calculate the batch loss

The loss function compares the logits with the correct labels and returns one average penalty for this batch.

5

Run the backward pass

loss.backward() calculates a gradient for every trainable weight. A gradient tells how that weight influenced the loss.

6

Update the weights

optimizer.step() uses the gradients and learning rate to change the weights. This is the only step in this cycle that actually changes the model.

Why the order matters: loss cannot be calculated before a prediction exists; gradients cannot be calculated before a loss exists; and the optimizer cannot make an informed update before gradients exist.

How Batches Form an Epoch

Processing the entire dataset at once may not fit in memory. Instead, the data loader divides it into batches. For N examples and batch size B:

Formula

updates per epoch = ⌈N ÷ B⌉

The ceiling brackets ⌈ ⌉ mean round upward because a smaller final batch still needs to be processed.

ONE EPOCH = every training example is visited onceBatch 116 examplesupdate 1Batch 216 examplesupdate 2Batch 316 examplesupdate 3Batch 416 examplesupdate 4Batch 516 examplesupdate 5Batch 616 examplesupdate 6Batch 74 examplesupdate 7100 examples ÷ batch size 16 = 6 full batches + 1 smaller final batch = 7 updates
Figure 2: Batch size determines how often the model updates during one epoch.

Small batch

Frequent, noisier updates and lower memory use.

Large batch

Smoother gradient estimate but more memory and fewer updates per epoch.

One epoch

A unit for scheduling validation, checkpoints and learning-rate changes.

A Complete Weight Update With Small Numbers

To see what the loop accomplishes, use the one-weight model ŷ = wx. It receives input x = 2 and should produce target y = 4. Start with w = 0.5, learning rate η = 0.1 and loss L = ½(ŷ − y)².

Input x

2

Target y

4

Starting w

0.5

Learning rate η

0.1

1

Forward

ŷ = wx = 0.5 × 2 = 1

2

Loss

L = ½(1 − 4)² = 4.5

3

Backward

∂L/∂w = (ŷ − y)x = (1 − 4) × 2 = −6

4

Update

w_new = w − η(∂L/∂w) = 0.5 − 0.1(−6) = 1.1

5

Verify the next step

ŷ_new = 1.1 × 2 = 2.2; L_new = ½(2.2 − 4)² = 1.62

What changed?

One batch update moved w from 0.5 to 1.1 and reduced loss from 4.5 to 1.62. The next batch repeats the same six operations using the new weight. Training is many small improvements like this.

Training and Validation Have Different Jobs

Training performance answers, “Is the optimizer fitting the examples it is allowed to learn from?” Validation performance answers, “Do those learned patterns also work on separate examples?” If validation examples update the weights, they are no longer an honest test of generalization.

Training and validation are separate passesTraining data follows forward, loss, backward and update steps. Validation data follows forward, loss and metrics only, with no gradient or weight update.TRAINING PASS — learning is ONTraining batchForward + lossBackwardUpdate weightsweightschangedVALIDATION PASS — learning is OFFValidation batchForward + lossMetricsRecord resultNo backward pass · No optimizer step · No information leaks back into training
Figure 3: Training changes the model; validation only measures the current model.
QuestionTraining passValidation pass
Which data?Training batchesHeld-out validation batches
Model mode?model.train()model.eval()
Calculate gradients?YesNo
Update weights?YesNever
Random augmentation?Usually yesNo; use deterministic preprocessing
Main purposeLearn parametersMeasure and choose checkpoints/settings

model.eval() does not calculate accuracy and does not disable gradients by itself. It changes the behaviour of layers such as dropout and batch normalization. torch.no_grad() separately prevents gradient recording, saving memory and computation.

How to Read Training Curves

At the end of each epoch, record average training loss and validation loss. A single point cannot show a trend, but the shape across several epochs can reveal whether learning is useful, overfitting or stalled.

Healthy learning

0.20.50.81.1123456trainingvalidationepochloss
Both losses fall; validation remains a little higher.

Overfitting

0.20.50.81.1123456trainingvalidationepochloss
Training improves while validation gets worse after epoch 3.

Learning has stalled

0.20.50.81.1123456trainingvalidationepochloss
Both curves stay almost flat; investigate the pipeline.
PatternLikely meaningWhat to check next
Both losses fallThe model is learning patterns that transfer.Continue while validation improves; save the best checkpoint.
Training falls, validation risesThe model is increasingly memorizing training-specific details.Use early stopping, data augmentation, weight decay, dropout or more representative data.
Both remain flatThe learning signal may be ineffective or the pipeline may be broken.Check labels, gradients, learning rate, frozen parameters and loss/output compatibility.
Loss becomes NaN or explodesNumerical instability or excessively large updates.Inspect input scale, learning rate, loss math and gradient norms.

The Tiny-Data Test: Check the Loop Before Tuning the Model

Before a long training run, take perhaps 10–20 clean examples and deliberately ask the model to memorize them. This is not the final goal. It is a diagnostic test: a sufficiently capable network should be able to drive training loss very low on such a tiny set.

1. Create the test

Use a fixed tiny batch with verified inputs and labels. Temporarily reduce augmentation and regularization.

2. Try to memorize

Train repeatedly on only those examples and watch training loss and accuracy.

3. Interpret

If loss cannot become very small, fix the data, model, gradients or loop before tuning generalization.

What the test does not prove: memorizing 20 examples only shows that the training path can fit them. It does not prove the model will generalize to new factory images.

A Complete PyTorch Training and Validation Loop

This code mirrors the diagrams exactly. The inner loop performs one correction per training batch. The second loop measures validation batches without gradients or updates.

training_loop.py
for epoch in range(num_epochs):
    # ----- TRAIN: weights change -----
    model.train()
    train_loss_sum = 0.0

    for inputs, targets in train_loader:       # 1. load batch
        inputs, targets = inputs.to(device), targets.to(device)
        optimizer.zero_grad()                   # 2. clear old gradients
        logits = model(inputs)                  # 3. forward pass
        loss = loss_fn(logits, targets)         # 4. calculate loss
        loss.backward()                         # 5. backward pass
        optimizer.step()                        # 6. update weights
        train_loss_sum += loss.item() * inputs.size(0)

    train_loss = train_loss_sum / len(train_loader.dataset)

    # ----- VALIDATE: weights do not change -----
    model.eval()
    val_loss_sum = 0.0
    correct = 0

    with torch.no_grad():
        for inputs, targets in val_loader:
            inputs, targets = inputs.to(device), targets.to(device)
            logits = model(inputs)
            val_loss_sum += loss_fn(logits, targets).item() * inputs.size(0)
            correct += (logits.argmax(dim=1) == targets).sum().item()

    val_loss = val_loss_sum / len(val_loader.dataset)
    val_accuracy = correct / len(val_loader.dataset)
    print(epoch + 1, train_loss, val_loss, val_accuracy)
CodePlain meaningCommon mistake it prevents
model.train()Turn on training behaviourAccidentally leaving dropout disabled
optimizer.zero_grad()Remove gradients from the previous batchUnwanted gradient accumulation
loss.backward()Calculate current gradientsOptimizer stepping with no new direction
optimizer.step()Change the weightsThinking backward itself updates parameters
model.eval()Use inference behaviourValidation changing with dropout/BatchNorm mode
torch.no_grad()Do not record a backward graphWasting validation memory and computation

Built-In Training or a Custom Loop?

A custom loop is valuable for understanding and unusual training logic, but it also creates more opportunities for mistakes. Use the simplest interface that supports the actual experiment.

SituationRecommended approachWhy
Ordinary classification or regressionBuilt-in fit/trainerLess boilerplate; callbacks and metrics are already integrated
Learn how training worksSmall explicit loopEvery operation remains visible
Several losses or optimizersCustom step or custom loopYou control exactly what updates and when
GANs, reinforcement learning, gradient accumulationCustom loopThe algorithm does not fit one standard forward-loss-update cycle
Production experiment trackingFramework loop plus callbacks when possibleReduces custom state and resuming errors

A Debugging Order That Saves Time

When training fails, changing the architecture first usually hides the real problem. Check the pipeline from the earliest input to the final update.

1. Inspect one batch

Print shapes, data type, minimum, maximum and several labels. Display images after preprocessing.

2. Check the forward output

Confirm output shape, finite values and the expected logits/probabilities for the loss.

3. Check loss on known cases

A better hand-made prediction should receive lower loss than a worse one.

4. Check gradients

Verify important parameters have non-None, finite gradient values and sensible norms.

5. Check the update

Compare one weight before and after optimizer.step(); it should change during training only.

6. Run the tiny-data test

Prove the model can fit 10–20 examples before adding regularization or more layers.

Common Mistakes

MistakeWhat goes wrongCorrection
Do not clear gradientsCurrent and earlier batch gradients are addedCall zero_grad each step unless accumulation is intentional
Validate in training modeDropout and BatchNorm behave incorrectly for evaluationCall model.eval() before validation
Update on validation dataValidation stops being independentNever call backward or optimizer.step in validation
Average batch means incorrectlySmall final batch can receive too much influenceAccumulate loss × batch size, then divide by example count
Watch accuracy onlyConfidence and loss problems remain hiddenTrack task metrics and loss together
Use the test set every epochModel choices indirectly overfit the test setTune on validation; evaluate test once choices are frozen

What to remember

One batch creates one correction

Load → clear → forward → loss → backward → update.

One epoch visits the training set once

Batch size determines the number of updates per epoch.

Validation measures; it never teaches

Use evaluation mode, no gradients and no weight updates.

Curves are diagnostic evidence

Compare training and validation trends, then investigate causes in order.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Training and Debugging a Neural Network"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • A batch follows load, clear, forward, loss, backward, and update.
  • An epoch visits the training set once through many batches.
  • Validation measures in evaluation mode without parameter updates.
  • Diverging training and validation curves can indicate overfitting.
  • A tiny-data overfit test checks the complete learning path.
  • Metrics and checkpoints make runs diagnosable and resumable.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
Which order is correct for one training batch?
Question 2 of 5conceptual
What does one epoch mean?
Question 3 of 5interpretation
Why use evaluation mode and no gradients during validation?
Question 4 of 5debugging/diagnostic
Training loss falls while validation loss rises. What is the likely warning?
Question 5 of 5practical selection
Why try to overfit 10–20 clean examples?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Which order is correct for one training batch?▼

Correct Answer: Clear → forward → loss → backward → update

The model predicts, loss measures the error, backward computes gradients, and the optimizer then updates parameters.

2What does one epoch mean?▼

Correct Answer: One pass through the training set

An epoch visits all training examples once, commonly through many mini-batches.

3Why use evaluation mode and no gradients during validation?▼

Correct Answer: Validation measures fixed parameters and should not update training state

Validation must observe the current model without weight updates or training-only layer behavior.

4Training loss falls while validation loss rises. What is the likely warning?▼

Correct Answer: Overfitting

The model is improving on seen data while becoming worse on unseen data, the characteristic overfitting pattern.

5Why try to overfit 10–20 clean examples?▼

Correct Answer: To test whether data, loss, gradients, and updates are connected

A functioning high-capacity model should memorize a tiny clean set; failure points to an implementation or data-path problem.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next