The neural notebook
← All chapters

IV-02 / Part I · Neural Network Foundations

Parameters, Batches and Tensor Shapes

Convert column samples to explicit row batches, transpose weights, and reject illegal multiplication or bias broadcasting.

Review the ideas this chapter uses

One neuron used one number as input. A more useful calculation may receive several measurements and return several features for several examples. Before multiplying anything, we need to know which number belongs to which example and which feature.

A shape is not decoration beside a formula. It is a compact statement of what the calculation is allowed to combine. The interaction starts with a legal two-sample example and lets you deliberately break its dimensions.

Compute it yourself

Make a legal batch multiplication

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
B
2
D
2
H
2
Win
2
biasRows
2
x00
1
w00
1
bias0
0.5
z00-0.5
outputRows2
outputColumns2
featureCount2

z00 -0.5. outputRows 2. outputColumns 2. featureCount 2. Validate matrix dimensions. Dimensions slice the leading rows/columns of authored arrays; incompatible dimensions are rejected.. outputRows 2. outputColumns 2

Validate matrix dimensions

X[B,D] * W_row[Win,H], with D=Win and biasRows=H

Dimensions slice the leading rows/columns of authored arrays; incompatible dimensions are rejected.

Inputs

B
2
D
2
H
2
Win
2
biasRows
2

Outputs

outputRows
2
outputColumns
2

X → explicit weight transpose → dot products → explicit bias broadcast → Z. Selected operation: Validate matrix dimensions.

X: sample=2 × input_feature=2
sample indexinput_feature 0input_feature 1
012
134

Leading slice of authored [[x00,2],[3,4]].

W_col: output_feature=2 × input_feature=2
output_feature indexinput_feature 0input_feature 1
01-1
120.5

Leading slice of authored [[w00,-1],[2,0.5]].

W_row: input_feature=2 × output_feature=2
input_feature indexoutput_feature 0output_feature 1
012
1-10.5

Explicit transpose of W_col.

b: output_feature=2 × column=1
output_feature indexcolumn 0
00.5
1-0.5

Authored bias column [bias0,-0.5], sliced by biasRows.

bias_batch: sample=2 × output_feature=2
sample indexoutput_feature 0output_feature 1
00.5-0.5
10.5-0.5

Named copy of b into every sample row.

Z: sample=2 × output_feature=2
sample indexoutput_feature 0output_feature 1
0-0.52.5
1-0.57.5

Explicit ordered dot products followed by bias additions.

Inspect tensor shapes and full precision

All computed outputs

z00
-0.5
outputRows
2
outputColumns
2
featureCount
2

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

X

sample=2 × input_feature=2 · float64 · display precision 8 · Leading slice of authored [[x00,2],[3,4]].

Storage indexValue
01
12
23
34

W_col

output_feature=2 × input_feature=2 · float64 · display precision 8 · Leading slice of authored [[w00,-1],[2,0.5]].

Storage indexValue
01
1-1
22
30.5

W_row

input_feature=2 × output_feature=2 · float64 · display precision 8 · Explicit transpose of W_col.

Storage indexValue
01
12
2-1
30.5

b

output_feature=2 × column=1 · float64 · display precision 8 · Authored bias column [bias0,-0.5], sliced by biasRows.

Storage indexValue
00.5
1-0.5

bias_batch

sample=2 × output_feature=2 · float64 · display precision 8 · Named copy of b into every sample row.

Storage indexValue
00.5
1-0.5
20.5
3-0.5

Z

sample=2 × output_feature=2 · float64 · display precision 8 · Explicit ordered dot products followed by bias additions.

Storage indexValue
0-0.5
12.5
2-0.5
37.5

shapes.outputRows

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · shapes: X[B,D] * W_row[Win,H], with D=Win and biasRows=H

Storage indexValue
02

shapes.outputColumns

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · shapes: X[B,D] * W_row[Win,H], with D=Win and biasRows=H

