Skip to content
Reading as a guest: this browser saves your progress. Create a free account and we’ll carry your progress over.

Foundations: Tensors & Data

Mission Map
SECTOR foundations, MISSION 3, Field repair: broken code first, 22 min, 1 exercise

Basic Tensor Operations

Which readings contribute to one repaired output?

Trace the repaired feed

Use sensors A and B from Demir's three-moment excerpt. Average the selected rows, apply the gain, then follow one channel-bank sum.

These are selections from the fictional recording used in Tensor Shapes. The header supplies sensor order A, B. Moment numbers are local to that excerpt. No physical unit was supplied. Gains and bank weights are dimensionless settings chosen for this calculation. This diagram calculates the shown example, not the full recording.

Experiment controls

Pair moments 1 and 2, then moments 2 and 3. Both views keep sensor A before sensor B.

2
0
0

Current inputs

Opening recording, sensors A and BFictional recording

Selection
Pair moments 1 and 2, then moments 2 and 3. Both views keep sensor A before sensor B.
Order
Moment first, then sensor A before sensor B. A reused reference row keeps that order.
Units
The recording supplies no physical unit. Gains and blend weights are dimensionless.
First view [2, 2]: rows are moments 1 and 2, columns are A and B
  1. 2Selected
  2. 20
  3. 3
  4. 18

Make a prediction, or run the experiment to see the result.

Choose your inputs, then run the experiment.

Your result will appear here. After two runs, you can compare what changed.

Inspect the reference example

Keep sensors A and B aligned while averaging 's selected moments. Apply gain, then inspect one bank's weighted sum.

Pass 1: three readings, two channels

210412614

Boosted average: [3, 2]

6188201022
2
Add [4, 8] to each row, then divide each sum by 2. The averages are [3, 9], [4, 10], [5, 11]. Gain 2 scales that average without changing channel order.
const merged = pass1.add(pass2).div(2);
const boosted = merged.mul(2);

Element-wise operations keep matching sensor positions. Broadcasting reuses one row. Matrix multiplication adds the channel contributions for each bank.

JavaScript simulation with fixed practice data. It does not run or train the lesson's models. Your challenge uses its own data and tests.

At the start of the shift, 's amplifier has stopped with this error: Error in matMul: inner shapes (64) and (1) of Tensors with shapes 1,64 and 1,64 and transposeA=false and transposeB=false must match. All sixty-four channels, one stream of readings per sensor, are waiting for the fix.

The hull array takes 983 thousand raw samples a minute before integration boils them down to readings. Whatever that red text is, it is not keeping up. Show me which readings go into each result before you send another hour to this console.

Restore the feed to 's console. First check the calculation on the recording just arranged: average neighboring moments for each sensor, apply the gain, then combine channels into a few weighted sums. The full 64-channel recording stays in the archive while you trace this excerpt.

Matching sensors across neighboring moments

wanted to multiply each reading by its matching gain, the number that controls how much to amplify it. That is element-wise multiplication, written mul. He used matMul instead. has a different rule, and [1, 64] times [1, 64] does not meet it.

reopens the three moments checked. He keeps sensors A and B in the order listed in the recording header, leaving C and D aside for now. points to the first two rows and waits for the calculation.

The earlier excerpt contains these values:

Local momentSensor ASensor B
1220
2318
3416

These are fictional recorded readings from the same selection used in Shapes. The header gives their order. It supplies no physical unit here, so we keep them as readings without adding one.

makes two overlapping views. The first holds moments 1 and 2. The second holds moments 2 and 3. Matching positions now pair the same sensor at neighboring moments. Averaging each pair smooths this short . It also changes the readings, so the raw recording stays available.

merge-two-passes.tstypescript
// Columns stay in header order: sensor A, then sensor B.
const pass1 = tf.tensor2d([[2, 20], [3, 18]]); // moments 1 and 2
const pass2 = tf.tensor2d([[3, 18], [4, 16]]); // moments 2 and 3
const gain = 2;

const { merged, boosted } = tf.tidy(() => {
const merged = pass1.add(pass2).div(2);
const boosted = merged.mul(gain);
return { merged, boosted };
});
console.log(merged.arraySync());  // [[2.5, 19], [3.5, 17]]
console.log(boosted.arraySync()); // [[5, 38], [7, 34]]
// Keep these tensors for the bank calculation below.

