Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 2: Programming Toolkit

NumPy: arrays and vectorization

P2.240 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Almost all data in machine learning is stored in arrays, and training only finishes in a reasonable time when whole-array operations replace Python loops. NumPy is where you learn both habits, and PyTorch tensors copy its way of working.

Before this: Your toolkit, Python essentials for ML, Tensors, shapes and broadcasting

After this lesson you can

  • Describe an ndarray by its shape, dtype and memory, and create arrays with array, zeros, ones, full, arange, linspace, eye and a random generator
  • Explain why a vectorized NumPy expression is much faster than the same Python loop, and rewrite a simple loop as an array expression
  • Say whether an indexing expression returns a view or a copy, and avoid the bug where changing a slice changes the original
  • Predict the shape and values of slicing, reshaping, axis reductions (with and without keepdims), boolean masks and np.where
  • Avoid the common pitfalls of dtypes, integer overflow, integer division, shape (n,) against (n,1) and in-place operations

You have one million numbers and want the sum of their squares. In plain Python you write a loop: take a number, square it, add it to a running total, a million times. In NumPy you write (x * x).sum(). Both give the same answer. On the laptop that wrote this lesson the loop needed about 16 milliseconds and the NumPy line about a millisecond or less. The timer cell below measures both on your machine, so you can see it for yourself.

A single sum does not matter much. But training a model repeats this kind of work billions of times. A habit of writing whole-array expressions instead of loops is the difference between code that finishes and code that does not. This lesson teaches that habit, and the everyday NumPy tools that go with it.

You met your first NumPy cell in P0.4. This lesson is the full tour. P1.B14 explained shapes, axes and the broadcasting rule as ideas; here we use them as code and link back instead of repeating the rules. P2.3 goes deeper on broadcasting and einsum.

What an array is

A NumPy array (type name ndarray, “n-dimensional array”) is a grid of numbers with three properties:

  • One dtype. Every entry has the same type, for example float64 (a 64-bit float, 8 bytes) or int64 (a 64-bit integer, 8 bytes). A Python list can mix a number, a word and another list. An array cannot, and that restriction is what makes it fast.
  • A shape. A tuple with the length of each axis. A table of 3 rows and 4 columns has shape (3, 4). A plain list of 5 numbers has shape (5,).
  • Packed memory. The numbers sit next to each other in one block of memory, not as separate objects scattered around.

Some useful attributes: shape, ndim (the number of axes), size (the number of entries, the product of the shape), dtype, itemsize (bytes per entry) and nbytes (bytes in all, which equals size * itemsize).

In machine learning the shape has a meaning. The rows of a data array are usually the examples and the columns are the features: an array of shape (N, d) holds NN examples with dd features each (P1.B5, P1.B14). A batch of BB examples is a slice of BB rows.

Creating arrays

You wantWrite
From a listnp.array([[3, 1], [4, 1]]), shape (2, 2)
Zeros, ones, one valuenp.zeros((2, 3)), np.ones(3), np.full((2, 2), 7.5)
The identity matrixnp.eye(3): 1 on the diagonal, 0 elsewhere
Evenly spaced by a stepnp.arange(2, 11, 3) gives [2 5 8] (stop excluded)
Evenly spaced by a countnp.linspace(0, 1, 5) gives [0. 0.25 0.5 0.75 1.] (end included)
Same shape as anothernp.zeros_like(A)
Random numbersrng = np.random.default_rng(0), then rng.random((4, 3)): uniform on [0, 1)

The random generator default_rng and its seed are explained in P1.G3. Use one generator, give it a seed, and call its methods (rng.random, rng.normal, rng.integers, rng.permutation).

arange and linspace look alike but behave differently. With a float step arange can surprise you, because the length is computed with rounding error: np.arange(1, 1.3, 0.1) has four entries, and the last one, 1.3000000000000003, is even a little above the “excluded” stop 1.3. When the step is a float, use linspace and say how many points you want.

The cell below shows the attributes, the constructors and the arange trap. Run it and compare each line with the table.

Try it: attributes and ways to make an array

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

shape:    (3, 4)
ndim:     2
size:     12
dtype:    int64
itemsize: 8 bytes per number
nbytes:   96 bytes in all
[[0. 0. 0.]
 [0. 0. 0.]]
[1 1 1]
[[7.5 7.5]
 [7.5 7.5]]
