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) orint64(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 examples with features each (P1.B5, P1.B14). A batch of examples is a slice of rows.
Creating arrays
| You want | Write |
|---|---|
| From a list | np.array([[3, 1], [4, 1]]), shape (2, 2) |
| Zeros, ones, one value | np.zeros((2, 3)), np.ones(3), np.full((2, 2), 7.5) |
| The identity matrix | np.eye(3): 1 on the diagonal, 0 elsewhere |
| Evenly spaced by a step | np.arange(2, 11, 3) gives [2 5 8] (stop excluded) |
| Evenly spaced by a count | np.linspace(0, 1, 5) gives [0. 0.25 0.5 0.75 1.] (end included) |
| Same shape as another | np.zeros_like(A) |
| Random numbers | rng = 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.
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:
- 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. - 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
float64array stores 8 bytes per number, side by side. Less memory means more numbers fit in the fast memory close to the processor. - NumPy loops in compiled code.
x * xis 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.
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 (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 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 . 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.
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 - qsubtracts 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 “subtractqfrom 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]is140.
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 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]orA[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.
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 asA[A > 8], return copies. - The transpose
A.Tis always a view.reshapeandravelgive 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] = 0changesA.
np.shares_memory(a, b) says whether two arrays overlap in memory. The cell below shows all four cases.
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 to , 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.
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 , 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=Truethe collapsed axis stays with size 1:(1, 4)and(3, 1). The result can then take part in further arithmetic withAwithout 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 examples and 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, . 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.
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 isTrue(a copy, shape(count,)). - Assign:
s[s < 0] = 0sets those entries to 0 in place (this one writes intos). - Count:
(s > 0).sum()counts theTruevalues (Truecounts 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 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 largest values. (argsort is not stable by default; pass kind="stable" if equal values must keep their order.)
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 largest of values you do not need to sort all of them. np.argpartition(s, -k)[-k:] puts the largest positions at the end (in no particular order) with less work than a full sort when is large. Then sort just those 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] = 99also changesa(a view). Fix:b = a[1:3].copy(). The same goes forb = a: one array with two names, so useb = a.copy().x[0] = 2.9on an int array stores2, silently, andx += 0.5raisesUFuncTypeError. Fix: make the array float (astype(float)).a == bon float arrays compares rounded numbers exactly, andif a == b:raises an error. Fix:np.allclose(a, b)ornp.array_equal(a, b).s > 0 & s < 1fails, 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 andreshapeone of them.int8arithmetic near 127 wraps to a negative number. Fix: use a wider dtype.- Python’s
sum(x)andfor 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 , which is x @ x. For , A.sum(axis=0) is and A.sum(axis=1) is . Standardizing a data matrix gives with .
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
Why is
(x * x).sum()on a large NumPy array usually much faster than a Pythonforloop that adds upv * v?Both versions do about multiplications and additions, so the Big-O is the same and no operations are skipped. The speed comes from a smaller constant: one compiled loop over packed numbers instead of interpreter work per element. NumPy runs on the CPU by default, not on a GPU.
With
a = np.arange(5), you runb = a[1:3]and thenb[0] = 99. What isaafterwards?A basic slice of an array shares memory with the original, so
b[0]is the same memory asa[1]. Lists behave differently, which is where the copy belief comes from. Assigning to a slice is allowed. The slicebstarts at the original position 1, so position 0 ofais not touched.For
Aof shape(3, 4), what is the shape ofA.sum(axis=0)?The axis you name disappears. Axis 0 has length 3, so it collapses and the 4 column sums remain: shape
(4,). The shape(3,)is whataxis=1gives. The shape(1, 4)appears only withkeepdims=True. A single number comes fromA.sum()with no axis.Which of these returns a copy of part of
Arather than a view?Boolean masks (and integer-array indexing) build a new array with copied values. A slice of rows, a column slice and the transpose are all views of the same memory.
What does
np.array([1, 2, 3], dtype=np.int64) // 2return?The operator
//is floor division, so 1, 2 and 3 divided by 2 give 0, 1 and 1. The result with decimals[0.5 1. 1.5]is what/gives. Rounding to nearest would give[1 1 2], but//rounds down. Dividing integer arrays is allowed.In NumPy,
np.array([127], dtype=np.int8) + np.int8(1)gives[-128]. What does this show?An 8-bit integer holds to , so does not fit and wraps to (P1.G1). It is the defined behaviour of the dtype, not a bug. No floating point is involved, and the sign is part of the 8 bits.
Exercises
- An array has shape
(5, 4, 3)and dtypefloat32. What are itsndim,sizeandnbytes?Show answer
ndimis 3,sizeis , andnbytesis bytes (4 bytes perfloat32). - What does
np.arange(2, 11, 3)return, and what doesnp.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). - With
B = np.arange(12).reshape(3, 4), what isB[1:, ::2]and what is its shape?Show answer
[[ 4 6] [ 8 10]], shape(2, 2): rows 1 and 2, columns 0 and 2. - A data array
Xhas 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 withkeepdims.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. - 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 answer
L.argmax(axis=1)gives[0 2]andL.max(axis=1)gives[2. 1.5]. - Write the ReLU of
s = np.array([-2., 0.5, 3., -0.1])two ways, and count the positive entries.Show answer
np.maximum(s, 0)andnp.where(s > 0, s, 0.0)both give[0. 0.5 3. 0. ]. The count is(s > 0).sum(), which is 2. - With
x = np.array([3., 4.]), write the length without a loop in two ways.Show answer
np.sqrt((x * x).sum())andnp.sqrt(x @ x), both 5.0. a = np.array([100], dtype=np.int8). What isa * 2, and how do you get 200?Show answer
[-56], because 200 does not fit in anint8and wraps (). Use a wider type:a.astype(np.int64) * 2gives[200].- 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 answer
If you mean “every entry matches”, use(pred == y).all()ornp.array_equal(pred, y). If you want the fraction of matches (the accuracy), use(pred == y).mean(). For float arrays that should match approximately, usenp.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.