Commander MirzaWe're picking up a structured data stream from Sector 7-G. ARIA can't parse it with her rule-based systems. We need someone who can think in data structures.
ARIAThe stream contains numerical sequences, Commander. My pattern matching is insufficient. I need a new way to represent this data.
You've worked with arrays your entire career as a frontend developer. Arrays of DOM elements, arrays of API responses, arrays of pixel data. What if I told you that the leap from JavaScript arrays to machine learning tensors is smaller than you think?
A tensor is simply a multi-dimensional array. That's it. If you can work with arrays in JavaScript, you already understand the core concept.
const arr = new Float32Array([1, 2, 3])const t = tf.tensor([1, 2, 3])Here's the key insight: Float32Array in JavaScript and tf.tensor in TensorFlow.js both store numbers in contiguous memory. The difference is that tensors know their shape and come with GPU-accelerated math operations.
import * as tf from '@tensorflow/tfjs';
// A scalar (0D tensor) — just a single number
const scalar = tf.scalar(42);
console.log(scalar.rank); // 0
// A vector (1D tensor) — like a regular array
const vector = tf.tensor1d([1, 2, 3, 4, 5]);
console.log(vector.rank); // 1
// A matrix (2D tensor) — like an array of arrays
const matrix = tf.tensor2d([[1, 2], [3, 4], [5, 6]]);
console.log(matrix.rank); // 2
// You can always get the data back as a JavaScript array
const jsArray = await vector.array();
console.log(jsArray); // [1, 2, 3, 4, 5]Think of it like this: you already use HTMLElement[] to represent a list of DOM nodes. A tensor is just a more powerful version of that — a typed, n-dimensional array with built-in math.
Now it's your turn. Create your first tensor from a JavaScript array.
Create a 1D tensor containing the values [1, 2, 3, 4, 5] using TensorFlow.js.
// Create a tensor with values 1 through 5 const tensor = null; // your code here
The signal begins to take shape as structured data.
Next: understanding tensor shapes