The neural notebook
← All chapters

IV-01 / Part I · Neural Network Foundations

From Fixed Neurons to Learning

Separate a fixed prediction from its target, loss, gradient and one explicitly applied parameter update.

Review the ideas this chapter uses

Suppose a little calculation receives the number two and returns two. You wanted five. Telling the calculation that five was desired does not, by itself, change how it calculates. Learning needs an explicit rule that changes its adjustable numbers.

This is the first distinction to make in a neural-network book: a forward calculation can run perfectly while producing an unsuitable prediction. The interaction begins in fixed prediction mode, so you can inspect that distinction before applying an update.

Compute it yourself

From fixed neurons to one declared update

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
x
2
y
5
w
1
b
0
eta
0.125
update
0
prediction2
loss4.5
nextPrediction2
nextLoss4.5

prediction 2. loss 4.5. nextPrediction 2. nextLoss 4.5. Fixed forward calculation. The target is not an operand of the prediction.. product 2. prediction 2

Fixed forward calculation

prediction=w*x+b

The target is not an operand of the prediction.

Inputs

w
1
x
2
b
0

Outputs

product
2
prediction
2

Fixed parameters: the proposal is not applied.

Starting forward path

x=2 → weight w=1, bias b=0 → prediction=2 → target y=5 → loss=4.5.

ParameterOriginalGradientProposedApplied
w1-61.751
b0-30.3750

Selected operation: Fixed forward calculation. Moving the trace does not train again.

Inspect tensor shapes and full precision

All computed outputs

prediction
2
loss
4.5
nextPrediction
2
nextLoss
4.5
error
-3
dW
-6
dB
-3
proposedW
1.75
proposedB
0.375
nextW
1
nextB
0
update
0

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

parametersBefore

parameter=2 × column=1 · float64 · display precision 8 · Authored toy: rows w,b; original values.

Storage indexValue
01
10

gradients

parameter=2 × column=1 · float64 · display precision 8 · Analytic derivatives of half-squared error; rows w,b.

Storage indexValue
0-6
1-3

parametersProposed

parameter=2 × column=1 · float64 · display precision 8 · One SGD proposal; rows w,b.

Storage indexValue
01.75
10.375

parametersAfter

parameter=2 × column=1 · float64 · display precision 8 · Applied values conditional on update; rows w,b.

Storage indexValue
01
10

forward.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward: prediction=w*x+b

Storage indexValue
02

forward.prediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · forward: prediction=w*x+b

Storage indexValue
02

loss.error

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · loss: error=prediction-y; loss=error*error/2

Storage indexValue
0-3

loss.squaredError

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · loss: error=prediction-y; loss=error*error/2

Storage indexValue
09

loss.loss

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · loss: error=prediction-y; loss=error*error/2

Storage indexValue
04.5

gradients.dW

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · gradients: dW=error*x; dB=error

Storage indexValue
0-6

gradients.dB

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · gradients: dW=error*x; dB=error

Storage indexValue
0-3

proposal.deltaW

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · proposal: proposedW=w-eta*dW; proposedB=b-eta*dB

Storage indexValue
0-0.75

proposal.deltaB

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · proposal: proposedW=w-eta*dW; proposedB=b-eta*dB

Storage indexValue
0-0.375

proposal.proposedW

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · proposal: proposedW=w-eta*dW; proposedB=b-eta*dB

Storage indexValue
01.75

proposal.proposedB

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · proposal: proposedW=w-eta*dW; proposedB=b-eta*dB

Storage indexValue
00.375

apply.nextW

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · apply: nextParameters = update ? proposedParameters : originalParameters

Storage indexValue
01

apply.nextB

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · apply: nextParameters = update ? proposedParameters : originalParameters

Storage indexValue
00

fresh.nextProduct

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · fresh: nextPrediction=nextW*x+nextB; nextLoss=(nextPrediction-y)^2/2

Storage indexValue
02

fresh.nextPrediction

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · fresh: nextPrediction=nextW*x+nextB; nextLoss=(nextPrediction-y)^2/2

Storage indexValue
02

fresh.nextError

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · fresh: nextPrediction=nextW*x+nextB; nextLoss=(nextPrediction-y)^2/2

Storage indexValue
0-3

fresh.nextSquaredError

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · fresh: nextPrediction=nextW*x+nextB; nextLoss=(nextPrediction-y)^2/2

