Concepts / Loss Function Definition

Loss Function Definition

The function is named calc_accuracy_loader.

  • Programming

Predicting Accuracy Before Reading the Mechanism

Once a classification model produces predictions, you need a single number that tells you how often those predictions match the true labels. That number is classification accuracy. This article follows a practical route: first you watch a function that computes accuracy over a PyTorch data loader, then you predict what it should return, and only after that do you read the mechanism behind each line. The goal is not just to know the formula, but to locate the exact step where a result goes wrong when it does.

What do you think happens?

A tiny batch has five examples. The model predicts the labels 0, 0, 1, 1, 1, and the true labels are 0, 1, 1, 1, 0. Count the matches position by position. What accuracy should the function report for this batch?

  • 20%

  • 40%

  • 60%

  • 80%

Reveal answer
Answer:

60%, which is 3 correct predictions out of 5 examples.

Position 1 matches (0 and 0), position 2 does not (0 versus 1), position 3 matches (1 and 1), position 4 matches (1 and 1), and position 5 does not (1 versus 0). That gives 3 matches. Dividing 3 by the 5 examples gives 0.6, or 60%.

Accuracy as a Ratio of Counts

In this context, accuracy is defined as the number of correct predictions divided by the total number of examples. Written as a ratio, it looks like this: $\text{accuracy} = \frac{\text{correct predictions}}{\text{total examples}}$. The numerator counts matches between predicted and true labels. The denominator counts the examples the model was scored on.

How Each Batch Flows Through the Function

The function is named calc_accuracy_loader. It takes a data loader, a model, a device, and an optional number of batches. The data loader yields batches, and each batch contains input examples together with their target labels. For every batch that falls within the requested number of batches, the function does four things in order. It moves the inputs and targets to the chosen device. It runs the model without tracking gradients. It reads only the logits for the last output token and takes the argument of the maximum along the final dimension to turn those logits into predicted labels. Finally, it compares the predicted labels with the target labels.

Data loaderyields batchesBatchinputs and targetsMove to deviceCUDA or CPUModel forward passgradients offLast-token logitsone row per examplePredicted labelsargmax over final dimensionCompare with targetselement by elementCorrect-predictioncountsum of matches as a numbernext batchinputs and targetsforward passoutputchoose labelpredictionsmatches summed
Where does each batch go after it leaves the data loader, what does the model do with it, and where does the correct-prediction count come from?

Keeping Running Counts Across Batches

The function does not compute a separate accuracy for each batch. It keeps two running totals. After comparing one batch, it adds the number of matches to the correct counter and adds the batch size to the examples counter. The loop then moves to the next batch. When the loop ends, the function returns the ratio of the two running totals. Because the totals accumulate, the final number reflects every batch that was evaluated, not just the last one.

Worked example

Two batches with unequal sizes

Batch 1 has 5 examples and 3 correct predictions. Batch 2 has 4 examples and 2 correct predictions. What does the function return after both batches?

  1. 1
    Start the counters

    Both running totals begin at zero: correct = 0 and total = 0.

  2. 2
    Process batch 1

    Add 3 matches to the correct counter, giving 3. Add the batch size 5 to the examples counter, giving 5.

  3. 3
    Process batch 2

    Add 2 matches to the correct counter, giving 5. Add the batch size 4 to the examples counter, giving 9.

  4. 4
    Compute the final ratio

    Divide the correct total by the examples total: $\frac{5}{9} \approx 0.556$, or about 55.6%.

Result

The function returns about 0.556. Averaging the two batch accuracies (60% and 50%) would give 55%, which is a different number, because the function weights each example equally rather than each batch.

Startcorrect 0, total 0After batch 1correct 3, total 5After batch 2correct 5, total 9Final ratio5 / 9 about 0.556add batch 1 countsadd batch 2 countsloop ends, divide
How do the correct and total counters change after each batch, and when does the final accuracy get computed?

Limiting Batches with num_batches

The num_batches argument controls how much of the loader is used. If it is left as None, the function uses every batch the loader provides. If a number is supplied, the function uses the smaller of that number and the loader's length, so requesting more batches than exist does not cause an error. Limiting the batches is a way to estimate accuracy more cheaply. The worked setting in this material uses 10 batches for that purpose. Because the denominator still counts examples, a limited run gives an estimate built from fewer examples, not a different kind of measurement.