[[1 0 0]
 [0 1 0]
 [0 0 1]]
[2 5 8]
[0.   0.25 0.5  0.75 1.  ]
[1.  1.1 1.2 1.3]
[1.   1.15 1.3 ]
random shape: (4, 3) | in [0, 1): True
ints and floats mixed: float64
default int here: int64

The cell sets dtype=np.int64 for the integer arrays on purpose. If you leave it out, NumPy 2 picks int64 on 64-bit computers (older NumPy on Windows picked int32); in 32-bit environments, such as the browser Python on this site, it can be int32. Set dtype when the integer size matters. Floats default to float64. The last line of the cell prints the default integer type of the computer that runs it: in the browser on this site it prints int32.

Go deeper Memory layout: strides and why a transpose is free

An array is a flat block of bytes plus a description of how to walk through it. The strides are the number of bytes to jump to reach the next entry along each axis. For the int64 array A of shape (3, 4), A.strides is (32, 8): the next column is 8 bytes away, the next row is 32 bytes away (4 entries of 8 bytes). This is the usual row-major layout (also called C order): a row is contiguous.

Because the description is separate from the bytes, many operations only change the description. The transpose A.T has strides (8, 32) and the same bytes. A slice A[:, ::2] has strides (32, 16): it skips every other entry. These results are views (more below). One consequence: A.T is not contiguous, and an operation that needs a contiguous block may have to make a copy.

You almost never touch strides yourself. They explain why some operations are instant (a view only builds a new description) and why others copy data.

Why loops are slow, and what vectorization does

Vectorization means writing an operation on a whole array at once, x * x, instead of a Python loop over the entries. Here is where the time goes in the loop for v in xs: total += v * v:

  1. The interpreter does work for every element. Python reads each step of your loop, finds the type of v, looks up what * means for that type, calls it, creates a new number object for the result, and repeats for +=. Each step is small, but it is repeated for every element.
  2. Numbers are objects. A Python list stores a pointer to each number, and each Python float is its own small object. On a typical 64-bit CPython a float object takes 24 bytes and its pointer 8 more, about 32 bytes per number. A NumPy float64 array stores 8 bytes per number, side by side. Less memory means more numbers fit in the fast memory close to the processor.
  3. NumPy loops in compiled code. x * x is one call. NumPy checks the dtypes and shapes once, then runs a loop written in a compiled language over the packed numbers. Compiled loops can also use processor instructions that handle several numbers at once (often called SIMD), which a Python loop cannot.

As P1.G4 explained, the Big-O stays the same and only the constant changes. How large the gain is depends on your machine and the array size: measure, don’t assume.

Signature cell: the timer

The first cell times the sum of squares with a Python loop and with NumPy at four sizes. It prints “on this machine”, because the numbers differ from computer to computer and from run to run.

Timer: loop vs. vectorized (sum of squares)

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

On the machine that wrote this lesson (a laptop, running ordinary Python rather than the browser version) one run looked like this. Yours will differ, and the in-browser version will give other numbers:

sum of squares, on this machine (best of 3):
        n      loop       NumPy ratio
    1,000  0.017 ms   0.002 ms    9x
   10,000  0.170 ms   0.005 ms   33x
  100,000  1.669 ms   0.038 ms   44x
1,000,000 16.727 ms   0.789 ms   21x
Numbers change from run to run.

Two things to notice. The loop time grows in proportion to nn (ten times more numbers, about ten times longer). The NumPy time grows more slowly at first, because each call has a fixed start-up cost, and a little faster than nn once the array stops fitting in the processor’s fast memory (so the ratio can even drop for the biggest array). The Big-O of both is still nn. Vectorization pays when the arrays are not tiny.

P1.G4 said a NumPy call is often a hundred times faster or more. For this simple sum of squares the ratio is smaller (here between about 10 and 45); for the distance example below it is about 100.

Where vectorization does not help

The second cell compares three ways to compute the distance from one query point to each of 20,000 points with 8 features (this is what k-nearest neighbors does, P3.B1). The middle one is a trap: it still runs a Python loop, with a NumPy call inside.

Try it: three ways to compute 20,000 distances

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

On the lesson writer’s laptop (again, yours will differ) one run printed:

same answers: True
on this machine (best of 3):
  two Python loops:       14.62 ms
  NumPy call per row:     54.39 ms
  one expression:          0.54 ms
  NumPy-per-row / one expression = 101x
