IV-05 / Part I · Neural Network Foundations
Losses, Targets and Reduction Rules
Compute squared error, stable binary cross-entropy and multiclass NLL sample by sample, then explicitly choose mean or sum.
A prediction has no built-in notion of success. Predicting a real measurement, choosing between two outcomes and choosing among three categories require different comparisons. A loss makes that comparison numerical, but only after we specify what the target means.
The interaction keeps two samples throughout. Start with exact fractional squared errors, then switch to binary or multiclass classification. Finally choose whether to sum the two sample losses or take their mean. These choices change actual arithmetic rather than merely relabeling a chart.
Choose the task, then the sample reduction
These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.
Complete results from this trace’s starting inputs
Starting inputs for these results
- mode
- 0
- reduction
- 0
- p0
- 0.25
- p1
- -0.75
- y0
- 0
- y1
- 1
- z0
- 0
- z1
- 0
- a0
- 0
- a1
- 0
- a2
- 0
- class0
- 0
- class1
- 1
objective 0.78125. sampleLoss0 0.03125. sampleLoss1 1.53125. meanLoss 0.78125. Half-squared error: sample 0. A real target is compared directly with a real prediction. There is one output per sample.. error 0.25. square 0.0625. sampleLoss 0.03125
Half-squared error: sample 0
error=prediction-target; sampleLoss=error*error/2
A real target is compared directly with a real prediction. There is one output per sample.
Inputs
- prediction
- 0.25
- target
- 0
Outputs
- error
- 0.25
- square
- 0.0625
- sampleLoss
- 0.03125
Real prediction versus real target. Only the active family's score/target controls enter its loss. All fields still require valid finite values.
| sample index | output_feature 0 |
|---|---|
| 0 | 0.25 |
| 1 | -0.75 |
Editable real predictions or binary logits, according to mode.
| sample index | target 0 |
|---|---|
| 0 | 0 |
| 1 | 1 |
Real targets, binary labels, or validated integer class IDs, according to mode.
| sample index | loss 0 |
|---|---|
| 0 | 0.03125 |
| 1 | 1.53125 |
One loss per sample before reduction.
Sum=1.5625; mean=0.78125; selected objective=0.78125. Selected operation: Half-squared error: sample 0. No feature or class averaging is hidden.
Inspect tensor shapes and full precision
All computed outputs
- objective
- 0.78125
- sampleLoss0
- 0.03125
- sampleLoss1
- 1.53125
- meanLoss
- 0.78125
- sumLoss
- 1.5625
- mode
- 0
- reduction
- 0
Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.
scores
sample=2 × output_feature=1 · float64 · display precision 8 · Editable real predictions or binary logits, according to mode.
| Storage index | Value |
|---|---|
| 0 | 0.25 |
| 1 | -0.75 |
targets
sample=2 × target=1 · float64 · display precision 8 · Real targets, binary labels, or validated integer class IDs, according to mode.
| Storage index | Value |
|---|---|
| 0 | 0 |
| 1 | 1 |
sample_losses
sample=2 × loss=1 · float64 · display precision 8 · One loss per sample before reduction.
| Storage index | Value |
|---|---|
| 0 | 0.03125 |
| 1 | 1.53125 |
squared-0.error
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · squared-0: error=prediction-target; sampleLoss=error*error/2
| Storage index | Value |
|---|---|
| 0 | 0.25 |
squared-0.square
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · squared-0: error=prediction-target; sampleLoss=error*error/2
| Storage index | Value |
|---|---|
| 0 | 0.0625 |
squared-0.sampleLoss
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · squared-0: error=prediction-target; sampleLoss=error*error/2
| Storage index | Value |
|---|---|
| 0 | 0.03125 |
squared-1.error
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · squared-1: error=prediction-target; sampleLoss=error*error/2
| Storage index | Value |
|---|---|
| 0 | -1.75 |
squared-1.square
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · squared-1: error=prediction-target; sampleLoss=error*error/2
| Storage index | Value |
|---|---|
| 0 | 3.0625 |
squared-1.sampleLoss
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · squared-1: error=prediction-target; sampleLoss=error*error/2
| Storage index | Value |
|---|---|
| 0 | 1.53125 |
reduction.sumLoss
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reduction: sumLoss=sampleLoss0+sampleLoss1; meanLoss=sumLoss/2
| Storage index | Value |
|---|---|
| 0 | 1.5625 |
reduction.meanLoss
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reduction: sumLoss=sampleLoss0+sampleLoss1; meanLoss=sumLoss/2
| Storage index | Value |
|---|---|
| 0 | 0.78125 |
reduction.objective
scalar_row=1 × scalar_column=1 · float64 · display precision 8 · reduction: sumLoss=sampleLoss0+sampleLoss1; meanLoss=sumLoss/2
| Storage index | Value |
|---|---|
| 0 | 0.78125 |
Start with the two exact fractional squared losses. Then compare zero binary logits and zero multiclass logits. For multiclass, the second row reverses a0,a1,a2; it is not an independently editable third dataset.
Check your understanding
Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.
Only the selected family’s scores enter its loss. Squared error uses p0,p1; binary cross-entropy uses z0,z1; multiclass uses the three a controls and integer class selections. The other controls remain visible for comparison and are still checked for valid finite values. There is no optimizer or generated training curve in this chapter.
A target number needs a task
For a real-valued prediction, a target such as one half is a desired numerical output. For the binary task here, a target is exactly zero or one, identifying which of two outcomes occurred. For multiclass classification, a target is an integer class ID: zero, one or two selects one entry from a three-class row.
These interpretations are not interchangeable. A class ID of two is an index, not a request for a prediction twice as large as class one. Similarly, this binary lesson deliberately rejects a target of one half rather than silently introducing a soft-label objective that has not been specified. The same one half remains a valid real target for squared error.
A logit is an unrestricted real score used before probability normalization. It is not itself a probability: it can be negative or greater than one. A probability lies between zero and one; a multiclass probability row sums to one. Loss calculations must know whether their inputs are real predictions, logits or already normalized probabilities.
Our sample axis always has length two. Regression predictions and binary logits have shape . Multiclass scores have shape , with axes sample,class_score. Targets and unreduced sample losses each have shape . A change in task does not add a hidden average over the class axis.
Half-squared error, one sample at a time
For sample , with prediction and real target , define
The lower-case denotes one sample’s loss. We reserve the selected objective for the later reduction. At the defaults , the signed errors are
Squaring and halving separately gives
This calculation does not treat the negative prediction as an invalid probability. It is a real output in a real-valued task. The square removes the error’s sign, while the magnitude determines the penalty. The factor one half is the same derivative-simplifying convention used in the first chapter.
An overall total is not needed to understand either sample. The trace therefore records each error and squared error before combining the losses. If a final number seems wrong, first check whether one sample’s target was misinterpreted or the reduction was changed.
Sum and mean are different objectives
A reduction combines per-sample losses into one scalar. The sum and sample mean here are
The default objective is the mean. Switching to sum changes the selected objective to while leaving both sample losses unchanged. The number two in the denominator counts samples. It does not count output features or classes.
This scale choice matters for optimization: summing gradients from two samples and averaging them differ by a factor of two. Later, a learning rate that worked with one convention cannot be assumed equivalent under the other. Here we show the arithmetic rather than claiming a training effect, since no gradient step is performed.
A smaller reported number after changing reduction is not evidence that predictions improved. Nor are loss magnitudes from different tasks automatically comparable. A squared measurement error and a logarithmic classification penalty answer different questions and may have different units or scales.
Binary cross-entropy from logits
For binary classification, let be a logit and its probability for outcome one. The binary cross-entropy, or BCE, can be described mathematically as
The logarithm here is natural logarithm, written or . The negative log probability penalizes assigning low probability to the observed outcome. A correct high-confidence prediction receives a small penalty; a confidently wrong prediction receives a large one.
Directly evaluating that expression from rounded probabilities can fail when rounds to zero or one. The reference instead uses the stable logit formula
The exponential argument is nonpositive. The code evaluates the final logarithmic correction with log1p, a numerical function designed to retain accuracy for when is small. The trace shows the maximum term, target product, linear difference, exponential and correction before their final sum.
At either default binary logit , the maximum and product terms are zero. The exponential is one, so each sample loss is , for either binary target. The sum is and the mean is . These are exact symbolic expectations, not stored decimal measurements.
Why the stable binary formula is the same loss
Write for the probability of outcome one. If , the loss is . If , it is . Combining these two binary cases gives
For , factor out of the logarithm’s argument:
For , keep as it is, since its exponential argument is already negative. Both branches can be expressed together as
log1p evaluates the final without first rounding the addition . We changed the evaluation strategy, not the binary objective or target meaning.
Try with target zero. The stable expression has linear term one thousand and a tiny correction, so the penalty is large and finite. With target one, its linear terms cancel and only the tiny correction remains. That correction can underflow to stored zero. The true analytic loss at a finite logit is still positive; a computed zero here is not proof of perfect certainty.
Multiclass negative log-likelihood
For three classes, each sample supplies a row of logits. The authored first row is and the second is . This reversal makes the samples related but distinct when logits differ. class0 and class1 independently select their target classes.
The negative log-likelihood, or NLL, of target class is computed as
The target logit is the entry selected by the integer class ID. To evaluate the normalizer stably, find , shift each logit and sum the exponentials:
At three zero logits, , all shifted logits are zero, and all three exponential terms are one. Thus , the normalizer is , and either target class has loss . The mean across the two default samples is also ; the sum is .
The trace exposes every shifted term and partial denominator sum. The final normalizer uses those same recorded maximum and logarithmic denominator values. Probabilities are available for interpretation as , but the loss does not take their logarithms.
Why NLL becomes logsumexp minus the target logit
For target class , softmax assigns . Taking negative natural logarithm and using the log quotient rule gives
To evaluate the sum safely, factor out , where is the largest logit:
Every shifted argument is nonpositive and at least one is zero. Thus includes a term equal to one and is never a zero denominator. This algebra explains both the stable normalization and why no logarithm of a stored probability is needed.
Why probabilities are an unsafe intermediate for NLL
Set the first row to and choose target class zero. After shifting by one thousand, the exponential arguments are . Some stored terms can underflow to zero. Taking the logarithm of the target’s stored zero probability would produce an infinite result, even though the original logit-based loss is finite, approximately two thousand.
The stable formula preserves the useful logit difference instead. Numerical underflow in a probability display is therefore not permission to replace the loss by infinity or invent a positive floor. Adding the same constant to all logits leaves their relative probabilities and exact NLL unchanged, another useful identity to inspect within the input bounds.
All logits are bounded in magnitude by one thousand. Real predictions and real targets are bounded by one hundred. Modes, reductions and class IDs are validated as integral choices, with binary labels additionally checked when BCE is selected. Invalid values yield an unavailable result rather than silent clipping, class rounding or a different objective.
Read the source, then interpret the questions
The reference computes sample losses first and reduction last. It uses explicit NumPy scalar operations, including the stable binary correction and the class-index-ordered multiclass sum. The sibling helper supplies validation, JSON and records rather than hiding a loss engine.
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""IV-05: samplewise losses with explicit sum/mean reduction and stable logits."""
import numpy as np
from reference import validate, choice, finite, guarded, tensor, step, result, run
DEFAULT_IV05 = {"mode": 0, "reduction": 0, "p0": 0.25, "p1": -0.75, "y0": 0, "y1": 1,
"z0": 0, "z1": 0, "a0": 0, "a1": 0, "a2": 0, "class0": 0, "class1": 1}
@guarded
def derive_iv05(state):
"""Never take log of a rounded softmax probability to compute NLL."""
s = validate(state, DEFAULT_IV05, {key: (-1000, 1000) for key in ["z0", "z1", "a0", "a1", "a2"]})
choice(s["mode"], [0, 1, 2], "mode")
choice(s["reduction"], [0, 1], "reduction")
for key in ["class0", "class1"]:
choice(s[key], [0, 1, 2], key)
mode, reduction = int(s["mode"]), int(s["reduction"])
if mode == 1:
choice(s["y0"], [0, 1], "binary y0")
choice(s["y1"], [0, 1], "binary y1")
targets = [s["class0"], s["class1"]] if mode == 2 else [s["y0"], s["y1"]]
scoreRows = ([[s["a0"], s["a1"], s["a2"]], [s["a2"], s["a1"], s["a0"]]] if mode == 2 else
[[s["p0"] if mode == 0 else s["z0"]], [s["p1"] if mode == 0 else s["z1"]]])
steps, losses, probabilities = [], [], []
for sample in range(2):
target = targets[sample]
if mode == 0:
prediction = scoreRows[sample][0]
error = finite(prediction - target, "squared error")
square = finite(error * error, "error square")
value = finite(square / np.float64(2), "half-squared loss")
steps.append(step(f"squared-{sample}", f"Half-squared error: sample {sample}", "error=prediction-target; sampleLoss=error*error/2", "A real target is compared to a real prediction.", {"prediction": prediction, "target": target}, {"error": error, "square": square, "sampleLoss": value}))
elif mode == 1:
z = scoreRows[sample][0]
positive = finite(np.float64(z if z > 0 else 0), "positive logit")
targetProduct = finite(z * target, "logit times target")
linear = finite(positive - targetProduct, "BCE linear term")
negativeMagnitude = finite(-np.abs(z), "negative logit magnitude")
expTerm = finite(np.exp(negativeMagnitude), "BCE exponential")
correction = finite(np.log1p(expTerm), "BCE log1p")
value = finite(linear + correction, "BCE loss")
steps.append(step(f"bce-{sample}", f"Stable binary cross-entropy: sample {sample}", "sampleLoss=max(z,0)-z*target+log1p(exp(-abs(z)))", "The target is binary; a finite tail may underflow in stored arithmetic.", {"z": z, "target": target}, {"positive": positive, "targetProduct": targetProduct, "linear": linear, "negativeMagnitude": negativeMagnitude, "expTerm": expTerm, "correction": correction, "sampleLoss": value}))
else:
row = scoreRows[sample]
maximum = max(row)
terms, denominator = [], np.float64(0)
for category in range(3):
logit = row[category]
shifted = finite(logit - maximum, "shifted logit")
term = finite(np.exp(shifted), "shifted exponential")
priorSum = denominator
denominator = finite(priorSum + term, "softmax denominator")
terms.append(term)
steps.append(step(f"nll-{sample}-term-{category}", f"Sample {sample}, class {category}: stable normalization", "term=exp(logit-max); denominator=priorSum+term", "Subtract the maximum, then add classes in index order.", {"logit": logit, "max": maximum, "priorSum": priorSum}, {"shifted": shifted, "term": term, "denominator": denominator}))
logDenominator = finite(np.log(denominator), "log denominator")
normalizer = finite(maximum + logDenominator, "logsumexp")
targetLogit = row[int(target)] # Integer class was validated before indexing.
value = finite(normalizer - targetLogit, "NLL loss")
rowProbabilities = [finite(term / denominator, "class probability") for term in terms]
probabilities.extend(rowProbabilities)
steps.append(step(f"nll-{sample}", f"Multiclass NLL: sample {sample}", "normalizer=max+log(denominator); sampleLoss=normalizer-targetLogit", "NLL uses logits, not log of stored probabilities.", {"target": target, "max": maximum, "denominator": denominator, "targetLogit": targetLogit}, {"logDenominator": logDenominator, "normalizer": normalizer, "probability0": rowProbabilities[0], "probability1": rowProbabilities[1], "probability2": rowProbabilities[2], "sampleLoss": value}))
losses.append(value)
sumLoss = finite(losses[0] + losses[1], "sumLoss")
meanLoss = finite(sumLoss / np.float64(2), "meanLoss")
objective = meanLoss if reduction == 0 else sumLoss
steps.append(step("reduction", "Mean over two samples" if reduction == 0 else "Sum over two samples", "sumLoss=sampleLoss0+sampleLoss1; meanLoss=sumLoss/2", "Reduce across samples only, never divide by the class count.", {"sampleLoss0": losses[0], "sampleLoss1": losses[1], "reduction": reduction}, {"sumLoss": sumLoss, "meanLoss": meanLoss, "objective": objective}))
tensors = [tensor("scores", [2, 3 if mode == 2 else 1], ["sample", "output_feature" if mode == 0 else "class_score"], [value for row in scoreRows for value in row], "Editable predictions or logits; second multiclass row is reversed."),
tensor("targets", [2, 1], ["sample", "target"], targets, "Validated task-specific targets."),
tensor("sample_losses", [2, 1], ["sample", "loss"], losses, "Loss before reduction.")]
output = result(tensors, steps, {"objective": objective, "sampleLoss0": losses[0], "sampleLoss1": losses[1], "meanLoss": meanLoss, "sumLoss": sumLoss, "mode": mode, "reduction": reduction})
if mode == 2:
output["tensors"].append(tensor("probabilities", [2, 3], ["sample", "class"], probabilities, "Stable softmax, used only for interpretation."))
return output
if __name__ == "__main__":
run(derive_iv05, DEFAULT_IV05)
Read the validation and JSON helpers
Read the complete executable Python / NumPy source
This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.
"""Small serialization/validation helpers for the five standalone references.
Run each ivNN.py from its path; this sibling module is then on Python's import
path. This module supplies no neuron, matrix multiplication or loss algorithm.
"""
import argparse
from functools import wraps
import json
import sys
import numpy as np
class ParseFault(ValueError):
"""Owned JSON syntax/profile failure, separate from numerical validation."""
_JSON_INT = int
def _members(pairs):
value = {}
for key, member in pairs:
if key in value:
raise ParseFault("Duplicate JSON object members are not allowed.")
value[key] = member
return value
def _constant(token):
raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")
def _integer(token):
if token == "-0":
return -0.0
try:
return _JSON_INT(token)
except ValueError as error:
if type(error) is not ValueError:
raise
raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error
class NumericalFault(ValueError):
def __init__(self, code, reason):
super().__init__(reason)
self.code = code
def finite(value, label):
if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
try:
value = np.float64(value)
except (ValueError, OverflowError) as error:
raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
if not np.isfinite(value):
raise NumericalFault("NONFINITE", f"{label} must be finite.")
return value
def validate(state, defaults, bounds=None):
if type(state) is not dict:
raise NumericalFault("INVALID_INPUT", "State must be a scalar-field object.")
values = {}
for key in defaults:
minimum, maximum = (bounds or {}).get(key, (-100, 100))
value = finite(state.get(key), key)
if value < minimum or value > maximum:
raise NumericalFault("INVALID_INPUT", f"{key} must be between {minimum} and {maximum}.")
values[key] = value
if any(key not in defaults for key in state):
raise NumericalFault("INVALID_INPUT", "Only the declared scalar fields are supported.")
return values
def choice(value, allowed, label):
if not float(value).is_integer() or value not in allowed:
raise NumericalFault("INVALID_INPUT", f"{label} must be one of {allowed}.")
def guarded(derive):
@wraps(derive)
def call(state):
try:
return derive(state)
except NumericalFault as error:
return {"status": "unavailable", "code": error.code, "reason": str(error)}
except (OverflowError, FloatingPointError) as error:
return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
except (TypeError, AttributeError) as error:
return {"status": "unavailable", "code": "UNAVAILABLE", "reason": str(error)}
return call
def tensor(identifier, shape, axes, values, provenance):
if not 1 <= len(shape) <= 4 or len(shape) != len(axes) or any(not isinstance(axis, str) or not axis for axis in axes) or len(set(axes)) != len(axes):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each axis uniquely.")
count = 1
for dimension in shape:
if isinstance(dimension, bool) or not isinstance(dimension, int) or not 1 <= dimension <= 64:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: invalid dimension.")
count *= dimension
if count > 4096:
raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: at most 4096 elements are supported.")
if count != len(values):
raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match shape.")
return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": "float64",
"values": [float(finite(value, identifier)) for value in values],
"provenance": provenance, "precision": 8}
def step(identifier, label, equation, explanation, inputs, outputs, state=None):
record = {"id": identifier, "label": label, "equation": equation, "explanation": explanation,
"inputs": {key: float(value) for key, value in inputs.items()},
"outputs": {key: float(finite(value, key)) for key, value in outputs.items()}}
if state is not None:
record["state"] = {key: float(value) for key, value in state.items()}
return record
def result(tensors, steps, outputs):
for operation in steps:
for key, value in operation["outputs"].items():
tensors.append(tensor(f'{operation["id"]}.{key}', [1, 1], ["scalar_row", "scalar_column"],
[value], f'{operation["id"]}: {operation["equation"]}'))
return {"status": "defined", "tensors": tensors, "steps": steps,
"outputs": {key: float(value) for key, value in outputs.items()}}
def run(derive, defaults):
"""Later owner CLI: ivNN.py [complete JSON state | - for stdin]."""
parser = argparse.ArgumentParser(description=derive.__doc__)
parser.add_argument("state", nargs="?")
args = parser.parse_args()
if args.state is not None:
source = sys.stdin.read() if args.state == "-" else args.state
try:
state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
except (json.JSONDecodeError, ParseFault) as error:
output = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
else:
output = derive(state)
else:
state = dict(defaults)
output = derive(state)
print(json.dumps(output, allow_nan=False, separators=(",", ":")))
The default and complete-state JSON entry points support comparison. Transcendental functions require justified floating-point tolerances. The five questions address target meaning, a current sample loss, the sample mean, reduction changes and the underflow counterexample.
For earlier context, use multiclass classification and softmax regression and cross-entropy and negative log-likelihood. The preceding MLP forward pass supplied predictions but intentionally no objective.
- Specify target meaning before choosing a loss.
- Compute one loss per sample before declaring a sum or mean.
- Use stable logit-based classification formulas rather than logs of rounded probabilities.
- A changed reduction scale is not a learned improvement.
Part II will connect these scalar objectives to computational graphs and local derivatives, then derive actual parameter updates through a multilayer network.