Storage indexValue
09

fresh.nextLoss

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · fresh: nextPrediction=nextW*x+nextB; nextLoss=(nextPrediction-y)^2/2

Storage indexValue
04.5

First change only the target in fixed mode. Then select exactly one update. Reset restores authored toy values; no repeated optimization or trained-model claim is hidden here.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. At x=2, prediction=2. What role does y=5 play?
2. Prediction=2, target=5. What is the signed error?
3. Error=-3, input=2. Which value is dW?
4. Keep w=1, b=0, x=2 fixed. In fixed mode, what happens to prediction when only y changes?
5. This run has loss=4.5 and nextLoss=4.5. Which general claim is justified?

Change only Target y. The fixed prediction stays put while the error and loss change. Reset, then choose Exactly one SGD update to apply the displayed proposal. Moving backward and forward in the trace inspects saved arithmetic; it does not repeatedly optimize the model.

What each number controls

A neuron here is a numerical function, not a biological cell simulation. Its input is xx, its weight is ww, and its bias is bb. The weight multiplies the input. The bias adds an offset afterward. Its prediction, written y^\hat y and named prediction in code, is

y^=wx+b.\hat y=wx+b.

We call ww and bb parameters because an optimization procedure is allowed to change them. The observed input xx and desired target yy are data. The learning rate η\eta, pronounced “eta,” controls the size of an update and is a hyperparameter rather than a fitted weight. These roles matter more than whether a number happens to be editable in an educational interface.

Every quantity in this example is scalar: it contains one real number. In the mathematical column convention, the input, weight and bias can each be represented as a one-by-one tensor. A tensor is simply a numerical collection with declared dimensions. The inspector’s two-entry parameter columns have rows for ww and bb; they do not represent two training samples.

Our numbers are self-authored toy values. There is no hidden dataset, pretrained model or measured performance result. The default values are x=2,y=5,w=1,b=0x=2,y=5,w=1,b=0, with η=1/8\eta=1/8. You should be able to explain every resulting number without trusting a neural-network library.

A forward pass has no target operand

A forward pass evaluates the model using its current parameters:

wx=(1)(2)=2,y^=2+0=2.wx=(1)(2)=2,\qquad \hat y=2+0=2.

Notice that yy does not occur in that expression. If you change yy from five to seven while keeping x,w,bx,w,b fixed, the prediction remains two. The calculation does not automatically adopt the target as its answer. This is why editing labels, drawing a desired output or displaying an error message is not evidence that a model learned.

The target enters a separate comparison. Define signed error e=y^−ye=\hat y-y. At the default point,

e=2−5=−3.e=2-5=-3.

The negative sign means the prediction is below the target. To score the size of the discrepancy, use half-squared error:

L=e22=(−3)22=92.L=\frac{e^2}{2}=\frac{(-3)^2}{2}=\frac92.

A loss is the numerical objective that an optimizer tries to reduce. Squaring makes the loss nonnegative and treats equally sized positive and negative errors symmetrically. The factor one half simplifies the derivative later. It is a declared convention: changing it would change gradient scale for the same prediction.

A gradient describes nearby change

A derivative measures how quickly one quantity changes when another changes a little. A gradient collects such sensitivities for the trainable parameters. Here we need one derivative for ww and one for bb. In the notation ∂L/∂w\partial L/\partial w, the partial symbol means that the other inputs are held fixed.

For the half-square, the loss derivative with respect to prediction is the error itself. Increasing the weight changes prediction at rate xx, whereas increasing the bias changes prediction at rate one. Multiplying these local effects gives

∂L∂w=ex=(−3)(2)=−6,∂L∂b=e=−3.\frac{\partial L}{\partial w}=ex=(-3)(2)=-6, \qquad \frac{\partial L}{\partial b}=e=-3.

The code calls these dW and dB. Their negative signs say that a sufficiently small increase in either parameter lowers loss at this starting point. They are not new parameter values. They also do not promise what a large change will do: a derivative describes a local slope, while a finite update can travel well beyond that local neighborhood.

The trace computes both gradients from the original w,bw,b. This is a small example of the chain rule, which combines local sensitivities through a composition. Later chapters will trace that rule through multiple hidden operations rather than presenting it as a mysterious automatic procedure.