summing 200,000 numbers:
  loop over a list:       2.94 ms
  loop over an array:    14.39 ms
  arr.sum():             0.033 ms

Three lessons from one run:

  • A NumPy call inside a Python loop is not vectorized. Here it was even slower than the plain Python loops, because each of the 20,000 tiny NumPy calls pays its start-up cost. The speed comes from one call on the whole array.
  • Looping over a NumPy array element by element is slow, often slower than looping over a list, because each step has to wrap one packed number into a Python object. Convert the loop into an array expression, or if you must loop, think about tolist().
  • X - q subtracts a vector of 8 numbers from every one of the 20,000 rows. That uses the broadcasting rule from P1.B14 and P2.3. For now, read it as “subtract q from each row”.
Go deeper What vectorization costs, and what np.vectorize is

A whole-array expression builds its intermediate results as arrays. In ((X - q) ** 2).sum(axis=1), the part X - q makes a full temporary array of the same size as X, and so does the squaring. For very large data that means extra memory, and a lot of reading and writing of memory. Programs that are limited by memory speed rather than arithmetic speed (P1.G4) see smaller gains. The in-place forms (np.multiply(a, b, out=a)) and processing the data in chunks reduce the temporaries.

np.vectorize does not make a function fast. Its own documentation says it is provided mainly for convenience and is implemented as a loop. It makes a Python function accept arrays, and the Python function still runs once per element. For speed you need an expression built from NumPy’s own functions.

Elementwise operations and ufuncs

Arithmetic on arrays of the same shape works entry by entry: a + b, a - b, a * b, a / b, a ** 2. A function that applies to every entry independently is called a universal function, or ufunc: np.sqrt, np.exp, np.log, np.abs, np.sin, np.maximum. Comparisons are ufuncs too: a > 0 gives an array of True and False.

Two operations that beginners mix up:

  • * is elementwise. np.array([1, 2, 3]) * np.array([10, 20, 30]) is [10 40 90].
  • @ is the matrix product (P1.B6). For two 1D arrays it is the dot product, [1 2 3] @ [10 20 30] is 140.

An array of one shape and an array of another shape can still combine when they are compatible: W * x below multiplies every row of W by x. The rule behind that is broadcasting (P1.B14, P2.3).

Two small tools: np.maximum(s, 0) is ReLU applied to a whole array (P4.4), and np.exp(s) is esie^{s_i} for every entry.

Indexing and slicing

Indexing an array uses the same ideas as lists, with one comma-separated index per axis. The shape rules (an integer drops an axis, a slice keeps it) are in P1.B14. In short, for A of shape (3, 4):

  • A[1, 2]: one entry, a single number.
  • A[1] or A[1, :]: row 1, shape (4,).
  • A[:, 2]: column 2, shape (3,).
  • A[0:2, 1:3]: rows 0 and 1, columns 1 and 2, shape (2, 2).
  • A[:, ::2]: every other column, starting at column 0, shape (3, 2).
  • A[-1, -2:]: last row, last two columns, shape (2,).

A slice is start:stop:step. The start is included, the stop is excluded, a negative number counts from the end, and ::-1 reverses. Try it in the widget before the next section: change the two boxes or press an example, and see which cells light up.

Which cells, which way

0123
03141
15926
28370

A[0:2, 1:3]

[[1 4]
 [9 2]]

shape (2, 2)

Basic slicing gives a view: the result shares memory with A, so changing it changes A.

A[0:2, 1:3] selects 4 cells. Shape (2, 2).
A 3 by 4 array A. In Slice mode, type an index or a slice for the rows and for the columns (such as 0:2, ::2, -1, ::-1) and the selected cells are outlined and filled, with the result and its shape below. In Reduce mode, choose sum, mean, max, min or argmax and an axis: an arrow shows which way the axis collapses, the result sits at the end of each row or column, and a star marks the winning cell for max, min and argmax. Means are rounded to 2 decimals. keepdims keeps the collapsed axis with size 1. If there is a tie, the first cell wins (as in argmax).

Things to try: press A[1] and then A[1:2] and compare the shapes, (4,) against (1, 4) (an integer drops the axis, a slice keeps it). Type 5 in the rows box and see the error. In Reduce mode, press axis=0, then axis=1, then switch on keepdims.