Storage indexValue
02

transpose.entry0

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · transpose: W_row[d,h]=W_col[h,d]

Storage indexValue
01

transpose.entry1

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · transpose: W_row[d,h]=W_col[h,d]

Storage indexValue
02

transpose.entry2

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · transpose: W_row[d,h]=W_col[h,d]

Storage indexValue
0-1

transpose.entry3

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · transpose: W_row[d,h]=W_col[h,d]

Storage indexValue
00.5

broadcast.entry0

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast: bias_batch[sample,h]=b[h,0]

Storage indexValue
00.5

broadcast.entry1

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast: bias_batch[sample,h]=b[h,0]

Storage indexValue
0-0.5

broadcast.entry2

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast: bias_batch[sample,h]=b[h,0]

Storage indexValue
00.5

broadcast.entry3

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · broadcast: bias_batch[sample,h]=b[h,0]

Storage indexValue
0-0.5

dot-0-0-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-0-0-0: sum=priorSum+input*weight

Storage indexValue
01

dot-0-0-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-0-0-0: sum=priorSum+input*weight

Storage indexValue
01

dot-0-0-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-0-0-1: sum=priorSum+input*weight

Storage indexValue
0-2

dot-0-0-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-0-0-1: sum=priorSum+input*weight

Storage indexValue
0-1

bias-0-0.value

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · bias-0-0: value=sum+bias_batch[sample,h]

Storage indexValue
0-0.5

dot-0-1-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-0-1-0: sum=priorSum+input*weight

Storage indexValue
02

dot-0-1-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-0-1-0: sum=priorSum+input*weight

Storage indexValue
02

dot-0-1-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-0-1-1: sum=priorSum+input*weight

Storage indexValue
01

dot-0-1-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-0-1-1: sum=priorSum+input*weight

Storage indexValue
03

bias-0-1.value

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · bias-0-1: value=sum+bias_batch[sample,h]

Storage indexValue
02.5

dot-1-0-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-1-0-0: sum=priorSum+input*weight

Storage indexValue
03

dot-1-0-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-1-0-0: sum=priorSum+input*weight

Storage indexValue
03

dot-1-0-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-1-0-1: sum=priorSum+input*weight

Storage indexValue
0-4

dot-1-0-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-1-0-1: sum=priorSum+input*weight

Storage indexValue
0-1

bias-1-0.value

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · bias-1-0: value=sum+bias_batch[sample,h]

Storage indexValue
0-0.5

dot-1-1-0.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-1-1-0: sum=priorSum+input*weight

Storage indexValue
06

dot-1-1-0.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-1-1-0: sum=priorSum+input*weight

Storage indexValue
06

dot-1-1-1.product

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-1-1-1: sum=priorSum+input*weight

Storage indexValue
02

dot-1-1-1.sum

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · dot-1-1-1: sum=priorSum+input*weight

Storage indexValue
08

bias-1-1.value

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · bias-1-1: value=sum+bias_batch[sample,h]

Storage indexValue
07.5

Dimensions choose leading slices of the displayed authored arrays. Try changing Win alone, then repair D. A bias with the wrong number of output entries is also rejected.

Check your understanding

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

1. X currently has shape [2,2]. What does its first axis count?
2. X:[2,2], W_row:[2,2]. What is Z's shape?
3. Follow the first dot product and bias in the trace. What is Z[0,0]?
4. W_col:[2,2] becomes W_row:[2,2]. What changed?
5. Current D=Win=2. Why should selecting a different Win alone make the calculation unavailable?

Change Weight input width Win alone. The input and weight feature axes no longer match, so the result becomes unavailable with an explanation. Change Input feature count D to match it and the calculation becomes meaningful again. The interface does not silently delete an input or invent a missing weight.

Read a tensor before reading its entries