Propose, then explicitly apply

Stochastic gradient descent, or SGD, subtracts learning rate times gradient. In this single-sample example the proposal is

w′=w−η dW=1−18(−6)=74,b′=b−η dB=0−18(−3)=38.w'=w-\eta\,dW=1-\frac18(-6)=\frac74, \qquad b'=b-\eta\,dB=0-\frac18(-3)=\frac38.

Subtracting a negative gradient increases the corresponding parameter. Both new values use the same original gradient state; this is a simultaneous update. Computing one new parameter and then recalculating the other gradient from that changed state would be a different procedure.

The table distinguishes original, proposed and applied values. In fixed mode, the proposal is educational information: the applied values remain w=1,b=0w=1,b=0. Therefore the actual next prediction and loss also remain two and 9/29/2. Only selecting one-update mode makes the applied parameters equal the proposal.

After that one update, we evaluate again rather than estimating the outcome from the gradient:

y^′=74⋅2+38=288+38=318,\hat y'=\frac74\cdot2+\frac38=\frac{28}{8}+\frac38=\frac{31}{8}, e′=318−5=−98,L′=(−9/8)22=81128.e'=\frac{31}{8}-5=-\frac98, \qquad L'=\frac{(-9/8)^2}{2}=\frac{81}{128}.

The loss decreased for this particular step. All these fractions have finite binary representations, so they provide useful exact reference arithmetic. Arbitrary decimal edits usually involve floating-point rounding; formatted display values are never inputs to the next calculation.

Why more movement can be worse

Reset, select one update, and set η=1\eta=1. The original gradients are still −6-6 and −3-3, but the updated parameters become w′=7,b′=3w'=7,b'=3. The new prediction is seventeen, the new error is twelve, and the new loss is seventy-two. A direction that helps locally has overshot badly.

For this neuron, substitution shows how that happens:

e′=(w−ηex)x+(b−ηe)−y=e−ηex2−ηe.e'=(w-\eta ex)x+(b-\eta e)-y =e-\eta ex^2-\eta e.

Factoring out the original error gives

e′=(1−η(x2+1))e.e'=\bigl(1-\eta(x^2+1)\bigr)e.

The expression is obtained by inserting both parameter updates into w′x+b′−yw'x+b'-y. It shows why the input’s magnitude affects step size: the weight’s contribution includes another factor of xx. There is no universal safe rate supplied merely by the word “gradient.” At η=0\eta=0, both parameter changes vanish and the update is a defined no-op.

The controls require finite data and parameters of magnitude at most one hundred, with rate between zero and two. A finite proposed update can leave the allowed starting range; it is not silently clamped. An edit from such a saved frame must restore valid starting inputs. This preserves the actual calculation instead of manufacturing a nicer-looking result.

Read the numerical source