Views and copies: the classic bug

A view shares memory with the array it came from. A copy has its own memory. This decides whether changing one changes the other.

  • A basic slice (A[0, :], A[0:2, 1:3], A[:, ::2]) is a view. This is different from Python lists, where a slice is a copy.
  • Integer-array (fancy) indexing, such as A[[0, 2]], and boolean masks, such as A[A > 8], return copies.
  • The transpose A.T is always a view. reshape and ravel give views when the memory layout allows it.
  • flatten() and .copy() always make a copy.
  • But assigning through any index writes into the original: A[A > 8] = 0 changes A.

np.shares_memory(a, b) says whether two arrays overlap in memory. The cell below shows all four cases.

Try it: views, copies and the aliasing bug

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
A[1, 2]     = 6
A[1]        = [4 5 6 7]
A[:, 2]     = [ 2  6 10]
A[0:2, 1:3] =
[[1 2]
 [5 6]]
A[:, ::2]   =
[[ 0  2]
 [ 4  6]
 [ 8 10]]
A[-1, -1]   = 11
slice  : A[0, 0] is now 100 | shared: True
copy   : A[0, 1] is now 1 | shared: False
fancy  : A[0, 1] is now 1 | shared: False
mask   : A[A > 8] = [100   9  10  11] | shared: False
after A[A > 8] = 0:
[[0 1 2 3]
 [4 5 6 7]
 [8 0 0 0]]

Dtypes and conversion

The dtype fixes how many bytes each number takes and how it behaves (P1.G1 explains the bit layouts). Convert with astype, which returns a new array: x.astype(np.float32). The dtype matters in four ways.

Memory. float32 takes 4 bytes per number and float64 takes 8, so one million numbers take 4,000,000 bytes or 8,000,000 bytes. Deep learning usually uses float32 or smaller (P1.G1, P10.B4). NumPy’s own default for floats is float64.

Integers wrap around. Fixed-width integers do not grow. An int8 holds −128-128 to 127127, and 127 + 1 wraps to -128, as explained in P1.G1. NumPy arrays do this silently; a single NumPy scalar can print an overflow warning, but you should not count on a warning.

Mixed types are promoted. np.array([1, 2, 3]) + 1.5 gives floats. A list that mixes ints and floats becomes a float64 array.

Assigning a float into an int array truncates silently. After x[0] = 2.9, an integer array holds 2. And the in-place x += 0.5 on an integer array raises an error, because the result cannot be stored back as integers without losing information.

Two Python habits that change meaning here. / always gives floats, // is floor division, and the mean of an integer array is a float. The cell shows each.

Try it: dtype surprises

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

int8 + 1:         [ 101  121 -128]
as int64, + 1:    [101 121 128]
int / 2:          [0.5 1.  1.5]   dtype: float64
int // 2:         [0 1 1]
after x[0] = 2.9: [2 2 3]
x += 0.5 fails with UFuncTypeError
float64 bytes: 24 | float32 bytes: 12
0.1 + 0.2 == 0.3          : False
np.isclose(0.1 + 0.2, 0.3): True
mean of int array [1, 2, 4]: 2.3333333333333335

Comparing floats

Floating-point numbers are rounded (P1.G1, P1.G2), so 0.1 + 0.2 == 0.3 is False. Compare floats with np.isclose(a, b), or np.allclose(a, b) for a whole array (one True or False). By default two numbers count as close when ∣a−b∣≤atol+rtol⋅∣b∣|a-b|\le \text{atol}+\text{rtol}\cdot|b|, with rtol=1e-05 and atol=1e-08. The test is not symmetric: b is the reference. Near zero only the absolute part helps, so for numbers that are naturally tiny set atol yourself. To compare two integer arrays exactly, use np.array_equal(a, b). And remember that a == b on arrays gives an array of True and False, so if a == b: raises an error (“truth value of an array is ambiguous”).

Reshaping

A.reshape(r, c) gives the same entries, in the same reading order (row by row), cut into a new shape. The total size must stay equal, and one size may be -1, which means “work it out”: np.arange(6).reshape(3, -1) has shape (3, 2). The full rules and the difference between a reshape and a transpose are in P1.B14.

To turn a vector into a column use v.reshape(-1, 1) or v[:, None]; for a row use v[None, :]. A.T is the transpose. The shape rules, and the difference between a reshape and a transpose, are in P1.B14.