A tensor is a numerical array with a declared shape and axis meanings. A vector has one varying index; a matrix has two. Here BB counts samples, DD counts input features, HH counts output features, and Win is the number of input columns declared by the weight matrix. These dimensions can each be one or two in this bounded demonstration.

A sample is one example. A feature is one numerical measurement within it. If the two samples contain the pairs (1,2)(1,2) and (3,4)(3,4), those pairs must remain separate during a forward pass. Putting examples in a batch evaluates them together; it does not add them together or declare them identical.

The earlier mathematical convention writes one sample as a column x:[D,1]x:[D,1]. A weight matrix Wcol:[H,D]W_{\mathrm{col}}:[H,D] has one row per output neuron. Multiplication produces Wcolx:[H,1]W_{\mathrm{col}}x:[H,1]. For the first sample,

x0=[12],Wcol=[1−121/2].x_0=\begin{bmatrix}1\\2\end{bmatrix},\qquad W_{\mathrm{col}}=\begin{bmatrix}1&-1\\2&1/2\end{bmatrix}.

The suffix “col” identifies the convention of applying these weights to column samples; it does not mean every weight is a column vector. The matrix still has output neurons as rows. Naming that distinction avoids an easy but persistent orientation mistake.

Make the batch conversion explicit

For a batch, we arrange samples as rows:

X=[1234]:[B,D]=[2,2].X=\begin{bmatrix}1&2\\3&4\end{bmatrix}:[B,D]=[2,2].

To preserve exactly the same neuron equations, transpose the weights:

Wrow=WcolT=[12−11/2]:[D,H].W_{\mathrm{row}}=W_{\mathrm{col}}^\mathsf T =\begin{bmatrix}1&2\\-1&1/2\end{bmatrix}:[D,H].

A transpose swaps row and column indices. It does not train, rescale or otherwise change the parameter values. The entry at output-neuron row hh, input-feature column dd becomes the entry at row dd, column hh. Our weights are intentionally nonsymmetric so the transpose visibly moves entries even when both dimensions equal two.

The batched formula is XWrow:[B,H]XW_{\mathrm{row}}:[B,H]. The middle dimensions must match: D=WinD=\mathrm{Win}. The input-feature index is summed away, while sample and output-feature indices survive. If you cannot name the summed axis, a familiar-looking matrix product may still be the wrong operation.

The parameter values are shared across samples. Changing a weight makes every sample use the new coefficient, but each sample keeps its own input row and resulting output row. Sharing parameters therefore differs from mixing samples.

What the dimension controls actually construct

The complete authored input array is [[x00,2],[3,4]][[x00,2],[3,4]], and the complete authored column-weight array is [[w00,−1],[2,1/2]][[w00,-1],[2,1/2]]. Defaults are x00=w00=1x00=w00=1. A dimension of one takes the leading row or column; a dimension of two retains both. This slicing rule defines the toy data rather than pretending that arbitrary new dimensions create arbitrary new examples.

For instance, choosing B=1B=1 retains only the first sample. Choosing D=Win=1D=\mathrm{Win}=1 retains only each neuron’s first input coefficient and each sample’s first feature. It does not average the removed feature into the retained one. Choosing H=1H=1 keeps the first output neuron and requires a one-entry bias column.

Every declared dimension must be an integer from the offered choices. Fractional or mismatched dimensions have no supported matrix interpretation here. The scalar coefficient controls must also be finite and bounded; invalid values produce a visible unavailable result before arithmetic begins.

Bias is a named broadcast

A bias is an additive parameter for each output neuron. The column convention uses

b=[1/2−1/2]:[H,1].b=\begin{bmatrix}1/2\\-1/2\end{bmatrix}:[H,1].

A broadcast explicitly copies values along a declared axis. To add biases to the row batch, we construct

bbatch=[1/2−1/21/2−1/2]:[B,H].b_{\mathrm{batch}}=\begin{bmatrix}1/2&-1/2\\1/2&-1/2\end{bmatrix}:[B,H].

