A model predicts four house prices, and the true prices are known. In code the predictions come out as a column, shape (4, 1), and the true prices are a plain list, shape (4,):
The errors are and the mean squared error is . But the one-line code ((y_pred - y) ** 2).mean() prints , with no error and no warning. Why? Because NumPy does not subtract the two lists entry by entry. It first stretches them to a common shape and produces a table of differences. This lesson is about shapes: how to read them, how to change them without scrambling the data, and the one rule (broadcasting) that decides what happens when shapes differ. Earlier lessons pointed here several times: a + 10 adding a number to every entry, NumPy stretching arrays in *, np.dot on arrays with more than two axes, and the .T/swapaxes/permute family. Along the way they also used (n,) against (n, 1) and reshape(-1, 1). Here they all get an answer.
Arrays with any number of axes
P1.B1 gave vectors, P1.B5 gave matrices. They are the first members of one family, the arrays, and each is described by its shape: the list of the sizes along each of its axes (an axis is one direction in which you can move along the array).
- A single number, a scalar: shape
(), no axes. - A vector with entries: shape
(n,), one axis. - A matrix with rows and columns: shape
(m, n), two axes. The grayscale picture of the digit in P1.B5 is(28, 28). - A 3-axis array: shape
(a, b, c). A colour picture has height, width and three colour channels:(H, W, 3). - And so on. A batch of colour pictures is
(N, H, W, 3): four axes.
Three numbers describe any array. The shape (the sizes), ndim (the number of axes, which is the length of the shape) and size (the total number of entries, which is the product of the shape). In P1.B1 you met the warning that ndim is not the “dimension” of a vector; the same happens here: a vector with 784 entries has ndim and size .
In machine-learning code such an array is called a tensor. That is the only meaning of the word you need on this site: an array of numbers with any number of axes. (In mathematics and physics “tensor” is stricter: it names an object that transforms in a particular way when you change coordinates. Every such object can be written down as an array of numbers, but not every array of numbers is such an object, so do not read more into the word than “N-D array” when you see it in ML.)
Our running example is a small array with three axes, T = np.arange(24).reshape(2, 3, 4). Think of 2 sheets, each with 3 rows and 4 columns:
T[0] = [[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
T[1] = [[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]
Its shape is (2, 3, 4), ndim is and size is . The array (B, T, d) of token embeddings and the array of images are the same kind of object with different meanings for the axes: the meaning is yours to remember, NumPy only knows the sizes.
Axes, negative axes and indexing
Axes are numbered from 0, in the order the shape is written. In (2, 3, 4), axis 0 has size 2 (the sheets), axis 1 has size 3 (the rows) and axis 2 has size 4 (the columns). A negative number counts from the end: axis -1 is the last axis, -2 the one before it. So T.shape[-1] is . Negative axes are the way to say “the feature axis, whatever the number of leading batch axes”, and that is why they are everywhere in model code.
To pick an entry you give one index per axis, T[1, 2, 3] is (sheet 1, row 2, column 3, counting from 0). If you give fewer indices, the axes you left out stay whole: T[1, 2] is the row [20 21 22 23]. A slice : keeps a whole axis, and ... (an “ellipsis”) means “all the axes not mentioned”.
The shape after indexing follows three simple rules:
- An integer index drops its axis:
T[0].shapeis(3, 4). - A slice keeps its axis, even if it has length 1:
T[0:1].shapeis(1, 3, 4). None(also writtennp.newaxis) adds a new axis of size 1:T[:, None].shapeis(2, 1, 3, 4).
For T (shape (2, 3, 4)) these give: T[:, 1].shape is (2, 4), T[:, 1:2].shape is (2, 1, 4) and T[..., 0].shape is (2, 3). The same holds for the data matrix of P1.B5 (5 houses, 3 features, X.shape is (5, 3)): X[1], one house, has shape (3,) and X[1:2] has shape (1, 3); the column X[:, 0] of areas has shape (5,) and X[:, 0:1] has shape (5, 1). That last pair is how you get a column that is really a column.
Adding up along an axis
A reduction turns many numbers into fewer: sum, mean, max, argmax and more. Called with no axis it uses every entry and returns one number. Called with axis=k it works along axis k: for each position of the other axes it adds up the entries as the index runs through its range, and axis k disappears from the shape.
Take (shape (2, 3)). Then M.sum(axis=0) is [5 7 9] and M.sum(axis=1) is [6 15].
The confusing part is the word “axis 0 means down the rows”. It means that the addition walks down along axis 0, the axis the rows are stacked on, so each column is added up into one number and the result has one number per column, written across. It does not mean that the result is arranged down the rows. A reliable way to remember: the axis you name is the one that vanishes, and the shape tells you what is left. Use the widget to see it on a array.
Things to try:
- axis=0: each column (e.g. ) becomes one number. The shape
(3, 4)becomes(4,): the 3 vanished. - axis=1: each row () becomes one number:
(3, 4)becomes(3,). Notice that a result with shape(3,)is a plain 1-D array: it is neither a row nor a column. - Tick keepdims. The summed axis stays with size 1:
(1, 4)and(3, 1). Now the result still has the same number of axes asG, which will matter in a moment. - no axis: all 12 entries add to 78, shape
().
For the 3-axis array T: T.sum(axis=1).shape is (2, 4), T.sum(axis=-1).shape is (2, 3), and several axes at once work too: T.sum(axis=(0, 2)).shape is (3,). The same works for mean: for the 5-house matrix of P1.B5, X.mean(axis=0) is one mean per feature, [102, 2.6, 20]. And argmax(axis=1) gives one index per row.
keepdims=True is more than a taste. A result that keeps its axes can be combined straight back with the original array by broadcasting (the next big section), as in “subtract each row’s mean from that row”.
Reshape: same numbers, new cutting
Reshape changes how the same entries are cut into axes. It does not change, add or reorder any number. NumPy reads the entries in row-major order (also called C order): last axis changes fastest, like reading a page line by line. Start with in a row, cut into 2 rows of 3, or 3 rows of 2:
A = np.arange(6).reshape(2, 3)
[[0 1 2]
[3 4 5]]
A.reshape(3, 2)
[[0 1]
[2 3]
[4 5]]
Three rules. The total size must stay the same (2·3 = 3·2 = 6; A.reshape(4, 2) fails with a ValueError, message like “cannot reshape array of size 6 into shape (4,2)”). One of the new sizes may be -1, which means “work this one out”: A.reshape(3, -1) is (3, 2) and A.reshape(-1) is the flat vector (6,). And the order is kept: the flat reading of a reshaped array is the same list as before.
This is how a image becomes a vector of 784 entries (P1.B1, P1.B5), and how a vector of 6 becomes a column: v.reshape(-1, 1) has shape (6, 1). Two other ways to make that column are v[:, None] and np.expand_dims(v, 1); np.squeeze removes axes of size 1 (np.zeros((1, 3, 1)).squeeze().shape is (3,)).
Reshape is not transpose
This is the most common shape mistake. A.reshape(3, 2) and A.T both have shape (3, 2), but the entries are different:
A.reshape(3, 2) A.T
[[0 1] [[0 3]
[2 3] [1 4]
[4 5]] [2 5]]
The transpose (P1.B10) really flips the matrix: the row becomes a column. A reshape keeps reading order and just re-cuts the line. If you reshape when you meant to transpose, the shapes agree, no error appears, and the numbers are scrambled. The same trap hides in images: if a picture is stored channels-first (C, H, W) and you reshape it to (H, W, C) instead of permuting the axes (next section), you get a picture of noise with a perfectly legal shape.
ravel() and flatten() both give the flat 1-D version (A.ravel() is [0 1 2 3 4 5]). flatten always returns a copy; ravel and reshape return a view of the same memory when they can, and a copy when they cannot, so a change to the result may or may not change the original. Keep the rule: do not rely on either; copy explicitly (.copy()) if you plan to change the result.
Joining arrays: stack and concatenate
Two functions join arrays, and the difference is exactly one axis. np.stack([x, y]) joins arrays of the same shape along a new axis: two (3, 4) arrays give (2, 3, 4). np.concatenate([x, y], axis=1) joins along an axis that already exists: two (3, 4) arrays give (3, 8) (and axis=0 gives (6, 4)). Use stack to make a batch out of single examples.
Go deeper Views and copies: when does a change leak?
A view shares the same memory as another array, so writing through one is visible in the other; a copy has its own memory. After A = np.arange(6).reshape(2, 3) the transpose A.T is a view (np.shares_memory(A, A.T) is True) because NumPy only changes how it reads the same entries. A.T.ravel() has to put the entries in a new order, so it is a copy. For a simple array like A, A.ravel() and A.reshape(3, 2) are views: b = A.ravel(); b[0] = 99 changes A too.
When a view is possible is a detail of how the array is laid out in memory, and you should not rely on it either way. The safe habits: use .copy() when you need your own array, and never write into the result of a reshape, ravel or transpose unless you want the original changed too. PyTorch has the same idea (its docs describe permute as returning a view).
Transposing many axes
For two axes .T swaps rows and columns (P1.B10). For more axes there are more ways to rearrange, and three tools cover them:
.Treverses all the axes.T.T.shapeis(4, 3, 2), andT.T[3, 2, 1]equalsT[1, 2, 3]. For a 1-D array it does nothing, which is the trap from P1.B10.np.transpose(a, axes)puts the axes in any order you list: entry of the tuple says which old axis goes in place .np.transpose(T, (1, 0, 2)).shapeis(3, 2, 4).np.swapaxes(a, i, j)swaps just two.T.swapaxes(0, 2).shapeis(4, 3, 2), andswapaxes(-1, -2)transposes the last two axes of any stack of matrices.
PyTorch’s x.permute(...) is the counterpart of np.transpose(x, ...): it takes the new order of all the axes. PyTorch’s x.transpose(i, j) swaps two, like swapaxes. (PyTorch’s own documentation says that .T on tensors that do not have exactly two axes, used to reverse the shape, is deprecated and will become an error; write permute or transpose instead.)
The classic use is the channels question (P5.1). A batch of 8 colour pictures of pixels can be stored channels-last, (8, 32, 32, 3), which is (N, H, W, C), or channels-first, (8, 3, 32, 32), which is (N, C, H, W). Moving between them is a permutation of the axes, not a reshape: x.transpose(0, 3, 1, 2) in NumPy (or x.permute(0, 3, 1, 2) in PyTorch) turns (8, 32, 32, 3) into (8, 3, 32, 32), and transpose(0, 2, 3, 1) goes back. PyTorch’s Conv2d layer expects channels-first input (N, C, H, W) (its documentation says so), while the Keras Conv2D layer takes channels-last (batch, height, width, channels) unless its data_format setting says otherwise (its documentation says that too). Libraries differ, so check the layout before you feed data into a layer.
Broadcasting: stretching the smaller array
P1.B2 noted that NumPy accepts np.array([1, 2, 3]) + 10 and adds 10 to every entry, and that np.array([1, 2]) + np.array([1, 2, 3]) fails with the error “could not be broadcast together”. Both are the same mechanism, called broadcasting: a rule that decides when two arrays of different shapes can be combined entry by entry, and how. The idea is to stretch the smaller array until its shape matches, like a stamp that repeats a row down a page.
The rule, as NumPy’s documentation states it (here in four steps):
- Align the two shapes from the right. Compare the last axes first, then the next to last, and so on.
- A missing leading axis counts as size 1. If one array has fewer axes, imagine 1s written on the left of its shape.
- On each axis the two sizes must be equal, or one of them must be 1. Otherwise NumPy raises a
ValueError. - The result has the larger size on each axis (the one that is not 1). An axis of size 1 is stretched to match.
The widget applies exactly this rule.
Things to try:
- Start with the first preset, (3,4) + (4,): a matrix plus a vector. The vector has one axis, so a leading 1 is added:
(1, 4). Axis-1is against : equal. Axis-2is against : B is stretched down to 3 rows. The result is(3, 4), and every row of A got the same added. - (3,4) + (3,1): now B is a column. Axis
-1is against , so each entry of the column is repeated across the row. This adds one number to each row of A. - (3,1) + (1,4): both arrays are stretched, and the result is
(3, 4): every pairing of a number from A with a number from B (the status warns about this). - (2,3) + (2,): the last axes are and . Not equal and neither is 1: a red cross, no result, and NumPy’s error. (3,) + (4,) fails the same way. The fix for the first is to make B a column of shape
(2, 1). - bug: (4,1) − (4,): this is the opening puzzle. B is treated as
(1, 4); both are stretched and the result is(4, 4). There is no error: both shapes are legal. - (3,) + scalar: a scalar has no axes, so it is treated as size 1 on every axis: this is
a + 10. (2,3,4) + (3,1): B is treated as(1, 3, 1)and stretched on two axes; the result has 3 axes. - Use the steppers to make your own pair. Try to predict each result shape before you look.
Intuition
Picture the smaller array as a stamp. A row of numbers, (4,), is stamped down on every row of a (3, 4) page; a column, (3, 1), is stamped across on every column. If both are small, as in (3, 1) and (1, 4), each one is stamped in its own direction and the two together fill a whole page, like a multiplication table.
The picture has limits. A stamp makes real copies; NumPy does not (see below). The rule is only about sizes, never about meaning: NumPy will gladly stretch a column of predictions against a row of targets if the sizes allow it, whether or not that makes sense for your problem. It checks that the sizes can be combined, not that you wanted them combined.
Math
Write the aligned shapes as and (pad the shorter one with 1s on the left). They are compatible when for every either , or , or , and the result shape has (for sizes of at least ; an axis of size against gives ).
For a matrix and a vector this is the matrix identity
where is the column of all ones: the outer product is the matrix whose every row is . Adding a column is . Adding a column and a row gives the matrix with entries .
Code
import numpy as np
A = np.arange(12).reshape(3, 4) # shape (3, 4)
b = np.array([10, 20, 30, 40]) # shape (4,)
c = np.array([[100], [200], [300]]) # shape (3, 1)
print(A + b) # b is added to every row
print(A + c) # c is added to every column
print((c + b).shape) # (3, 4): a (3, 1) and a (4,) fill a tableA + b is [[10 21 32 43] [14 25 36 47] [18 29 40 51]], and A + c is [[100 101 102 103] [204 205 206 207] [308 309 310 311]].
Two examples from machine learning
A bias for the whole batch. A layer’s output on a batch (P1.B6) is , shape (N, h), and the layer then adds its bias (P1.B5), shape (h,), to every example. That is Z + b: (N, h) and (h,) are compatible, and the vector is added to every row. For the product of P1.B10, , and the result is .
Centering the columns. For the 5-house matrix X of P1.B5, X - X.mean(axis=0) subtracts each column’s mean from that column: (5, 3) and (3,). The first house becomes , and every column now adds up to (up to rounding). Subtracting means is how data is centred before PCA (P3.C3) and how normalisation layers (P4.19) start.
Where keepdims earns its keep
Dividing each row of by its own sum should give rows that add to 1. Written with keepdims=True it does: S / S.sum(axis=1, keepdims=True) divides (3, 3) by (3, 1), and every row sums to 1. Written without, S / S.sum(axis=1) divides (3, 3) by (3,), which is treated as a row (1, 3): it divides each column by the vector , rows now sum to , and no error is raised because the matrix happens to be square. For a (5, 3) matrix the same slip fails with an error, which is the lucky case. This is the same trap as the opening puzzle. The same trick is how softmax is computed along the last axis of a score array: subtract s.max(axis=-1, keepdims=True), exponentiate, divide by e.sum(axis=-1, keepdims=True) (P7.4, P1.G2).
The silent shape bug
Back to the opening puzzle. The shape (n, 1) minus (n,) is legal and gives (n, n): entry of the result is , every prediction against every target. For and the numbers above, the squared differences average to instead of . The model would still train, just on the wrong loss (PyTorch’s mse_loss can print a warning about a size mismatch like this one, but you should not rely on that). The fixes are to make the shapes agree: y_pred.ravel() or y_pred.squeeze(1), or y.reshape(-1, 1).
The defence is a habit: print the shapes, and assert them (assert y_pred.shape == y.shape) at the place where two arrays meet.
Go deeper Broadcasting does not copy: stride zero
Conceptually, broadcasting stretches the smaller array. In memory, NumPy does not make copies. It reads the one row again and again by using a stride of zero bytes along the stretched axis. You can see it with np.broadcast_to: for b = np.arange(4.0), which holds 8-byte numbers, bb = np.broadcast_to(b, (3, 4)) has bb.strides equal to (0, 8): stepping down a row moves by 0 bytes, stepping along a row moves by 8. It shares memory with b (np.shares_memory(b, bb) is True) and is read-only. Broadcasting a small array against a huge one therefore costs almost no extra memory for the small one (the result of the operation is a new, full-size array, of course).
Shape puzzles
Predicting a shape from a line of code is a skill you build by practice. The puzzles use the arrays and the operations of this lesson. Think first, then choose.
Batched matrix products
P1.B6 multiplied two matrices. In real code you multiply stacks of matrices. NumPy’s @ (and PyTorch’s) follow the rule: for arrays with more than two axes, the last two axes are the matrices, and all the leading axes are treated as a batch that is broadcast by the rule above. So for each position in the batch a (p, q) matrix meets a (q, r) matrix and gives a (p, r) matrix.
(2, 5, 3) @ (3, 7)is(2, 5, 7): a batch of two matrices, each multiplied by the same matrix. This is a layer on a batch of sequences of tokens:X @ WwithXof shape(B, T, d).(2, 3, 4) @ (2, 4, 5)is(2, 3, 5): a different matrix for each item of the batch.(2, 1, 3, 4) @ (5, 4, 6)is(2, 5, 3, 6): the batch axes(2, 1)and(5,)broadcast to(2, 5).- With a 1-D operand it works like P1.B6:
(3, 4) @ (4,)is(3,), and(4,) @ (4,)is a plain number. - Attention scores (P7.3): queries
Qof shape(B, h, T, d_k)and keysKof the same shape,Q @ K.swapaxes(-1, -2)has shape(B, h, T, T): for every example and every head, all token-against-token dot products at once. The softmax then runs over the last axis (axis=-1), so each row of scores becomes a set of weights adding to 1.
The inner sizes must still agree and the batch sizes must broadcast: (2, 3, 4) @ (3, 4, 5) fails because the batch axes and clash. Do not use np.dot for this. For more than two axes, np.dot does something different (it combines every item of the first array with every item of the second): np.dot of a (2, 3, 4) and a (2, 4, 5) array has shape (2, 3, 2, 5), not (2, 3, 5). This is why P1.B6 recommended @.
Go deeper einsum: naming the axes instead of remembering them
np.einsum writes a product by naming each axis with a letter. The rule: a letter that appears in the inputs but not after the arrow is summed over; letters after the arrow are kept. Matrix product: np.einsum('ij,jk->ik', A, B) equals A @ B ( is summed). Transpose: np.einsum('ij->ji', A). Sum over rows: np.einsum('ij->j', A) equals A.sum(axis=0). Outer product: np.einsum('i,j->ij', u, v). The attention scores above are np.einsum('bhtd,bhsd->bhts', Q, K): batch b and head h are kept, d is summed, and the two token axes t and s stay apart. Many people find it easier to read than a chain of swapaxes and @. P2.3 teaches it in depth.
Habits that prevent shape bugs
- Print
.shapeof every array the first time you write a step. A shape you did not expect is a bug found early. - Assert shapes where two arrays meet:
assert y_pred.shape == y.shape. - Write the axes in a comment:
# X: (B, T, d). NumPy does not know what the axes mean; you must. - Make columns on purpose with
v[:, None]orreshape(-1, 1), and usekeepdims=Truewhen the result will be combined with the original array. - When a result seems the right shape but wrong, ask: did I reshape where I should have transposed?
- Broadcast silently only when you meant to. When in doubt, write the shape you expect on paper first.
Try it in NumPy
The first cell covers shapes, indexing, reductions, reshape against transpose, and joining arrays.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
What to expect: T.shape is (2, 3, 4) with ndim 3 and size 24; the shape of each indexed form is the one in the text; A.reshape(3, 2) is not equal to A.T; and the failing reshape prints a ValueError (its exact wording can differ between NumPy versions). Change a line and predict the shape before you run it.
The second cell is about broadcasting, the silent bug and batched products.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
What to expect: the first two lines show A + row and A + column, then the shape (3, 4) of the outer-style sum. The two failures print operands could not be broadcast together with shapes ... (the wording and spacing can differ between versions). The opening puzzle prints (4, 4), then , then . The row sums with keepdims are (up to rounding); without it they are . The last block prints (2, 5, 7), (2, 3, 5, 5) and (2, 3, 2, 5).
Where you will meet it next
- The forward pass with a batch (P4.5, P4.10). A layer on
(N, d)data isX @ W.T + b, shape(N, h), with the bias broadcast. - Embeddings (P4.21) and attention (P7.3 to P7.5).
(B, T, d)activations, scores of shape(B, h, T, T), softmax over the last axis, and batched@. - Normalisation (P4.19). Batch, layer, group and RMS normalisation differ in which axes they average over, written as
mean(axis=..., keepdims=True). - Images (P5.1 to P5.5).
(H, W, C)for one picture,(N, C, H, W)or(N, H, W, C)for a batch, and the permutation between them. - The libraries. P2.2 and P2.3 (NumPy arrays, broadcasting in practice,
einsum) and P2.6 (PyTorch tensors) teach the library functions in full; this lesson gives the ideas those lessons use. - The map (P1.B15). The next lesson puts and attention on one map, with these shapes.
Common mistakes
Check your understanding
Ahas shape(5, 3)andbhas shape(5,). What doesA + bdo?The shapes are aligned from the right, so the last axes are compared first: 3 against 5. They are different and neither is 1, so there is no broadcast. To add
b[i]to rowiyou needbas a column,b[:, None](shape(5, 1)). An array of shape(5,)or(3, 5)is not what any broadcast of these shapes would give.y_predhas shape(8, 1)andyhas shape(8,). What is the shape ofy_pred - y?yis treated as(1, 8). Against(8, 1)both axes are compatible (one side is 1 each time), so both arrays are stretched and the result is(8, 8): every prediction minus every target. That is why the bug raises no error. The result is not(8,)or(8, 1), because both arrays are stretched.xhas shape(2, 3, 4). What is the shape ofx.sum(axis=1, keepdims=True)?Axis 1 (size 3) is added up, and
keepdims=Trueleaves it behind with size 1. Withoutkeepdimsthe shape would be(2, 4). The(1, 3, 4)shape would come from axis 0 and(2, 3, 1)from axis 2.A = np.arange(6).reshape(2, 3), soAis[[0 1 2] [3 4 5]]. What isA.reshape(3, 2)?Reshape keeps the entries in reading order, 0, 1, 2, 3, 4, 5, and cuts them into 3 rows of 2.
[[0 3] [1 4] [2 5]]is the transpose, which is a different operation;[[5 4] [3 2] [1 0]]reverses the order and[[0 2] [4 1] [3 5]]scrambles it. Reshape does neither.xhas shape(5, 3). Which expression has shape(5, 1)?The slice
0:1keeps the column axis with length 1, and:keeps all 5 rows.x[:, 0]uses an integer, which drops the axis (shape(5,)).x[0:1]is the first row kept as a row,(1, 3), andx[0]is the first row as a 1-D array,(3,).Xhas shape(4, 10, 16)(batch, tokens, features) andWhas shape(16, 8). What is the shape ofX @ W?The last two axes of each array are the matrices:
(10, 16) @ (16, 8)is(10, 8), and the leading batch axis of size 4 is kept, with the sameWused for each of the 4 items.@accepts arrays with more than two axes.A batch of images has shape
(8, 32, 32, 3)(channels last). What turns it into the channels-first shape(8, 3, 32, 32)without scrambling any picture?Moving an axis needs a permutation of the axes: the new axes are old axes 0, 3, 1, 2. A reshape has the right shape but cuts the numbers in reading order, so the pixels and channels get mixed up.
x.Treverses all four axes, giving(3, 32, 32, 8), andsumremoves the channel axis.
Exercises
- For
np.zeros((4, 5, 6))give the shape,ndimand size.Show answer
Shape(4, 5, 6),ndim3, size . - For
x = np.zeros((4, 5, 6))give the shapes ofx[2],x[:, 2],x[..., 2],x[:, 2:3]andx[None].Show answer
(5, 6),(4, 6),(4, 5),(4, 1, 6)and(1, 4, 5, 6). The integer indices drop an axis, the slice2:3keeps one, andNoneadds one. - Which of
x.reshape(20, -1),x.reshape(-1, 10)andx.reshape(7, -1)work for the samex(120 entries)?Show answer
The first gives(20, 6)and the second(12, 10). The third fails: is not a whole number. - Give the shapes of
x.sum(axis=0),x.sum(axis=(0, 2))andx.sum(axis=1, keepdims=True).Show answer
(5, 6),(5,)and(4, 1, 6). - Give the result shape, or say it fails: (a)
(5, 1, 4) + (3, 1), (b)(2, 3) + (3, 2), (c)(8,) + (8, 1), (d)(4, 1, 1) + (3, 1).Show answer
(a)(5, 3, 4):(3, 1)is treated as(1, 3, 1). (b) fails: the last axes are 3 and 2. (c)(8, 8): the silent-bug pattern. (d)(4, 3, 1). Ahas shape(3, 4)andbhas the three numbers in a 1-D array.A + bfails. Write the fix so that is added to row .Show answer
A + b[:, None](orb.reshape(-1, 1)). The column has shape(3, 1)and is stretched across the 4 columns.- A loss function receives
y_predof shape(6, 1)andyof shape(6,). Give two correct ways to compute the squared errors, each of shape(6,), and an assertion that would have caught the mistake.Show answer
(y_pred.ravel() - y) ** 2or(y_pred[:, 0] - y) ** 2; or makeya column and keep(6, 1). The assertion:assert y_pred.shape == y.shape(it fails with(6, 1)against(6,)). Xis an data matrix. Write one line that subtracts each column’s mean, and one that divides each column by its standard deviation after that. What shape does the mean have, and doeskeepdims=Truechange the result?Show answer
Xc = X - X.mean(axis=0)andXs = Xc / Xc.std(axis=0). The mean has shape(d,); withkeepdims=Trueit is(1, d)and the result is the same, because both are stretched down the rows.- Normalise the rows of so each adds to 1. What is the first row?
Show answer
S / S.sum(axis=1, keepdims=True); the first row is . - What is the shape of
np.zeros((2, 1, 3, 4)) @ np.zeros((5, 4, 6))?Show answer
(2, 5, 3, 6): the matrices are(3, 4) @ (4, 6)giving(3, 6), and the batch axes(2, 1)and(5,)broadcast to(2, 5). - Queries and keys both have shape
(2, 3, 5, 4)(batch, heads, tokens, head size). Write the scores, give their shape, and say along which axis the softmax is taken.Show answer
Q @ K.swapaxes(-1, -2)has shape(2, 3, 5, 5). The softmax is taken over the last axis,axis=-1, so each token’s row of scores adds up to 1. - Pictures are stored as
(N, C, H, W)and a library wants(N, H, W, C). Give the NumPy line.Show answer
x.transpose(0, 2, 3, 1). A reshape would keep the shape but scramble the pixels. - Code: show that
np.stackandnp.concatenatediffer by one axis, using two arrays of shape(2, 3).Show answer
np.stack([a, b]).shapeis(2, 2, 3);np.concatenate([a, b]).shapeis(4, 3)and withaxis=1it is(2, 6). Stack makes a new axis, concatenate uses an existing one. - Challenge: for a vector
vof length 3 give one expression that builds the table of all differences . Check it with .Show answer
v[:, None] - v[None, :](shapes(3, 1)and(1, 3)). For the rows are , and .