A (n,) array is not a (n, 1) array. Subtract one from a column (6, 1) and NumPy builds a full (6, 6) table. When a result has an unexpected shape, print .shape first.

Axis operations

A reduction takes many numbers and returns fewer: sum, mean, max, min, std, prod, any, all, and argmax/argmin (the position of the largest or smallest). With no axis, a reduction combines every entry into one number. With axis=k it combines along axis k, and that axis disappears from the shape.

For A of shape (3, 4):

  • A.sum(axis=0) adds down each column and gives shape (4,): the row axis (axis 0) collapsed.
  • A.sum(axis=1) adds along each row and gives shape (3,): the column axis (axis 1) collapsed.
  • With keepdims=True the collapsed axis stays with size 1: (1, 4) and (3, 1). The result can then take part in further arithmetic with A without any reshaping (P1.B14).

Use the Reduce mode of the widget above to see the arrow. In a data matrix of shape (N, d), rows are examples and columns are features, so:

  • X.mean(axis=0) has shape (d,): the mean of each feature over all examples.
  • X.sum(axis=1) has shape (N,): one number per example.
  • For scores of shape (B, K) (a batch of BB examples and KK classes), scores.argmax(axis=1) has shape (B,): the predicted class of each example.

Standardizing the features is a short recipe: subtract each feature’s mean and divide by its standard deviation, z=(x−μ)/σz=(x-\mu)/\sigma. In NumPy: Z = (X - X.mean(axis=0)) / X.std(axis=0). Each column of Z then has mean 0 and standard deviation 1.

For higher-dimensional arrays, axis can be a tuple (T.sum(axis=(0, 2))) and negative values count from the end (axis=-1 is the last axis), as in P1.B14.

Try it: axes, reshape, masks and np.where

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

sum, no axis:    49
sum axis=0:      [16 13 13  7]   shape (4,)
sum axis=1:      [ 9 22 18]   shape (3,)
sum axis=1, keepdims=True:
[[ 9]
 [22]
 [18]]   shape (3, 1)
max axis=0:      [8 9 7 6]
argmax axis=1:   [2 1 0]
mean axis=0:     [5.33 4.33 4.33 2.33]
feature means:         [  2.5  25.  250. ]
standardized column 0: [-1.342 -0.447  0.447  1.342]
standardized means:    [0. 0. 0.]
[[0, 1, 2], [3, 4, 5]] (3, 2) (6, 1)
(n,) vs (n,1) vs (1,n): (6,) (6, 1) (1, 6)
mask: [False  True  True False] | count: 2
relu via where: [0.  0.5 3.  0. ]
np.where, one argument: (array([1, 2]),)
both conditions: [False  True False False]

Boolean masks and np.where

A comparison gives an array of True and False, the mask. Use it three ways:

  • Select: s[s > 0] keeps the entries where the mask is True (a copy, shape (count,)).
  • Assign: s[s < 0] = 0 sets those entries to 0 in place (this one writes into s).
  • Count: (s > 0).sum() counts the True values (True counts as 1), and (s > 0).mean() is the fraction. The accuracy of a classifier is (pred == y).mean().

To combine masks use & (and), | (or) and ~ (not), with parentheses around each comparison: (s > 0) & (s < 1). The words and, or and not do not work on arrays, and without the parentheses the & is evaluated first and the expression fails.

np.where(cond, a, b) builds a new array that takes a where cond is true and b elsewhere: np.where(s > 0, s, 0.0) is a ReLU. With only the condition, np.where(cond) returns the positions of the true entries (as a tuple with one array per axis). mask.any() and mask.all() ask “is any / is every entry true”.

Matrix product, stacking, sorting

Matrix product. A @ B multiplies matrices, with the shape rule (m, n) @ (n, p) giving (m, p) (P1.B6). With a vector, W @ x of shapes (2, 3) and (3,) gives (2,). Two 1D arrays give a single number, their dot product. Compare W * x, which is not a product of matrices but an entry-by-entry multiplication in which the row x is repeated for each row of W.

Joining arrays. np.concatenate([a, b], axis=0) joins along an existing axis. np.stack([a, b], axis=0) joins along a new axis, so two arrays of shape (3,) give (2, 3), or (3, 2) with axis=1. np.vstack and np.hstack are shorthand for stacking rows or columns. The new axis in stack is the same idea as the batch axis: a batch of BB examples of shape (d,) is a stack with shape (B, d).