Each sample row receives the same output-specific biases. There is no new bias parameter for each sample: the repeated values are copies of shared parameters. The biasRows control describes the original bias column and must equal HH. A bias column with the wrong number of entries is rejected rather than accidentally expanded by a library’s general broadcasting rules.

The full operation is now Z=XWrow+bbatchZ=XW_{\mathrm{row}}+b_{\mathrm{batch}}. Both terms being added have shape [B,H][B,H]. Addition is therefore elementwise between named matching entries, not an unexplained shape trick.

Work every default output

For sample zero, output zero uses the first neuron row (1,−1)(1,-1):

1⋅1=1,2⋅(−1)=−2,1+(−2)=−1,−1+12=−12.1\cdot1=1,\quad 2\cdot(-1)=-2,\quad 1+(-2)=-1,\quad -1+\frac12=-\frac12.

Output one uses (2,1/2)(2,1/2):

1⋅2=2,2⋅12=1,2+1=3,3−12=52.1\cdot2=2,\quad 2\cdot\frac12=1,\quad 2+1=3,\quad 3-\frac12=\frac52.

For sample one, the first neuron gives 3⋅1+4⋅(−1)+1/2=−1/23\cdot1+4\cdot(-1)+1/2=-1/2. The second gives 3⋅2+4⋅(1/2)−1/2=15/23\cdot2+4\cdot(1/2)-1/2=15/2. Thus

Z=[−1/25/2−1/215/2].Z=\begin{bmatrix}-1/2&5/2\\-1/2&15/2\end{bmatrix}.

The two equal first-column values are a consequence of these particular inputs and coefficients, not evidence that samples were merged. The trace shows each feature product, running partial sum and final bias addition separately. Bias is added once after each completed dot product, rather than once per feature.

Read the loop as an equation

