Level 3 In-Depth AI · Programming and Tools
NumPy and Array Thinking
NumPy stores numbers in arrays and does maths on whole arrays at once, hundreds of times faster than Python loops. Shapes, indexing, broadcasting and matrix multiplication are the grammar of all AI code, including PyTorch.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 3 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 3 concepts before this one
- Vectors
- Python for AI
- Matrices and Matrix Multiplication
- NumPy and Array Thinking
Read them roughly in this order. See it on the concept map →
Why it matters
Every piece of data in AI ends up as a grid of numbers. A grayscale photo is a grid of brightness values. A sentence becomes a list of token ids and then a grid of embedding vectors. A neural network layer is a matrix of weights. Training means multiplying and adding these grids, billions of times.
Plain Python is far too slow for that. A Python for loop handles one number at a time, with a lot of overhead for each. NumPy ("Numerical Python") is the library that fixes this. It stores numbers in compact arrays and provides operations that act on a whole array at once, running in compiled C code. The result is often 100 to 10,000 times faster.
NumPy matters even more for what it teaches. Its way of thinking, about shapes, axes and broadcasting, is copied almost exactly by PyTorch, tensor libraries such as JAX, and Pandas and Working with Data. Learn it once here and you can read nearly all numerical AI code.
The intuition
Think of a spreadsheet. You could compute a new column by going down row by row, multiplying one cell by another. Or you could write one formula and apply it to the whole column at once. NumPy is the second approach. You stop thinking about individual numbers and start thinking about whole blocks of them.
Every array has a shape: a tuple of numbers giving its size along each direction. Each direction is called an axis (plural axes).
- A list of 5 numbers has shape
(5,). One axis. - A table with 100 rows and 3 columns has shape
(100, 3). Two axes: axis 0 runs down the rows and axis 1 runs across the columns. - A batch of 32 colour images, each 224 × 224 pixels with 3 colour channels, has shape
(32, 224, 224, 3). Four axes.
Most bugs in AI code are shape bugs. Experienced practitioners constantly ask "what shape is this?" and write the answer in comments.
How it works
The convention is to import NumPy as np. All outputs shown below are real.
Creating arrays
import numpy as np
a = np.array([1.0, 2.0, 3.0]) # from a Python list
X = np.array([[1, 2, 3],
[4, 5, 6]]) # a 2-D array: a list of rows
print(X.shape, X.ndim, X.dtype) # (2, 3) 2 int64
np.zeros((2, 3)) # 2x3 array of 0.0
np.ones(3) # [1. 1. 1.]
np.arange(0, 10, 2) # [0 2 4 6 8]
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ]
Unlike a Python list, every element of an array has the same dtype (data type), such as int64 (whole numbers stored in 64 bits) or float32 (decimals in 32 bits). Deep learning mostly uses float32 or smaller types, because they halve memory compared with float64. Mixed Precision Training and Quantization push this further.
Element-wise arithmetic
Arithmetic on arrays happens element by element, with no loop:
a * 10 # [10. 20. 30.]
a + a # [2. 4. 6.]
a ** 2 # [1. 4. 9.]
np.sqrt(a) # [1. 1.41421356 1.73205081]
Replacing an explicit loop with whole-array operations like these is called vectorisation. It is the single most important habit in numerical Python.
Indexing and slicing
Indexing works like Python lists, with one index per axis, separated by commas. Slicing with start:stop picks a range, and a bare : means "everything along this axis".
X[0] # [1 2 3] first row
X[1, 2] # 6 row 1, column 2
X[:, 1] # [2 5] every row, column 1
X[-1, :2] # [4 5] last row, first two columns
A boolean mask selects elements that meet a condition. The comparison produces an array of True/False, and indexing with it keeps the True positions:
scores = np.array([0.2, 0.9, 0.4, 0.7])
scores > 0.5 # [False True False True]
scores[scores > 0.5] # [0.9 0.7]
Reductions along an axis
Functions such as sum, mean, max and argmax (the position of the maximum) can work on the whole array or along one axis. The axis you name is the one that disappears:
X.sum() # 21
X.sum(axis=0) # [5 7 9] summed down the rows: one value per column
X.sum(axis=1) # [ 6 15] summed across columns: one value per row
X.mean(axis=0) # [2.5 3.5 4.5]
In AI code, axis 0 is almost always the batch axis (one row per example), so mean(axis=0) means "average over examples" and argmax(axis=1) means "for each example, which class scored highest".
Reshaping
reshape changes the shape without changing the data, as long as the total number of elements stays the same. A -1 means "work this size out for me". .T transposes (swaps rows and columns).
X.reshape(3, 2) # [[1 2] [3 4] [5 6]]
X.T # [[1 4] [2 5] [3 6]] shape (3, 2)
v = np.arange(12).reshape(3, 4)
v.reshape(-1).shape # (12,) flatten
v[None].shape # (1, 3, 4) add a new axis at the front
Flattening a 28 × 28 image into a vector of 784 numbers before feeding it to a simple network is exactly img.reshape(-1).
Broadcasting
What happens when you add arrays of different shapes? NumPy follows a rule called broadcasting: it stretches the smaller array, without actually copying it, so the shapes match.
The rule, in words: line the two shapes up from the right. Two sizes are compatible if they are equal or if one of them is 1. A size of 1 is stretched to match the other. A missing axis on the left counts as 1.
A worked example by hand. Take
and the row [10, 20, 30] with shape (3,). Lining up from the right, 3 matches 3, and the missing axis is treated as 1 and stretched to 2. So the row is added to each row of :
M = np.array([[1, 2, 3], [4, 5, 6]])
M + np.array([10, 20, 30]) # [[11 22 33]
# [14 25 36]]
M + np.array([[100], [200]]) # shape (2, 1): one number per row
# [[101 102 103]
# [204 205 206]]
M + np.array([1, 2]) # ValueError: operands could not be broadcast
# together with shapes (2,3) (2,)
The last line fails because, from the right, 3 and 2 are neither equal nor 1. Broadcasting is how you subtract the mean of each column from a dataset, add a bias vector to every example in a batch, or compare every point with every other point, all without loops.
Matrix multiplication
The @ operator performs matrix multiplication. For A @ B, the last axis of A must match the first axis of B, and those matching sizes vanish from the result: (n, k) @ (k, m) gives (n, m).
W = np.array([[1, 0], [0, 1], [1, 1]]) # shape (3, 2)
M @ W # (2, 3) @ (3, 2) -> (2, 2)
# [[ 4 5]
# [10 11]]
Check the top-left entry by hand: row 0 of M is (1, 2, 3) and column 0 of W is (1, 0, 1), and . Each entry is a dot product. A dense neural-network layer is exactly X @ W + b: a matrix multiply followed by a broadcast addition. Do not confuse @ with *, which multiplies element by element.
Random numbers
AI uses randomness everywhere: initial weights, shuffling data, dropout. Create a random number generator with a seed, a starting number that makes the "random" sequence repeatable, so you and others get the same results:
rng = np.random.default_rng(42)
rng.normal(0, 1, size=3) # [ 0.30471708 -1.03998411 0.7504512 ]
rng.integers(0, 10, size=5) # [0 6 2 0 5]
rng.permutation(5) # [2 4 0 3 1] a shuffled order
Run it again with seed 42 and you get exactly these numbers. Older code uses np.random.seed(0) and np.random.rand(...). That still works, but the generator style above is the recommended one.
Why it is so fast
A Python list holds pointers to separate number objects scattered around memory, and every + in a loop goes through Python's general machinery to check types. A NumPy array is one solid block of raw numbers of the same type. One call such as A @ B hands that whole block to optimised compiled code (for matrix multiplication, a linear-algebra library called BLAS) that uses the processor's vector instructions and several cores. Multiplying two 200 × 200 matrices with three nested Python loops took about 1.7 seconds on one laptop. A @ B took about 0.13 milliseconds, more than 10,000 times faster, with the same answer. GPUs push the same idea much further.
Key idea Think in whole arrays, not elements. If you are writing a
forloop over the numbers in an array, there is almost certainly a NumPy operation that does it faster. And always know the shape of every array.
In code
This example does three things you will see in every machine-learning pipeline: standardising features with broadcasting, a neural-network layer as a matrix multiply, and a row-wise softmax (which turns scores into probabilities, see Logistic Regression). Watch the shapes.
import numpy as np
rng = np.random.default_rng(0)
# A batch of 100 examples, 3 features each, on very different scales.
X = rng.normal(loc=[50, 0.5, 1000], scale=[10, 0.1, 200], size=(100, 3))
print(X.shape) # (100, 3)
# Standardise each column: broadcasting (100, 3) with (3,)
mean, std = X.mean(axis=0), X.std(axis=0)
X_std = (X - mean) / std
print(X_std.mean(axis=0).round(3) + 0, X_std.std(axis=0).round(3))
# One layer of a neural network: 3 inputs -> 4 outputs.
W = rng.normal(0, 0.1, size=(3, 4)) # weights
b = np.zeros(4) # biases
logits = X_std @ W + b # (100, 3) @ (3, 4) -> (100, 4)
# Softmax across each row turns scores into probabilities.
e = np.exp(logits - logits.max(axis=1, keepdims=True))
probs = e / e.sum(axis=1, keepdims=True) # (100, 4) / (100, 1)
print(probs.shape, probs[0].round(3), probs[0].sum())
print(probs.argmax(axis=1)[:10]) # predicted class per example
# (100, 3)
# [0. 0. 0.] [1. 1. 1.]
# (100, 4) [0.259 0.263 0.251 0.228] 1.0
# [1 1 0 3 3 3 0 0 0 3]
keepdims=True keeps the reduced axis as size 1, so the row maxima have shape (100, 1) instead of (100,). That makes them broadcast across the columns correctly. Without it, NumPy would try to line (100,) up against the last axis of size 4, and fail. Subtracting the row maximum before exp does not change the softmax but prevents overflow with large scores. The probabilities are close to 0.25 each because the weights are small and random: this network has not been trained. PyTorch adds the missing piece, automatic gradients, to the same operations.
Common pitfalls
*when you meant@.A * Bmultiplies element by element and, thanks to broadcasting, may silently produce an array of the wrong shape instead of an error.- Silent broadcasting. Subtracting a
(100,)array from a(100, 1)array gives a(100, 100)array, not an error. This classic bug often appears when computing errors aspred - y. Print shapes when results look odd. - Views, not copies. A slice such as
X[:, 0]is a view on the same memory. Changing it changesX. Use.copy()when you need independence. - Integer division surprises. An array created from whole numbers has an integer dtype. Assigning
0.5into it stores0. Create float arrays withnp.array([...], dtype=float)or write1.0instead of1. - Forgetting the seed. Without a fixed seed, results change every run, and you cannot tell whether a change in accuracy came from your edit or from luck.
Watch out The most dangerous shape bug produces no error at all. If
y_predhas shape(n, 1)andyhas shape(n,), then((y_pred - y) ** 2).mean()broadcasts to an(n, n)table and returns a plausible-looking but meaningless loss. Your model trains, badly, and nothing complains. Checky_pred.shape == y.shapebefore computing a loss.
Where it leads
- Pandas and Working with Data builds labelled tables on top of NumPy arrays.
- Visualising Data turns arrays into charts with Matplotlib.
- scikit-learn takes NumPy arrays as input:
Xwith shape(n_samples, n_features)andywith shape(n_samples,). - PyTorch tensors behave almost exactly like NumPy arrays, adding GPU support and automatic gradients.
torch.from_numpyandtensor.numpy()convert between them. - Tensors and Shapes explains the mathematics of arrays with many axes, and GPUs and Why AI Needs Them why array operations parallelise so well.
A bit of history
Fast array computing in Python began with Numeric, written by Jim Hugunin in 1995. A rival package, Numarray, followed in the early 2000s, and the community was split until Travis Oliphant merged the two into NumPy, releasing version 1.0 in 2006. Broadcasting and the array style itself descend from older array languages such as APL (1960s) and from MATLAB. NumPy 2.0, the first major version change in 18 years, arrived in 2024. A 2020 paper in Nature, "Array programming with NumPy", describes its design and its role in projects from the first image of a black hole to the detection of gravitational waves.
Try it
- Create
A = np.arange(12).reshape(3, 4). Predict the shapes ofA.sum(axis=0),A.sum(axis=1),A[:, :2]andA @ A.T, then check.- Given 5 points in 2-D,
P = rng.random((5, 2)), compute the 5 × 5 table of distances between every pair without a loop. UseP[:, None, :] - P[None, :, :].- Write the dense layer above with an explicit Python loop over the 100 examples and compare it with
X_std @ W + busingnp.allclose. Time both with%timeit.Hint for 2: the difference has shape
(5, 5, 2). Square it, sum over the last axis, and take the square root.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
NumPy: the absolute basics for beginners
The official, friendly introduction to arrays, shapes, indexing and broadcasting.
Python Data Science Handbook
Free online book covering IPython and notebooks, NumPy, pandas, Matplotlib and scikit-learn, every chapter a runnable notebook.
Broadcasting
The official explanation of NumPy's broadcasting rules, with diagrams of how arrays of different shapes line up.
From Python to NumPy
A free book on thinking in vectorised code, with many worked examples of turning loops into fast array operations.
CS231n Python and NumPy Tutorial
A compact crash course in Python, NumPy, SciPy and Matplotlib written for students starting deep learning.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/numpy.md