Skip to the workspace
Pebellslearn by building
Linear Algebra  ›  Lesson

Scalars, Vectors and Tensors

Scalars, Vectors, Tensors 12 minScalars, vectors, matrices and tensors are numbers arranged with zero, one, two or more indexes, and a shape says how many of each.

machine learning / Scalars, Vectors and Tensors

Explore each scene at your own pace.

01 · The rule

The rule

Scalars, Vectors and Tensors

To you, flat B is "a two-room flat near the metro". To a model it is just [60, 2, 1]. Everything a model sees, from one rent to a year of photos, is numbers arranged in a grid of some number of dimensions. Naming those arrangements correctly is the first step to reading any ML code.

The rule

Count the indexes you need: 0 scalar, 1 vector, 2 matrix, more tensor.

An index is a position you must give to pick out one number.

  • Scalar: a single number, no index needed. Flat B's rent, 22.
  • Vector: a list, one index. Flat B's features, [60, 2, 1]: size, rooms, metro km. Its third entry is 1.
  • Matrix: a table, two indexes (row, column). All five flats, one row each.
  • Tensor: three or more indexes. The same table for 12 months needs month, flat and feature.

Deep-learning libraries such as PyTorch and TensorFlow call every one of these a tensor, including scalars and vectors, because their code treats them all the same way.

A shape lists how many positions each index has. The number of indexes is the rank (NumPy calls it ndim).

import numpy as np
rent_b = np.array(22)                     # shape ()      scalar
flat_b = np.array([60, 2, 1])             # shape (3,)    vector
X = np.array([[40, 1, 2],
              [60, 2, 1],
              [80, 3, 3],
              [50, 2, 4],
              [70, 2, 1]])                # shape (5, 3)  matrix

The workhorse operation on vectors is the dot product: multiply matching entries and add. With weights w = [0.3, 1, -1], flat B scores 0.3×60+1×2+(−1)×1=190.3 \times 60 + 1 \times 2 + (-1) \times 1 = 19. A linear model's prediction is exactly this: features dotted with weights. Two vectors can only be dotted if they have the same length.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.