A vector is a list of numbers that belong together, like a day's temperature and humidity, or every pixel of a picture. The same list can be read as a point, or as an arrow from the origin, and each view helps in a different way. Vectors are the language of machine learning: every example a model ever sees, and every set of weights it learns, is a vector. This lesson starts the biggest module of the section and brings in its two Python tools: NumPy, and PyTorch, the library most models are built with. By the end you'll read a vector three ways, store one as a NumPy array and as a PyTorch tensor, unroll a small picture into one, and know why a Python list and an array behave so differently when you add them.
What you'll be able to do
See a vector three ways: a list of numbers, a point, and an arrow
Name a vector's components and its dimension, and know that a moved arrow is the same vector
Make vectors with NumPy's np.array, read .shape, and know why a list isn't an array
Turn real data into vectors: a day as 2 numbers, a picture as 25, a word as an embedding
Make the same vectors as PyTorch tensors, and read their .shape and .dtype
Quick check
Have a guess before you start. An arrow goes from (0, 0) to (3, 2). Which of these is the same arrow, just drawn somewhere else?
From (1, 1) to (4, 3)
From (0, 0) to (2, 3)
From (3, 2) to (0, 0)
From (1, 1) to (3, 2)
Show the answer
From (1, 1) to (4, 3)
Both go 3 across and 2 up. A vector is a movement, so where it starts doesn't matter: only how far across and how far up.
The math: one object, three views
Purpose. Hold several numbers that belong together as one thing.
A vector is a list of numbers in order, written in brackets: v = (3, 2). Each number is a component, and the count of them is the dimension: (3, 2) is 2-dimensional, (1, 0, 4) is 3-dimensional. The same vector can be read three ways:
as a list: just the numbers, 3 then 2;
as a point: over 3, up 2, like lesson 41's coordinates;
as an arrow: from the origin to that point, with a length and a direction.
As an arrow, a vector is a movement, "3 across, 2 up". So the same arrow drawn from a different start is still the same vector.
Quick check
From lesson 41: how far is the point (3, 4) from the origin?
5
7
25
12
Show the answer
5
√(3² + 4²) = √25 = 5. Read as an arrow, that's the vector (3, 4)'s length, which lesson 49 calls its norm.
Try it now
Drag the arrow's tip. The list, the point and the arrow always show the same two numbers.
From a grid to a vector. Many things that look like grids become vectors by unrolling them. Take a tiny 5 × 5 picture of a trail sign, each pixel 0 (blank) or 1 (ink). Lay its rows end to end and the picture becomes a single list of 25 numbers: a 25-dimensional vector. Nothing is lost, as long as you remember the grid was 5 wide.
The picture. Watch it unroll. The flow draws the sign with its ink dark, under the empty row of 25 it unrolls into. Each step lights one row of the sign and the five places it fills, and the numbers along the top mark where each row starts. Above the code, a PyTorch tab beside the Python one shows the same line in PyTorch, the library this lesson's last part introduces.
Symbols and formula. Vectors are usually written in bold or with an arrow, and their components with subscripts:
v=(v1,v2,…,vn)∈Rn
In plain words: v is a list of n real numbers, v₁ first. That's lesson 28's ℝⁿ, now with a name.
So the unrolled sign is a vector in ℝ²⁵. A 3-dimensional vector can still be pictured as an arrow in space; past 3 we can't picture it, but every rule in this module works the same in 25 dimensions as in 2.
Quick check
What is the dimension of the vector (4, −1, 0, 7)?
7
10
4
3
Show the answer
4
It has four components, so it's 4-dimensional: a point in ℝ⁴. The 0 still counts.
In your own words
In your own words: why is the arrow from (1, 1) to (4, 3) the same vector as the one from (0, 0) to (3, 2)?
Write a sentence or two, then compare it with a good answer in the lesson.
In Python: NumPy arrays
Purpose. Store vectors so that math on them is fast and short.
NumPy is the Python library almost everyone uses for arrays of numbers, imported under the short name np. np.array turns a list into an array, and .shape says how many numbers it holds:
import numpy as np
v = np.array([3, 2])
print(v, v.shape, v[0], len(v))
It runs right here in your browser, with nothing to install.
(2,) means one direction with 2 numbers: a 2-dimensional vector. Indexing counts from 0, as with lists, so v[0] is v₁. Arrays print without commas, which is a quick way to tell an array from a list.
Code flow. Here is that step from list to array one line at a time, with two tent-shop days, each (temperature, humidity). Step through and watch the boxes under Variables: np.array keeps the numbers and changes only the type, from list to ndarray, NumPy's name for an array. Then the last two lines use + on each kind.
A named mistake: a list isn't an array. You just watched it: with lists, + joins them end to end. With arrays, + adds matching components, which is what vector math needs. Printing shows the difference too:
The first line makes a longer list; the second adds vectors. Code that mixes them up runs without an error and gives the wrong kind of answer. When in doubt, print it: commas mean a list.
Unrolling a picture is one method call. .flatten() lays the rows end to end:
Each is a 1-dimensional array, a vector, and .shape gives its dimension: a day is 2 numbers (temperature, humidity), a 3 × 3 sign unrolled is 9, the weights are 3, and the word is 4. Models never see "a day" or "a word", only these lists. Everything they learn is learned from vectors like these.
Quick check
What does this print?
import numpy as np
v = np.array([5, 1, 4])
print(v.shape, v[2], len(v))
(3,) 4 3
3 4 3
(3,) 1 3
(1, 3) 4 3
Show the answer
(3,) 4 3
Three numbers give shape (3,). v[2] is the third, counting from 0: 4. len is 3.
Quick check
Which line adds two vectors component by component?
[1, 2] + np.array
(1, 2) + (3, 4), with tuples
[1, 2] + [3, 4], with plain lists
np.array([1, 2]) + np.array([3, 4])
Show the answer
np.array([1, 2]) + np.array([3, 4])
Arrays add matching components: [4 6]. Lists and tuples join end to end instead.
Drill
Lists into vectors
Fix the code: total should be the component-by-component sum of the two days, and x the 2 × 3 grid unrolled into a vector of 6.
import numpy as np
day1 = [20, 50]
day2 = [24, 60]
total = day1 + day2
grid = np.array([[1, 2, 3], [4, 5, 6]])
x = grid
print(total, x.shape)
In the lesson, your code is checked as you write it.
In your own words
Why does vector math in Python use NumPy arrays instead of lists?
Write a sentence or two, then compare it with a good answer in the lesson.
In AI and ML: every example is a vector
Purpose. A model can only take numbers in, so everything it sees is first turned into a vector.
Here are this lesson's three kinds of data as a model sees them:
A tent-shop day is (temperature, humidity): a vector in ℝ².
A trail sign, a 5 × 5 picture unrolled, is a vector in ℝ²⁵.
A word is looked up in a table and replaced by a short list of numbers learned in training, its embedding. Words used in similar ways end up with similar vectors.
x∈Rd
In plain words: an input is d numbers. The model's job is to turn those d numbers into a prediction.
Here three words each have a 2-number embedding; row 1 is the second word's vector.
Quick check
A model reads 28 × 28 gray pictures. What is the dimension of each input vector?
2
56
784
28
Show the answer
784
Every pixel is one component: 28 × 28 = 784. Each picture is a point in ℝ⁷⁸⁴.
Why vectors make similarity easy. Once two things are vectors of the same length, they can be compared number by number: lesson 41's distance, and lesson 51's angle, both work on any two vectors. Two pictures of the same sign are close vectors; two words used in the same way have embeddings pointing the same way. Turning things into vectors is the step that makes "similar" something a computer can measure.
The shape is the first thing to check. Every model expects inputs of one fixed dimension. A model built for 25-pixel signs can't read a 36-pixel one, and a model built for (temperature, humidity) can't read a day described by three numbers. So the first line of almost any ML debugging is a print of .shape, and the first question about any data set is "how many numbers describe each example?"
Quick check
What does this print?
import numpy as np
day = np.array([24, 60])
sign = np.array([[1, 0], [0, 1]]).flatten()
print(day.shape, sign.shape, sign.tolist())
(2,) (2, 2) [1, 0, 0, 1]
(2,) (4,) [1, 0, 1, 0]
(2,) (4,) [1, 0, 0, 1]
(1, 2) (4,) [1, 0, 0, 1]
Show the answer
(2,) (4,) [1, 0, 0, 1]
A day is a vector of 2. The 2 × 2 sign unrolls row by row into a vector of 4: row 1 (1, 0), then row 2 (0, 1).
Drill
Shapes of real data
Set n_day, n_sign and n_word to the dimensions of a tent-shop day (temperature, humidity, wind), a 6 × 6 sign unrolled, and a word with an 8-number embedding. Then set flat to the 2 × 2 grid g unrolled.
import numpy as np
n_day = 2
n_sign = 6 + 6
n_word = 1
g = np.array([[7, 8], [9, 10]])
flat = g
print(n_day, n_sign, n_word, flat)
In the lesson, your code is checked as you write it.
In PyTorch. PyTorch is the library most models are written in, and its array is called a tensor. Your browser can't run real PyTorch, so it runs a small teaching version of it, with NumPy underneath. The PyTorch lines in these lessons run unchanged on a real install. Every lesson with code in Phases 2 to 6, math to LLM engineering, has a "Run it for real" notebook that runs its code on the real libraries, and PyTorch tensors takes tensors further.
torch.tensor makes a tensor from a list, and torch.from_numpy makes one from a NumPy array:
The first printed line holds the same numbers the NumPy embeddings cell above printed: 3 words of 2 numbers, and row 1 is 0.8, 0.2. PyTorch writes the shape as torch.Size([3, 2]) and shows four decimals. .dtype is the kind of number a tensor holds: torch.float32, PyTorch's usual decimal, takes 32 bits per number. NumPy's usual decimal is float64, twice the bits, and torch.from_numpy keeps it. A model's weights are float32, and a layer given float64 numbers stops with an error, so an array from NumPy usually gets .float() on its way in.
Quick check
What does this print?
import numpy as np
import torch
g = torch.from_numpy(np.array([[0.5, 1.0], [2.0, 4.0]]))
print(g.flatten().shape, g.dtype)
torch.Size([2, 2]) torch.float64
torch.Size([4]) torch.float64
torch.Size([4]) torch.float32
(4,) torch.float64
Show the answer
torch.Size([4]) torch.float64
flatten unrolls the 2 × 2 grid into 4 numbers, which PyTorch writes as torch.Size([4]). torch.from_numpy keeps NumPy's float64; .float() would make it float32.
In your own words
Why does a model need its inputs as vectors?
Write a sentence or two, then compare it with a good answer in the lesson.
31Formulas with fractions: clear them firstFreeClearing denominators, cross-multiplying, a letter in the bottom, and reciprocal formulas like 1/R = 1/R₁ + 1/R₂.35 min
37Inverse functions, lines and scalingFreeUndoing a function by making x the subject, domains that allow it, line forms, and unscaling predictions.40 min
38Sequences and sums: find n, a, d and rFreeEvery letter of the arithmetic and geometric formulas as the subject, and an average's window from its decay.40 min
40Review: rearrange anything (algebra)FreeBroken rearrangements to fix, mixed practice from the whole algebra block, a strategy chart, and its formula sheet.35 min
41Coordinates and distanceFreePoints as (x, y), Pythagoras, distance in any number of coordinates, and nearest neighbors.42 min
42Angles, degrees and radiansFreeMeasuring a turn, converting units, arcs, and the angle between two arrows.36 min
43Sine and cosineFreeAcross and up: right triangles, the unit circle, and directions and rotations.42 min
44Waves: height, speed and shiftFreeAmplitude, period and phase, sampling a wave, and position codes in transformers.37 min
68Vector equations: rearranging with arrowsFreeSolving for a vector or a scale, recovering a gradient from two weight snapshots, and an angle from a dot product.40 min
87Counting: choices, orders and groupsFreeThe counting principle, factorials, ordered picks and groups, and why attention's cost grows with the square of the length.43 min
88Probability: from counts to chancesFreeEqually likely outcomes, the complement, distributions, seeded simulation, and a next-word model.43 min
89Combining events: and, or, independentFreeThe or rule, independence, probability trees, drawing with and without replacement, and chains of steps.42 min
100Maximum likelihoodFreeLikelihoods as products, log-likelihoods as sums, grid search, underflow, and the negative log-likelihood loss.45 min
101Linear regression: the best lineFreeResiduals, least squares by formula, three roads to one line, the matrix form, and train versus test error.45 min
109One neuron, start to finishFreeWeighted sum, activation, loss, slopes and update, by hand and in code, and what one straight line can and can't split.45 min
111Training a small networkFreeThe backward pass in matrix form, gradient checks, a full training loop, and reading loss curves.45 min
112The same network in PyTorchFreenn.Sequential with the NumPy weights loaded, the same loss and slopes, then SGD and mini-batches.45 min
113Attention as matrix mathFreeScaled dot-product scores, the causal mask, a row-by-row softmax, and blending value vectors.45 min
114Residual connections and layer normFreeAdding the input back and why its slope keeps learning alive, layer norm by hand, and add and norm.40 min
115A transformer block, start to finishFreeA sentence through embeddings, attention, add and norm, a small network and next-word scores, every shape named.45 min
117Final test: transpose any formulaFreeSlips to fix from every topic, mixed practice of every kind of rearranging, the strategy chart and the full sheet.45 min
Learn the math behind AI from arithmetic up: numbers, algebra, vectors and matrices, calculus, probability and statistics, each shown as numbers moving and checked in Python, ending with a network you build and train from the formulas.
See the course →
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write