Follow sensor A through the first pair: (2 + 3) / 2 = 2.5. Gain 2 gives 5. Sensor B uses (20 + 18) / 2, then the same gain. The gain is a dimensionless setting chosen for this example. Doubling a value also doubles any error in it. This example establishes no noise reduction from independent repeated measurements.

Each operation creates a tensor. tf.tidy() releases temporary tensors when its synchronous callback finishes. That callback must finish without await. TensorFlow.js keeps the tensors in the returned object, so you can use boosted in the next calculation and dispose of both results afterward.

One channel-bank sum

also wants to inspect channels together. A bank is one supplied set of channel . Bank 0 keeps A, Bank 1 keeps B, and Bank 2 adds A and B. These fixed settings help you check the calculation. They make no claim about which sensors detect an .

Matrix multiplication computes a dot product for each output: multiply each channel by its weight, then add the products. The first boosted row is [5, 38]. Bank 2 uses [1, 1], so its score is 5 * 1 + 38 * 1 = 43. Element-wise mul produces the separate products. matMul also sums them.

TensorRow meaningColumn meaningShape
boostedNeighboring-moment pairSensor A, B[2, 2]
mixBank 0, 1, 2Sensor A, B[3, 2]
mix.transpose()Sensor A, BBank 0, 1, 2[2, 3]
mixedNeighboring-moment pairBank 0, 1, 2[2, 3]

Transpose puts each bank's weights in a column. The multiplication then has matching sensor axes: [2, 2] times [2, 3] produces [2, 3].

weighted-channel-mix.tstypescript
// Continue with boosted from merge-two-passes.ts.
const mix = tf.tensor2d([[1, 0], [0, 1], [1, 1]]);
const mixed = tf.tidy(() => boosted.matMul(mix.transpose()));
console.log(mixed.arraySync()); // [[5, 38, 43], [7, 34, 41]]

tf.dispose([pass1, pass2, merged, boosted, mix, mixed]);

In the activity, select Channel-bank sums, then choose an output row and column. The highlighted sensor values and weights show every contributor to that score. Check their meanings as well as their counts. The general matrix rule is [m, n] times [n, p] produces [m, p], where the shared n counts the values in each dot product.

Broadcasting one reference row

keeps the first moment beside the chart as a fixed reference. He checks what the same merge function does when he reuses that row for both outputs.

This case blends each row with the first moment. It is a chosen comparison, not another capture of those moments. The reference has shape [2]: A's reading 2, then B's reading 20.

broadcast-recording-reference.tstypescript
const earlier = tf.tensor2d([[2, 20], [3, 18]]); // moments 1 and 2
const reference = tf.tensor1d([2, 20]); // moment 1, reused
const blended = tf.tidy(() => earlier.add(reference).div(2));
console.log(blended.arraySync()); // [[2, 20], [2.5, 19]]
tf.dispose([earlier, reference, blended]);

lets that one row apply to both rows. TensorFlow.js compares shapes from right to left. Each pair of sizes must match, or one must be 1. A missing leading axis acts like size 1. Here, [2] matches the last axis of [2, 2]. The result keeps shape [2, 2].

Select Fixed first-moment reference in the activity. Trace sensor B in the second output row: (18 + 20) / 2 = 19 at gain 1. The same reference value reaches each row, while A and B keep their own columns. A scalar gain has one value and applies to every result.

Optional: the full amplifier and extra matrix examples

The shape error

Here is the code that produced the error. wanted to multiply each of the 64 readings by its own gain factor.

amplify-broken.tstypescript
import * as tf from '@tensorflow/tfjs';

// channelGains: 64 amplification factors. latestReadings: 64 raw values.
const gains = tf.tensor2d([channelGains]);      // shape [1, 64]
const readings = tf.tensor2d([latestReadings]); // shape [1, 64]

// BROKEN: this operation requires matching inner dimensions.
const amplified = gains.matMul(readings);
// Error in matMul: inner shapes (64) and (1) of Tensors with
// shapes 1,64 and 1,64 and transposeA=false and transposeB=false
// must match.

matMul needs the left tensor's column count to match the right tensor's row count. Here those counts are 64 and 1. only wanted to multiply matching positions, so he needs mul instead.

Extra element-wise operations

