← Math
Math

Matrices as transformations

Why did the receipt land in primary?

Interpret a model’s weights as a transformation before trusting its exported layout.

Outcome

Read y = Wx + b as one row per output, read an exported kernel in the layout it was stored in, and score a whole batch as one matrix product.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Dense layer Also affine layer
y = Wx + b: every output is a weighted sum of every input plus a bias.
Weight matrix
W with one row per output and one column per input in the y = Wx + b convention.
Kernel
The weights as a training framework stores them; Keras stores a Dense kernel as [input][output], the transpose of W.
Row-major
A flat layout where each row’s entries sit next to each other, so entry (r, c) is at r × columns + c.
Probe
An input whose correct outputs are known, used to check that an exported model computes what training did.

Why this matters

The dense layer here applies an affine transformation, Wx + b, to every input vector. Models are trained in one framework and served by another, and the weights cross that boundary as a flat list of numbers. Whether row 0 means the first output or the first input is a convention, and getting it backwards produces a model that runs, passes its shape checks and gives wrong answers.

This lesson assumes vectors and dot products.

What a dense layer computes

A matrix arranges numbers in rows and columns. The input vector supplies one value for each feature. Each output is a weighted sum of all the inputs plus its own bias. Write the weights as a matrix W with one row per output, and the layer is y = Wx + b: row o dotted with x, plus b[o].

The matrix product Wx is a linear transformation; adding b makes this layer affine. The bias offsets each output independently of the input. A flat export must preserve which weight connects each input to each output, as well as the number of values.

01A layer is y = Wx + b

A layer is y = Wx + b

An email client sorts mail on the device into primary, updates and promotions with a small dense layer. The layer was trained in one framework and is served by code in the app. After the latest export, a receipt lands in primary and a message from a contact lands in promotions. Every shape check passes.

To separate the arithmetic from the three-class inbox model, use a two-input, two-output probe. With W = [[1, 2], [−1, 1]], b = [0.5, −0.5] and a probe email x = [2, 1], the scores are [1 × 2 + 2 × 1 + 0.5, −1 × 2 + 1 × 1 − 0.5] = [4.5, −1.5]. Features and scores are dimensionless in this worked model; the bias must have the same scale as its output’s weighted sum.

02Rows, columns and the exported kernel

Rows, columns and the exported kernel

The Keras-style exporter stores this kernel [input][output]: the weight from input i to output o sits at kernel[i × outputs + o]. For this layer that is [1, −1, 2, 1]. Predict both lines.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Exported by training as [input][output]: kernel[i * outputs + o] is the weight from input i to output o.
const kernel = [1, -1, 2, 1];
const bias = [0.5, -0.5];
const probe = [2, 1]; // a probe email whose scores we know: [4.5, -1.5]

const asRows = [kernel.slice(0, 2), kernel.slice(2, 4)]; // what the runtime did
const asStored = [
  [kernel[0]!, kernel[2]!],
  [kernel[1]!, kernel[3]!]
]; // one row per output

const score = (w: number[][]) =>
  w.map((row, o) => row[0]! * probe[0]! + row[1]! * probe[1]! + bias[o]!);

console.log(score(asRows).join(" "));
console.log(score(asStored).join(" "));
Where each weight lives in the exported kernel
kernel[ ]ValueWeight
01input 0 → output 0, W[0][0]
1−1input 0 → output 1, W[1][0]
22input 1 → output 0, W[0][1]
31input 1 → output 1, W[1][1]

TensorFlow.js stores a dense layer’s kernel with shape [inputs, units], the [input][output] layout; typed arrays are flat, so the index arithmetic is yours.

03Why the shape check passed

Why the shape check passed

Reading the kernel as rows gives [[1, −1], [2, 1]], which is Wᵀ. For a 2 × 2 layer, W and Wᵀ have the same shape, so a check that the matrix is 2 × 2 passes. The scores come out as [1.5, 4.5]: the largest score moves from output 0 to output 1. If a shaped matrix were transposed, a rectangular shape check could catch it. But this app reshapes a flat buffer to the expected dimensions: even twelve wrongly ordered numbers fill a 3 × 4 matrix. A length or shape check cannot establish that each entry still belongs to the right feature and class.

The inbox layer has 3 outputs and 4 inputs. Would reading its kernel as rows pass a shape check?

04A batch is one matrix product

A batch is one matrix product

To sort a whole inbox at once, stack the emails as the rows of X. Then the scores are Y = XK + b, where K is the kernel as stored, and b is added to every row. Each email’s class is the column of its largest score. Here K = Wᵀ has shape n × m, so a k × n inbox batch produces k × m scores. For each email, start each class score from its own bias. Pick the first class with the largest score, keeping the first on a tie. The lab uses four dimensionless features in this order: link count, sender-in-contacts indicator, unsubscribe-header indicator and receipt-word count.

05Probe before you ship

Probe before you ship

Use a probe that distinguishes the layouts: the reduced [2, 1] input does, while a zero input tests only the bias. A few probes establish agreement on those inputs, not that the model is accurate or that every possible input is correct. For the inbox model, the receipt features [1, 0, 0, 1] should score [0.700, 1.100, 0.950] and select updates. The misread buffer scores [2.300, 0.200, 1.650] and selects primary. That is the receipt failure the importer must prevent.

06Ship the inbox classifier

Ship the inbox classifier

Repair one email’s scores, then decode the export’s layout. The batch task adds the release decision: verify the training probe before using those weights to sort mail. A fixed batch index alone is insufficient when the loaded weights or feature order do not reproduce training.

An on-device inbox classifier

Score one email, decode the kernel, then verify the export before sorting a batch.

  1. easy · M-MATRICES-V4-1 Score one email
  2. medium · M-MATRICES-V4-2 Read the exported kernel
  3. hard · M-MATRICES-V4-3 Sort a batch
In the frontend A probe-checked layer in Next.js and Svelte Optional

A web client can run the same layer: load the kernel and bias as JSON, score with the stored layout, and refuse the model if its probe scores do not match.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Run the exported layer in the browser and refuse a transposed export at load time.
type Exported = {
  kernel: number[];
  bias: number[];
  labels: string[];
  probe: { input: number[]; scores: number[] };
};

function scores(model: Exported, x: number[]): number[] {
  const m = model.bias.length;

  return model.bias.map((b, o) =>
    x.reduce((sum, v, i) => sum + v * model.kernel[i * m + o]!, b)
  ); // kernel stored [input][output]
}

export async function loadClassifier(url: string) {
  const model: Exported = await fetch(url).then((r) => r.json());
  const got = scores(model, model.probe.input);

  if (got.some((s, o) => Math.abs(s - model.probe.scores[o]!) > 1e-3))
    throw new Error("Exported layer fails its probe");

  return (x: number[]) => {
    const y = scores(model, x);

    return model.labels[y.indexOf(Math.max(...y))]!;
  };
}

Check this idea later
A kernel is stored [input][output] for 3 inputs and 3 outputs. Where is the weight from input 2 to output 1?
Why can a transposed square layer pass a shape check?
Sources

Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The inbox classifier is a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.