Two other setup steps happen before any batch is scored. The function sets the device to CUDA when a GPU with Nvidia CUDA support is available and to the CPU otherwise, then moves the model to that device. It also calls model.eval() to switch the model into evaluation mode and wraps each forward pass in a no-gradient context, because no training update happens during measurement. The material also calls torch.manual_seed(123) before its accuracy calculations, so that comparing results across runs reflects the model and data rather than random variation in the setup.

Reading a Near-Chance Result

Accuracy becomes useful for judgment, not just reporting, when you compare it with a baseline. In the spam classification setting, the two classes are non-spam (label 0) and spam (label 1). A random prediction would be right about 50% of the time because there are two classes. If the accuracies for the training, validation, and test splits all sit close to that level, the model is not yet performing well and needs fine-tuning. Fine-tuning means adjusting the model's parameters so that its performance improves on the specific task.

Why the Loss Function Comes First

Fine-tuning cannot begin until a loss function is defined. A loss function measures the difference between the model's predictions and the true labels, and training optimizes against it. The stated objective in this setting is to maximize spam classification accuracy, which means the model should output the correct class label for each message. Accuracy is the measure you read after the fact; the loss function is what training actually pushes on. That is why a near-chance accuracy leads to a sequence of steps rather than a single fix.

Accuracy measuredtrain, validation, testNear 50% chancelevel?two classesDefine loss functionmeasures prediction errorFine-tune modeltraining optimizes the lossMeasure accuracyagaincompare with baselinecompare with baselineyes, needs fine-tuningtraining startsevaluate
What steps must happen in order before fine-tuning can fix a near-chance accuracy, and what depends on the loss function being defined first?

Mistakes When Computing Accuracy by Hand

  • Common mistake

    Dividing correct predictions by the number of batches

    What it looks like

    Getting 5 correct over 2 batches and reporting 2.5

    Why it fails

    The denominator counts examples, not batches. Each batch contributes its batch size to the total.

    Do this instead

    Divide by the examples counter, which is 9 in the two-batch example above, giving 5/9.

  • Common mistake

    Averaging per-batch accuracies and treating the result as the overall accuracy

    What it looks like

    Averaging 60% and 50% to get 55% when the function returns about 55.6%

    Why it fails

    Batches of different sizes carry different weight in the overall count, so a simple average of batch ratios can differ from the example-weighted ratio.

    Do this instead

    Accumulate correct and total counts across batches first, then divide once.

  • Common mistake

    Reading the matches as a tensor instead of a plain number

    Why it fails

    The function extracts the sum of matches as a plain number before adding it to the running correct count.

    Do this instead

    Keep the correct counter as a number so that the final ratio is a simple division.

  • Common mistake

    Assuming num_batches larger than the loader length causes an error

    Why it fails

    The function uses the smaller of the requested number and the loader's length.

    Do this instead

    Request any number of batches; the function evaluates whatever batches exist up to that limit.

  • Common mistake

    Treating a near-chance accuracy as proof of a bug in the accuracy code

    Why it fails

    Near-chance accuracy signals that the model needs fine-tuning, and a loss function must be defined before fine-tuning begins.

    Do this instead

    Check the trace stage by stage first, then move to defining the loss and fine-tuning.

Practice Tracing a New Batch

MEDIUM

A batch has four examples. The model predicts the labels 1, 0, 0, 1, and the true labels are 1, 1, 0, 1. Count the matches position by position, then compute the accuracy this batch contributes. Explain which step of the trace you would check first if the function reported a different number.

Hints
  • Compare the predicted and true labels at each of the four positions, one at a time.
  • Position 2 is the only mismatch in this batch.
  • The denominator is the number of examples in the batch, which is 4.

Key Points to Carry Forward

Key point

Accuracy is the ratio of correct predictions to total examples. Track both as running counts across batches and divide once at the end.

Key Takeaways

  • Accuracy is the number of correct predictions divided by the total number of examples, not the number of batches.
  • calc_accuracy_loader moves each batch to the device, runs the model with gradients off, takes the argmax of the last-token logits, compares with targets, and accumulates running counts.
  • The num_batches argument limits how many batches are used and makes accuracy a cheaper estimate, without changing what the denominator counts.
  • Accuracy near the 50% chance level in a binary spam setting signals that the model needs fine-tuning, and a loss function must be defined before fine-tuning begins because training optimizes against it.

Related concepts

More concepts starting with L