The Python reference below makes the dependency order explicit: prediction, error, loss, two gradients, two deltas, both proposed parameters, conditional application, then fresh prediction and loss. NumPy supplies binary64 scalar arithmetic, not an optimizer or automatic differentiation 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-01: a fixed scalar neuron, an explicit proposal, and optionally one update."""
import numpy as np
from reference import validate, choice, finite, guarded, tensor, step, result, run

DEFAULT_IV01 = {"x": 2, "y": 5, "w": 1, "b": 0, "eta": 0.125, "update": 0}


@guarded
def derive_iv01(state):
    """Every update uses both derivatives at the original parameter state."""
    s = validate(state, DEFAULT_IV01, {"eta": (0, 2)})
    choice(s["update"], [0, 1], "update")
    x, y, w, b, eta, update = (s[key] for key in DEFAULT_IV01)
    # Prediction does not read y. The target enters only the loss calculation.
    product = finite(w * x, "w*x")
    prediction = finite(product + b, "prediction")
    error = finite(prediction - y, "error")
    squaredError = finite(error * error, "squaredError")
    loss = finite(squaredError / np.float64(2), "loss")
    dW = finite(error * x, "dW")
    dB = error
    deltaW = finite(eta * dW, "deltaW")
    deltaB = finite(eta * dB, "deltaB")
    proposedW = finite(w - deltaW, "proposedW")
    proposedB = finite(b - deltaB, "proposedB")
    # Fixed mode shows the proposal but does not apply it.
    nextW, nextB = (proposedW, proposedB) if update == 1 else (w, b)
    nextProduct = finite(nextW * x, "nextProduct")
    nextPrediction = finite(nextProduct + nextB, "nextPrediction")
    nextError = finite(nextPrediction - y, "nextError")
    nextSquaredError = finite(nextError * nextError, "nextSquaredError")
    nextLoss = finite(nextSquaredError / np.float64(2), "nextLoss")
    updated = dict(s, w=nextW, b=nextB)
    steps = [
        step("forward", "Fixed forward calculation", "prediction=w*x+b", "The target is not an operand of the prediction.", {"w": w, "x": x, "b": b}, {"product": product, "prediction": prediction}, s),
        step("loss", "Compare with the target", "error=prediction-y; loss=error*error/2", "Changing y changes loss, not the fixed prediction.", {"prediction": prediction, "y": y}, {"error": error, "squaredError": squaredError, "loss": loss}, s),
        step("gradients", "Local loss sensitivities", "dW=error*x; dB=error", "Both gradients use the original parameters.", {"error": error, "x": x}, {"dW": dW, "dB": dB}, s),
        step("proposal", "Proposed simultaneous update", "proposedW=w-eta*dW; proposedB=b-eta*dB", "A proposal is not an applied update.", {"w": w, "b": b, "eta": eta, "dW": dW, "dB": dB}, {"deltaW": deltaW, "deltaB": deltaB, "proposedW": proposedW, "proposedB": proposedB}, s),
        step("apply", "Apply exactly one simultaneous update" if update == 1 else "Keep the parameters fixed", "nextParameters = update ? proposedParameters : originalParameters", "Only update=1 applies the proposal.", {"update": update, "w": w, "b": b, "proposedW": proposedW, "proposedB": proposedB}, {"nextW": nextW, "nextB": nextB}, updated),
        step("fresh", "Fresh prediction and loss", "nextPrediction=nextW*x+nextB; nextLoss=(nextPrediction-y)^2/2", "Recompute the actual outcome.", {"nextW": nextW, "x": x, "nextB": nextB, "y": y}, {"nextProduct": nextProduct, "nextPrediction": nextPrediction, "nextError": nextError, "nextSquaredError": nextSquaredError, "nextLoss": nextLoss}, updated),
    ]
    tensors = [tensor("parametersBefore", [2, 1], ["parameter", "column"], [w, b], "Authored toy: rows w,b; original values."),
               tensor("gradients", [2, 1], ["parameter", "column"], [dW, dB], "Analytic gradients; rows w,b."),
               tensor("parametersProposed", [2, 1], ["parameter", "column"], [proposedW, proposedB], "One SGD proposal; rows w,b."),
               tensor("parametersAfter", [2, 1], ["parameter", "column"], [nextW, nextB], "Applied values conditional on update; rows w,b.")]
    return result(tensors, steps, {"prediction": prediction, "loss": loss, "nextPrediction": nextPrediction, "nextLoss": nextLoss,
                                  "error": error, "dW": dW, "dB": dB, "proposedW": proposedW, "proposedB": proposedB,
                                  "nextW": nextW, "nextB": nextB, "update": update})


if __name__ == "__main__":
    run(derive_iv01, DEFAULT_IV01)

The sibling helper file handles bounded input validation, tensor records, JSON and error reporting. To use the references later, keep both files in the same directory. Each chapter script accepts its default or a complete JSON state; a dash reads JSON from standard input. These are authored entry points, not claims of executed validation.

Read the shared 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=(",", ":")))

Try the five questions with a changed target. They ask you to distinguish a target from a parameter, compute signed error and a gradient, predict a target edit, and recognize a finite-step counterexample. If an answer differs, inspect the first operation where the operands diverge.

What one update establishes

  • A prediction is determined by inputs and parameters; a target supplies a comparison.
  • Loss and gradients can be computed without applying an update.
  • One simultaneous update changes both parameters using their original gradients.
  • Fresh evaluation reveals improvement, no change or overshoot.

Even a zero loss on this one point would not establish useful predictions elsewhere: many lines pass through one point. “Trainable” describes the adjustable model; “trained” needs a disclosed optimization history. Revisit the artificial neuron, composition and parameters, loss and optimization for the earlier foundations. Next, we give several inputs and outputs explicit shapes so that every multiplication has a clear meaning.