The reference follows sample index, then output index, then input-feature index. The innermost loop multiplies one input by its matching weight and adds it to a partial sum initialized at zero. After completing the features, it adds the copied bias. This ordering makes both the index semantics and binary64 accumulation order inspectable.

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-02: explicit transpose, ordered products, and declared bias broadcasting."""
import numpy as np
from reference import NumericalFault, validate, choice, finite, guarded, tensor, step, result, run

DEFAULT_IV02 = {"B": 2, "D": 2, "H": 2, "Win": 2, "biasRows": 2, "x00": 1, "w00": 1, "bias0": 0.5}


@guarded
def derive_iv02(state):
    """Dimensions select leading slices, never silently repair incompatible shapes."""
    dims = ["B", "D", "H", "Win", "biasRows"]
    s = validate(state, DEFAULT_IV02, {key: (1, 2) for key in dims})
    for key in dims:
        choice(s[key], [1, 2], key)
    B, D, H, Win, biasRows = (int(s[key]) for key in dims)
    if D != Win:
        raise NumericalFault("SHAPE_MISMATCH", "D must equal Win.")
    if biasRows != H:
        raise NumericalFault("SHAPE_MISMATCH", "biasRows must equal H.")
    X = np.array([[s["x00"], 2], [3, 4]], dtype=np.float64)[:B, :D]
    Wcol = np.array([[s["w00"], -1], [2, 0.5]], dtype=np.float64)[:H, :Win]
    Wrow = Wcol.T.copy()  # Declared conversion from column-neuron weights.
    b = np.array([s["bias0"], -0.5], dtype=np.float64)[:biasRows]
    biasBatch = np.empty((B, H), dtype=np.float64)
    for sample in range(B):
        for h in range(H):
            biasBatch[sample, h] = b[h]  # Explicit named sample-axis broadcast.
    steps = [
        step("shapes", "Validate matrix dimensions", "X[B,D] * W_row[Win,H], with D=Win and biasRows=H", "Leading slices of authored arrays.", {key: s[key] for key in dims}, {"outputRows": B, "outputColumns": H}),
        step("transpose", "Explicitly transpose column weights", "W_row[d,h]=W_col[h,d]", "Orientation changes, parameter values do not.", {"H": H, "Win": Win}, {f"entry{i}": value for i, value in enumerate(Wrow.ravel())}),
        step("broadcast", "Explicitly broadcast the bias", "bias_batch[sample,h]=b[h,0]", "Copy biases into every sample row.", {f"bias{i}": value for i, value in enumerate(b)}, {f"entry{i}": value for i, value in enumerate(biasBatch.ravel())}),
    ]
    Z = np.empty((B, H), dtype=np.float64)
    for sample in range(B):
        for h in range(H):
            total = np.float64(0)
            for d in range(D):
                inputValue, weight = X[sample, d], Wrow[d, h]
                product = finite(inputValue * weight, "affine product")
                priorSum = total
                total = finite(priorSum + product, "affine partial sum")
                steps.append(step(f"dot-{sample}-{h}-{d}", f"Sample {sample}, output {h}, feature {d}", "sum=priorSum+input*weight", "Feature-index order, before bias.", {"input": inputValue, "weight": weight, "priorSum": priorSum}, {"product": product, "sum": total}))
            bias = biasBatch[sample, h]
            value = finite(total + bias, "biased output")
            Z[sample, h] = value
            steps.append(step(f"bias-{sample}-{h}", f"Add bias: sample {sample}, output {h}", "value=sum+bias_batch[sample,h]", "Add one bias after the dot product.", {"sum": total, "bias": bias}, {"value": value}))
    tensors = [tensor("X", [B, D], ["sample", "input_feature"], X.ravel(), "Leading slice of authored inputs."),
               tensor("W_col", [H, Win], ["output_feature", "input_feature"], Wcol.ravel(), "Authored column weights."),
               tensor("W_row", [Win, H], ["input_feature", "output_feature"], Wrow.ravel(), "Explicit transpose."),
               tensor("b", [biasRows, 1], ["output_feature", "column"], b, "Authored bias column."),
               tensor("bias_batch", [B, H], ["sample", "output_feature"], biasBatch.ravel(), "Explicit sample-axis broadcast."),
               tensor("Z", [B, H], ["sample", "output_feature"], Z.ravel(), "Ordered dot products, then bias.")]
    return result(tensors, steps, {"z00": Z[0, 0], "outputRows": B, "outputColumns": H, "featureCount": D})


if __name__ == "__main__":
    run(derive_iv02, DEFAULT_IV02)

NumPy stores the authored arrays and makes the transpose explicit, but the dot products are scalar loops rather than a hidden matrix call. The helper source supplies validation and JSON records only. Keep it beside the chapter script for the later default/full-state JSON CLI; no execution evidence is implied by showing source.

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

Row-major storage lists each row’s entries before moving to the next row. That flat storage order is not a new mathematical orientation. The inspector always retains the shape and named axes so that a list of four numbers cannot silently stand for several incompatible matrices.

Common mistakes and a useful next question

A square matrix can hide a transpose mistake because its shape stays unchanged. A scalar bias may seem convenient, but this lesson’s contract requires one declared bias per output, even when the chosen biases happen to be equal. A batch dimension is also not a feature dimension: varying BB changes how many examples are evaluated, while varying DD changes what measurements each neuron reads.

Use the five lab questions to check axis meanings, the output shape, a real computed entry, the transpose, and an illegal contraction. Revisit matrix–vector multiplication and samples, features and targets when either interpretation feels uncertain.

  • Column samples and row batches describe the same examples after an explicit conversion.
  • Matching contracted dimensions make multiplication legal.
  • Transposes and bias broadcasts must name what changes and what stays shared.
  • Products, partial sums and bias additions explain each output entry.

So far the calculation is affine: a weighted sum plus bias. The next chapter adds nonlinear activations and asks how their outputs respond to small changes in those sums.