The short arrays below are separate toy inputs for comparing addition, subtraction, and multiplication. They do not come from the recording.

JavaScript

Array.map()
arr.map((x, i) => x + arr2[i])

Machine Learning

tf.add()
tf.add(tensor1, tensor2)
Structural Bridge
Where the analogy ends
Array.map calls a JavaScript function for each value. tf.add sends the calculation to a backend, the engine TensorFlow.js uses to run it. That engine can use the CPU or GPU. Small calculations may still be faster in plain JavaScript.

When you write arr.map((x, i) => x + arr2[i]), you're doing element-wise addition. tf.mul, tf.add, and tf.sub do the same kind of calculation on tensors. Their shapes must follow the broadcasting rules. gains.mul(readings) is the one-word fix for the broken amplifier:

tensor-ops.tstypescript
import * as tf from '@tensorflow/tfjs';

// The amplifier from amplify-broken.ts, repaired: matching positions,
// so matMul's inner-dimension rule does not apply. The shapes still
// have to be broadcast-compatible.
const amplified = gains.mul(readings);    // [1, 64], gain[i] * reading[i]

const sensor1 = tf.tensor([1, 2, 3]);
const sensor2 = tf.tensor([4, 5, 6]);

// Element-wise operations: same as map + zip
const sum = tf.add(sensor1, sensor2);     // [5, 7, 9]
const product = tf.mul(sensor1, sensor2); // [4, 10, 18]
const diff = tf.sub(sensor2, sensor1);    // [3, 3, 3]

// Chaining with method syntax
const result = tf.tidy(() => sensor1.add(sensor2).mul(2));
// [10, 14, 18]
tf.dispose([amplified, gains, readings, sensor1, sensor2, sum, product, diff, result]);

Broadcasting compares shapes from right to left. Each pair of sizes must match, or one must be 1. A missing leading axis also acts like size 1.

For example, .mul(tf.scalar(2)) doubles every value. Subtracting two column means, shape [2], from five rows, shape [5, 2], subtracts the same pair from each row. A size mismatch that meets this rule is valid for an element-wise operation. Matrix multiplication follows its own rule.

Tensor operations are not automatically faster than JavaScript loops. Call overhead and readback can dominate a small array. Acceleration depends on the workload and backend. Measure the version you intend to run. This lesson checks shape rules. You would need runtime measurements to compare speed.

A matrix example with three inputs

This separate toy example uses three inputs and two outputs to make the inner-dimension rule visible with different sizes.

Dense layers compute weighted sums. matMul computes them for every row of its left input against every column of its right input. Element-wise multiplication alone leaves the products unsummed. The matrix operation has a shape rule:

[m, n] times [n, p] produces [m, p]: the inner dimensions must match.

The left tensor's column count must equal the right tensor's row count. If a matrix stores the intended axes in the opposite order, transpose it. A shape error can also mean missing features or an incorrect layout. Transposing until code runs can silently change the computation. Here, rows and columns need to swap:

matmul.tstypescript
// weights: [3, 2], input: [3, 1]
const weights = tf.tensor2d([[1, 2], [3, 4], [5, 6]]);  // [3, 2]
const input = tf.tensor2d([[1], [1], [1]]);               // [3, 1]

// weights.matMul(input) would throw:
//   [3, 2] × [3, 1]: inner dims 2 ≠ 3. No deal.

// transpose() flips [3, 2] to [2, 3]. Now the rule is satisfied:
//   [2, 3] × [3, 1] to [2, 1] ✓
const output = tf.tidy(() => weights.transpose().matMul(input));
output.print();
// [[9],: 1+3+5: first column of weights, summed against input
//  [12]]: 2+4+6: second column
tf.dispose([weights, input, output]);

A dense layer, which you will build next, starts with matMul(input, weights) + bias. The same shape rule will help you check its inputs and weights. The time-based models in module 6 use it too.

Challenge

Help write the reusable functions behind those calculations. The challenge supplies separate diagnostic inputs with varied values and shapes, including a [3, 2] block paired with one [2] row. These are test cases for your code, rather than excerpts of the 64-channel recording.

Return both the average and the amplified result from mergePasses. Return one per reading and bank from mixChannels. The result tables show your function's outputs for the supplied cases. Check the numbers as well as the shapes before uses the functions on the full recording.