Gradient LabStart the lesson

Lessons › Chapter 2: Math toolkit

Dot products and matrices

Take two vectors of the same length: a = [2, 1, 3] and b = [1, 2, 1]. The dot product turns them into one number.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Scoring everyone at once

Leo needs to weigh every customer’s numbers and add them up, for thousands of customers at once.

Concept

Two vectors

Take two vectors of the same length: a = [2, 1, 3] and b = [1, 2, 1]. The dot product turns them into one number.

Build

Multiply matching pairs

Multiply the first with the first, second with the second, and so on: 2×1, 1×2, 3×1.

Build

Then add them up

Stack the products: 2 + 2 + 3 = 7. That is a · b. Weighted sums like this are the basic move inside almost every model.

Insight

Dot product measures similarity

Arrows pointing the same way give a large dot product. Perpendicular arrows give 0. Recommenders and search engines use this to ask “how alike are these two things?”

Concept

A matrix is a grid of numbers

Stack vectors as rows and you get a matrix. This W has 2 rows and 3 columns, a 2 × 3 matrix.

Build

Matrix times vector

W @ x dots each row with x. Row 1 · x = 1×2 + 0×1 + 2×3 = 8. Row 2 · x = 0×2 + 1×1 + 1×3 = 4. The result is a new vector [8, 4].

A neural-network layer is exactly this, plus a bias and an activation. You will see it again.

Real life

In real life: “Because you watched…”

Streaming services describe you and every film with a taste vector (how much action, comedy, romance…). The dot product of your vector with a film’s vector is a match score. The highest scores fill your home screen.

Quick check: What is [1, 2] · [3, 4]?

1×3 + 2×4 = 3 + 8 = 11. A dot product always gives a single number.

Pseudocode

a = [2, 1, 3]
b = [1, 2, 1]
dot(a, b) = 2×1 + 1×2 + 3×1 = 7

W = [[1, 0, 2],      # row 1
     [0, 1, 1]]      # row 2
x = [2, 1, 3]
W × x = [row 1 · x, row 2 · x] = [8, 4]
layer = W × x + bias    # one neural-network layer

Key terms

dot product
Multiply matching numbers in two lists and add them up. Big means “similar”.
matrix
A grid of numbers, made of rows and columns.