Sorting. np.sort(s) returns a sorted copy. s.sort() sorts in place and returns None. np.argsort(s) returns the positions that would sort the array, which is how you rank things: np.argsort(s)[::-1][:k] gives the positions of the kk largest values. (argsort is not stable by default; pass kind="stable" if equal values must keep their order.)

Try it: stack, @, sort and argsort

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

concatenate: [ 1  2  3 10 20 30]
stack axis=0: (2, 3)
[[ 1  2  3]
 [10 20 30]]
stack axis=1: (3, 2)
[[ 1 10]
 [ 2 20]
 [ 3 30]]
vstack:
[[ 1  2  3]
 [10 20 30]
 [ 7  8  9]]
W * x   (elementwise):
[[ 4  0 12]
 [ 0  5 18]]
W @ x   (matrix-vector): [16 23]
a @ b   (dot product):   140 | a * b: [10 40 90]
np.sort(s): [10 20 30 40] | s is still [30 10 20 40]
argsort(s): [1 2 0 3]
indices of the 2 largest: [3 0]
after s.sort() (in place): [10 20 30 40]
allclose: True
a == b gives an array: [ True False]
np.array_equal: False
Go deeper Top k without sorting everything, and einsum

To find the kk largest of nn values you do not need to sort all of them. np.argpartition(s, -k)[-k:] puts the kk largest positions at the end (in no particular order) with less work than a full sort when nn is large. Then sort just those kk if you need the order.

np.einsum writes sums over repeated indices directly, for example np.einsum('ij,j->i', W, x) is W @ x. It is the subject of P2.3.

Common bugs and their fixes

  • b = a[1:3]; b[0] = 99 also changes a (a view). Fix: b = a[1:3].copy(). The same goes for b = a: one array with two names, so use b = a.copy().
  • x[0] = 2.9 on an int array stores 2, silently, and x += 0.5 raises UFuncTypeError. Fix: make the array float (astype(float)).
  • a == b on float arrays compares rounded numbers exactly, and if a == b: raises an error. Fix: np.allclose(a, b) or np.array_equal(a, b).
  • s > 0 & s < 1 fails, because & is evaluated first. Fix: (s > 0) & (s < 1).
  • (n,) minus (n, 1) gives an (n, n) table with no error. Fix: print the shapes and reshape one of them.
  • int8 arithmetic near 127 wraps to a negative number. Fix: use a wider dtype.
  • Python’s sum(x) and for v in arr: on a big array are slow. Fix: x.sum() or an array expression.

Intuition

A NumPy array is a block of identical numbers, so one operation can run over all of them in a tight compiled loop. Think in whole arrays: “the mean of each column”, “where this is positive”. Slices are windows onto the same block, masks and index lists make new blocks, and the axis you name in a reduction is squeezed away.

Math

The sum of squares is ∑ixi2=x⋅x\sum_i x_i^2=\mathbf{x}\cdot\mathbf{x}, which is x @ x. For A∈Rm×n\mathbf{A}\in\mathbb{R}^{m\times n}, A.sum(axis=0) is sj=∑iAijs_j=\sum_i A_{ij} and A.sum(axis=1) is ti=∑jAijt_i=\sum_j A_{ij}. Standardizing a data matrix gives Zij=(Xij−μj)/σjZ_{ij}=(X_{ij}-\mu_j)/\sigma_j with μj=1N∑iXij\mu_j=\frac1N\sum_i X_{ij}.

Code

import numpy as np
X = np.random.default_rng(0).random((100, 5))   # 100 examples, 5 features
Z = (X - X.mean(axis=0)) / X.std(axis=0)        # standardize each feature
dist = np.sqrt(((X - X[0]) ** 2).sum(axis=1))   # distance of every example to example 0
nearest = np.argsort(dist)[1:4]                 # three nearest (skipping itself)

Quiz

Check your understanding

  1. Why is (x * x).sum() on a large NumPy array usually much faster than a Python for loop that adds up v * v?

  2. With a = np.arange(5), you run b = a[1:3] and then b[0] = 99. What is a afterwards?

  3. For A of shape (3, 4), what is the shape of A.sum(axis=0)?

  4. Which of these returns a copy of part of A rather than a view?

  5. What does np.array([1, 2, 3], dtype=np.int64) // 2 return?

  6. In NumPy, np.array([127], dtype=np.int8) + np.int8(1) gives [-128]. What does this show?

