Skip to content

AIPrimer A03Before Day 7

Vectors and Dot Products

8 min read · outside the 100 days

From Day 7 on, one row of a table is a vector, and almost every model starts by multiplying it by a list of weights. Four moves cover what the course needs: the dot product, length, cosine similarity, and many dot products at once.

Read before: Day 7 · about 20 minutes

A vector is a list of numbers

A vector is an ordered list of numbers. Order matters: each position always means the same thing. One bike-share hour at 25 °C and 60% humidity is the vector (25, 60), with temperature first. The number of entries is the vector's size; it's also called the number of dimensions.

Two vectors of the same size add entry by entry. A number times a vector scales every entry.

  • (25, 60) + (5, −10) = (30, 50)
  • 2 × (25, 60) = (50, 120)
  • The average of (2, 1) and (4, 1) is (6, 2) ÷ 2 = (3, 1). Day 40 averages word vectors this way: (2, 1) is "won" and (4, 1) is "cash".

A NumPy array does all of this with plain +, * and /.

# script_id: primer_a03/vectors
import numpy as np

a = np.array([25, 60])                  # temperature °C, humidity %
b = np.array([5, -10])
print("a + b   =", a + b)
print("2 * a   =", 2 * a)

won, cash = np.array([2, 1]), np.array([4, 1])
print("average =", (won + cash) / 2)
print("size    =", a.shape)
a + b   = [30 50]
2 * a   = [ 50 120]
average = [3. 1.]
size    = (2,)

a.shape is (2,): one axis with 2 entries.

The dot product

The dot product of two vectors multiplies matching entries, then adds the products. The answer is one number. A shopping receipt is a dot product: 2 apples and 1 loaf, at 1.50 € and 3 € each, cost 2 × 1.5 + 1 × 3 = 6 €.

A model's weighted sum is the same thing. The features are the quantities, the weights are the prices, and the bias is a fixed amount added at the end, like a delivery fee.

w⋅x=w1x1+w2x2+⋯+wdxd\mathbf{w}\cdot\mathbf{x} = w_1 x_1 + w_2 x_2 + \dots + w_d x_d
Symbol Meaning
x\mathbf{x} the feature vector: one row's inputs (bold marks a vector)
w\mathbf{w} the weights, one per feature
dd the size of both vectors; they must match

Worked: w=(20,−3)\mathbf{w} = (20, -3) and x=(10,5)\mathbf{x} = (10, 5) give 20×10+(−3)×5=200−15=18520 \times 10 + (-3) \times 5 = 200 - 15 = 185. Add a bias of 40, and the prediction is 225.

# script_id: primer_a03/dot
import numpy as np

w = np.array([20, -3])
x = np.array([10, 5])
print("by hand:", 20 * 10 + (-3) * 5)
print("np.dot :", np.dot(w, x))
print("w @ x  :", w @ x)                # @ is the same dot product
print("w @ x + 40 =", w @ x + 40)       # add the bias
by hand: 185
np.dot : 185
w @ x  : 185
w @ x + 40 = 225

Find the prices from five receipts

Each weight says how much its feature counts; the bias b is the starting point. Move the sliders to bring the predictions close to the targets.

z = 1·Apples bought + 1·Loaves bought + 0

Every row
Apples boughtLoaves boughtz = ŷtarget y
2138
03311
42614
1013.5
33615.5

row 1: z = 3RMSE 7.064

Each receipt total (in €) is the dot product of what was bought and the prices, plus a delivery fee. The two weights are the prices and the bias is the fee. They start at 1, 1 and 0, with an RMSE (the typical miss) of about 7.06. Find the prices and the fee that bring it to 0.

Length and distance

A vector's length is the square root of its dot product with itself. For (3, 4), that's 3×3+4×4=25=5\sqrt{3 \times 3 + 4 \times 4} = \sqrt{25} = 5. The distance between two rows is the length of their difference. A distance of 0 means the two rows are identical.

Take the hours (25, 60) and (20, 90). The difference is (5, −30), so the distance is 25+900≈30.4\sqrt{25 + 900} \approx 30.4. The humidity gap supplies 900 of the 925, only because its numbers are bigger. Day 15's nearest neighbours and Day 17's k-means use this distance, and Day 16's margin uses the length of the weights. Day 9 shows why features are put on one scale first.