Exercises

  1. An array has shape (5, 4, 3) and dtype float32. What are its ndim, size and nbytes?
    Show answerndim is 3, size is 5⋅4⋅3=605\cdot4\cdot3=60, and nbytes is 60⋅4=24060\cdot4=240 bytes (4 bytes per float32).
  2. What does np.arange(2, 11, 3) return, and what does np.linspace(0, 1, 5) return?
    Show answer[2 5 8] (the next value, 8 + 3 = 11, equals the stop, which is excluded) and [0. 0.25 0.5 0.75 1. ] (five points, both ends included).
  3. With B = np.arange(12).reshape(3, 4), what is B[1:, ::2] and what is its shape?
    Show answer[[ 4 6] [ 8 10]], shape (2, 2): rows 1 and 2, columns 0 and 2.
  4. A data array X has shape (100, 5): 100 examples and 5 features. Give the code and the shape for (a) the mean of each feature and (b) the same with keepdims.
    Show answer(a) X.mean(axis=0), shape (5,). (b) X.mean(axis=0, keepdims=True), shape (1, 5). The axis you name (axis 0, the examples) is the one that goes away.
  5. A batch of scores has shape (2, 3): L = np.array([[2.0, 0.5, 0.1], [0.2, 0.3, 1.5]]). Which class does the model predict for each example, and what is each winning score?
    Show answerL.argmax(axis=1) gives [0 2] and L.max(axis=1) gives [2. 1.5].
  6. Write the ReLU of s = np.array([-2., 0.5, 3., -0.1]) two ways, and count the positive entries.
    Show answernp.maximum(s, 0) and np.where(s > 0, s, 0.0) both give [0. 0.5 3. 0. ]. The count is (s > 0).sum(), which is 2.
  7. With x = np.array([3., 4.]), write the length x12+x22\sqrt{x_1^2+x_2^2} without a loop in two ways.
    Show answernp.sqrt((x * x).sum()) and np.sqrt(x @ x), both 5.0.
  8. a = np.array([100], dtype=np.int8). What is a * 2, and how do you get 200?
    Show answer[-56], because 200 does not fit in an int8 and wraps (200−256=−56200-256=-56). Use a wider type: a.astype(np.int64) * 2 gives [200].
  9. Your code does if pred == y: with two arrays and fails with “truth value of an array is ambiguous”. Give two ways to fix it, depending on what you mean.
    Show answerIf you mean “every entry matches”, use (pred == y).all() or np.array_equal(pred, y). If you want the fraction of matches (the accuracy), use (pred == y).mean(). For float arrays that should match approximately, use np.allclose(pred, y).

Next: P2.3 gives the broadcasting rule and einsum the full treatment; P2.4 plots arrays with Matplotlib; P2.6 shows that PyTorch tensors work the same way, with gradients and GPUs added.

Key takeaways

  • An ndarray is a block of numbers of one dtype with a shape. Its size is the product of the shape, nbytes is size times itemsize, and a float64 takes 8 bytes per number.
  • A Python loop spends time on every element (looking up the type, calling the operation, creating a number object). A NumPy call runs one compiled loop over numbers stored side by side. The Big-O is the same, the constant is much smaller: measure it with a timer on your own machine.
  • A basic slice such as A[0:2, 1:3] is a view that shares memory with A. Integer-array indexing, boolean masks and .copy() give independent copies, but assigning through them (A[mask] = 0) writes into A. np.shares_memory tells you which you have.
  • In a reduction, the axis you name is the one that disappears: A.sum(axis=0) adds down the columns, A.sum(axis=1) adds along the rows, and keepdims=True keeps the collapsed axis with size 1.
  • reshape keeps the reading order, a (n,) array is not a (n,1) array, and ravel can return a view while flatten always copies.
  • Watch the dtype: int8 wraps around silently, an int array truncates a float you assign into it, / gives floats while // floors, and == on floats needs np.isclose or np.allclose.
  • @ is the matrix product and * is elementwise. np.where, boolean masks, np.stack, np.concatenate, np.sort and np.argsort are the everyday tools around them.
Found a mistake? Tell us