# script_id: primer_a03/length
import numpy as np

v = np.array([3, 4])
print("sqrt(v @ v)    =", np.sqrt(v @ v))
print("np.linalg.norm =", np.linalg.norm(v))

a, b = np.array([25, 60]), np.array([20, 90])
print("distance a to b =", np.linalg.norm(a - b).round(1))
sqrt(v @ v)    = 5.0
np.linalg.norm = 5.0
distance a to b = 30.4

Cosine similarity: direction only

A dot product grows when two vectors point the same way, but it also grows when they get longer. To compare direction alone, divide by both lengths. The result is the cosine similarity.

cos⁡(a,b)=a⋅b∥a∥ ∥b∥\cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a}\cdot\mathbf{b}}{\lVert \mathbf{a} \rVert \, \lVert \mathbf{b} \rVert}
Symbol Meaning
∥a∥\lVert \mathbf{a} \rVert the length of a\mathbf{a}
cos⁡\cos 1 means the same direction, 0 a right angle, −1 opposite directions

Worked: (2, 1) and (4, 1) give 8+15 17=99.22≈0.98\frac{8 + 1}{\sqrt{5}\,\sqrt{17}} = \frac{9}{9.22} \approx 0.98, nearly the same direction. (2, 1) and (4, 2) give exactly 1: the second is twice as long, but points the same way.

Day 40 uses cosine to find similar words. Day 41 meets a related catch: a dot product adds one product per entry, so vectors with more entries give more spread-out scores, and attention divides them back down.

# script_id: primer_a03/cosine
import numpy as np

def cosine(a, b):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))

won, cash, later = np.array([2, 1]), np.array([4, 1]), np.array([-2, 3])
print("won, cash   :", cosine(won, cash).round(2))
print("won, later  :", cosine(won, later).round(2))
print("dot, then doubled:", won @ cash, won @ (2 * cash))
print("cos, then doubled:", cosine(won, cash).round(2), cosine(won, 2 * cash).round(2))
won, cash   : 0.98
won, later  : -0.12
dot, then doubled: 9 18
cos, then doubled: 0.98 0.98

Doubling a vector doubles the dot product, but the cosine stays at 0.98. Won and later point slightly apart, so their cosine is just below 0.

Many dot products at once

Stack the rows of a table and you get a matrix: a grid of numbers with shape (rows, columns). A matrix times a vector, X @ w, takes the dot product of every row with w. You get one number per row.

  • Predictions (Day 7): 3 rows of 2 features times 2 weights gives 3 predictions.
  • A layer (Day 29): each neuron's weights form one row, so one product gives every neuron's sum.
  • Attention (Day 41): a query times the matrix of keys gives one score per key.

The sizes must line up. A (3, 2) matrix needs a vector of size 2; a vector of size 3 raises a ValueError, because some entries would have no partner. For the rows (10, 5), (20, 0) and (0, 10) with w=(20,−3)\mathbf{w} = (20, -3), the three sums are 185, 400 and −30.

# script_id: primer_a03/matrix
import numpy as np

X = np.array([[10, 5], [20, 0], [0, 10]])   # 3 rows, 2 features
w = np.array([20, -3])
print("X shape:", X.shape, " X @ w =", X @ w)

K = np.array([[0, 0, 1, 0], [2, 2, 0, 0], [1, 1, 0, 0]])   # keys: the, river, bank
q = np.array([1, 1, 0, 0])                                 # the query for "bank"
print("scores q @ K.T =", q @ K.T)
X shape: (3, 2)  X @ w = [185 400 -30]
scores q @ K.T = [0 4 2]

K.T is the transpose of K: rows turned into columns, so each key's entries line up with the query's. The scores 0, 4 and 2 are Day 41's.

Quick check

Quick check

1. What is (1, 2, 3) · (4, 0, −1)?

2. You double every entry of vector a. What happens to its cosine similarity with b?

3. X has 100 rows and 4 columns, and w has 4 entries. What does X @ w give?

Next

Go back to Day 7's weighted sum; the same moves return in Day 15's distances, Day 40's cosine and Day 41's attention scores.