You have 3 points on a map and 2 shops. You want the table of squared distances: 3 rows, 2 columns, no for loop. And later you want the scores that say how well each of 5 queries matches each of 6 keys, for a whole batch at once, written in one short line that you can check by reading it.
Both jobs are the same kind of problem: combine arrays so that every row meets every column, and keep track of which axis is which. P1.B14 taught the rule for broadcasting and P2.2 taught arrays and axis operations. This lesson is the practice: the patterns that real ML code is full of, the bugs that go with them, and einsum, a notation that writes axes by name. (P1.A3 promised it: np.einsum('i,i->', a, b) is . You will see why.)
Broadcasting in one paragraph
To combine two arrays of different shapes, NumPy aligns the shapes from the right, treats a missing leading axis as size 1, and requires each pair of sizes to be equal or one of them 1; a size of 1 is stretched to match. Otherwise it raises a ValueError. A row (n,) therefore acts like (1, n), a column must be written (n, 1), and no data is copied for the stretching. If any of that is not fresh, P1.B14 has the rule with a visualiser and shape puzzles. From here on we use it.
Patterns you will write again and again
Every pattern below is one line, has no loop, and is checked by the shapes. The running data is a small table X of shape (4, 3): 4 people, 3 features (height in cm, weight in kg, age in years).
Centre and standardise the columns
The mean of each column is X.mean(axis=0), shape (3,) (the axis you name disappears; P2.2). Subtracting it from X of shape (4, 3) aligns (4, 3) with (3,): the vector is treated as one row and subtracted from every row.
For the data in the code below, the column means are and the column standard deviations are about . Dividing the centred data by them gives standardised columns: mean 0 and standard deviation 1 in each column. The first person becomes about .
# centre: every column now has mean 0
Xc = X - X.mean(axis=0)
# standardise: every column now has std 1
Z = Xc / X.std(axis=0)
Why do this? Features measured in different units (centimetres, kilograms, years) have very different sizes, and many methods behave badly when one feature is simply bigger than another (P3.C3 for PCA, P1.F3 for gradient descent). Two cautions. NumPy’s std divides by by default (ddof=0), while many statistics tools divide by , so state which you mean. And a constant column has standard deviation 0, so you divide and get nan; the usual fix is to divide by std + eps with a tiny eps such as 1e-8. When you standardise a test set, reuse the mean and standard deviation of the training set (P3.A11 explains why).
Normalise each row, and why keepdims is not optional
To make each row have length 1 you divide each row by its own norm. The norms come out as a flat vector of shape (3,) for a (3, 2) matrix, but you need them as a column (3, 1) so that each one is stretched across its row:
# shape (3, 1), not (3,)
norms = np.linalg.norm(R, axis=1, keepdims=True)
unit_rows = R / norms
For R = [[3, 4], [6, 8], [1, 0]] the norms are and every row becomes or . Without keepdims=True the norms have shape (3,), which is aligned with the last axis of size 2: the shapes (3, 2) and (3,) clash and NumPy raises an error. That is the lucky case. For a square matrix the clash does not happen, the division goes the wrong way, and nothing warns you (P1.B14 shows it with row sums). The habit: when a reduction will be combined with the original array, use keepdims=True.
Add a bias to a whole batch
A layer’s output for a batch is Z of shape (B, h) (batch size , outputs), and its bias is b of shape (h,). Z + b adds the bias to every example. The mirror image, one number per example (say a weight for each row), needs a column: w[:, None] * Z with w of shape (B,).
Tables of all pairs: outer products and differences
To combine every entry of a with every entry of b, make one of them a column and the other a row. For v = [1, 2, 4]:
# (3, 1) and (1, 3) -> (3, 3): every difference
v[:, None] - v[None, :]
# the outer product: every product
v[:, None] * v[None, :]
The difference table is and the product table is . Both arrays are stretched, which is a case where that is exactly what you want (P1.B14 showed the same stretching as a bug when it is not what you meant). None and np.newaxis are the same thing.
One-hot encoding by comparison
A class label is an integer such as 2. A one-hot vector for 3 classes is (P6.1). To turn a whole array of labels into one-hot rows, compare a column of labels with a row of class numbers:
labels = np.array([2, 0, 1, 2])
# (4, 1) == (3,) -> (4, 3)
onehot = (labels[:, None] == np.arange(3)).astype(float)
Row is 1 in the column that equals labels[i] and 0 elsewhere, and every row sums to 1. Do not write labels == np.arange(3): that compares labels[i] with class number one by one. If the two lengths differ it raises an error, and if they happen to be equal it silently returns a meaningless array of True and False.
Masks
A mask is an array of True and False with the same shape as the data (or a shape that broadcasts to it) that says which entries to use. Two masks appear in language models (P7.8).
A padding mask: sequences in a batch have different lengths and are padded to a common length . If lengths = [2, 3] and , then np.arange(3)[None, :] < lengths[:, None] compares a row (1, 3) with a column (2, 1) and gives the (2, 3) mask [[True, True, False], [True, True, True]]: position is real if is less than the length.
A causal mask: token may look only at tokens . With i = np.arange(T), i[:, None] >= i[None, :] is a (T, T) array that is True on and below the diagonal (the lower triangle).
Masks are used by np.where(mask, scores, -np.inf): the masked entries become , so after the softmax they get weight exactly 0 and the others still add to 1. If every entry of a row is masked, the row’s maximum is , is nan, and the whole row becomes nan; keep at least one unmasked entry per row. For the scores with the last position masked, the weights are about . The softmax itself is written with keepdims=True (P1.G2 shows the stable form). One more use: the mean of only the entries that pass a condition is (x * mask).sum() / mask.sum(); for x = [3, 1, 4, 1, 5] and x > 1 it is .
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
All pairwise distances
Given points in A (shape (n, d)) and points in B (shape (m, d)), the squared distance between point of A and point of B is . All of them are used by k-nearest neighbours (P3.B1) and k-means (P3.C1). There are two standard ways to compute the whole table.
Way 1: broadcast the differences
Give A a middle axis and B a leading one, subtract, square, and sum over the last axis:
# (n, 1, d) - (1, m, d) -> (n, m, d)
diff = A[:, None, :] - B[None, :, :]
# sum over the feature axis -> (n, m)
D2 = (diff ** 2).sum(axis=-1)
It is easy to read and always accurate. The cost is in diff: it holds numbers. For 3 points and 2 centres in 2 dimensions that is 12 numbers; for , , it is numbers, about 10 GB in 64-bit floats, while the answer D2 has only numbers (80 MB). Broadcasting copies nothing for the inputs, but the intermediate result is full size.
Way 2: the expansion trick
Expand the square: (P1.B3, P1.B4). All the dot products at once are the matrix product A @ B.T (P1.B6), and the squared lengths are one number per point:
D2 = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2 * A @ B.T
Here the biggest array is (n, m), and the work is done by one matrix product, which is fast. For the small example below both ways give the same table, for the points against .
The numerical caveat. The trick subtracts large, nearly equal numbers (P1.G1, P1.G2), so rounding can leave a tiny negative value where the true answer is 0 or very small, for example for two points that are almost the same. A negative squared distance breaks the next step, np.sqrt, which then returns nan. The cure is one line: D2 = np.maximum(D2, 0). In the cell below, 32-bit numbers near 1000 are used on purpose: their squares are around 3 million, where 32-bit floats can only represent steps of 0.25, so the formula’s error (here about 0.5) is huge compared with the true squared distance (about 0.000003). The cell applies the formula to 200 pairs of almost identical points. (The exact count of negative values you see may change a little with the computer and the NumPy build; that some values are negative is the point.)
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Which way to choose? Use the broadcast version when the arrays are small or you want the easiest code to check; use the trick when would not fit in memory. A third way is to process A in chunks of rows. Libraries such as SciPy (scipy.spatial.distance.cdist) and scikit-learn already do this for you.
When broadcasting goes wrong
The danger of broadcasting is that it is permissive: it accepts any shapes whose sizes are equal or 1, whether or not you meant them to combine. P1.B14 showed the headline bug: (n, 1) minus (n,) is an (n, n) table, no error, and a mean squared error of 4.5 instead of 0.75. Three habits catch almost everything.
- Print the shapes of every array the first time you write a line. Print the shape of the result too: if you expected
(n,)and see(n, n), you have found it. - Assert shapes where two arrays meet:
assert y_pred.shape == y.shape, (y_pred.shape, y.shape). An assert costs nothing and turns a silent wrong number into a loud error that shows both shapes. - Write the axes in a comment:
# X: (B, T, d). NumPy does not know what an axis means; you must.
Here are the failure messages you will meet, and what to do with them.
np.ones((2, 3)) + np.ones(2)raisesValueError: operands could not be broadcast together with shapes (2,3) (2,). The last axes are 3 and 2. Make the second a column(2, 1)if you meant one number per row.a += bwhereais(3, 1)andbis(1, 4)raisesValueError: non-broadcastable output operand with shape (3,1) doesn't match the broadcast shape (3,4). In-place operations cannot growa: writea = a + b, a new array.(n, 1) - (n,)works and gives(n, n)(P1.B14): assert the shapes.- A square matrix divided by its row sums without
keepdimsdivides the wrong way (P1.B14): usekeepdims=True. labels == np.arange(k)gives an error, or a meaningless array if the lengths match. Writelabels[:, None] == np.arange(k).
Go deeper np.broadcast_shapes and np.broadcast_to: check without making data
np.broadcast_shapes((4, 1), (4,)) returns (4, 4), and np.broadcast_shapes((5, 1, 3), (4, 1)) returns (5, 4, 3). It takes shapes, not arrays, so you can test a pair of shapes (or write a unit test for the shapes in a model) without allocating anything. When the shapes clash it raises a ValueError whose message begins with shape mismatch: objects cannot be broadcast to a single shape and names the two shapes. np.broadcast_to(a, shape) returns the stretched array as a read-only view whose stride along each stretched axis is 0, so it uses no extra memory; for np.arange(3) stretched to (2, 3) the strides are (0, 8) (8 bytes per 64-bit integer). Call .copy() if you need a writable array. P1.B14 explained the stride-0 idea.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Einsum: name every axis
So far we have kept axes straight by position: “axis 0”, “the last axis”, [:, None]. That works until a line has three or four axes and a matrix product in the middle. Einsum (Einstein summation) lets you give every axis a letter and write down what to do with the letters. It is the same Σ notation you met in P1.A3, with the sum sign left out.
From Σ to letters
The matrix product of P1.B6 is written with a sum:
Look at the indices. and stay on the left, so they label the result. appears twice on the right and not on the left, so it is the one being summed. Einsum writes exactly this, with the inputs on the left of an arrow and the result on the right:
# the same as A @ B
np.einsum('ik,kj->ij', A, B)
Read it aloud: “A has axes and , B has axes and ; the result has axes and .” The letter k is not after the arrow, so it is summed over. The same rule covers the dot product from P1.A3: np.einsum('i,i->', a, b) is , with nothing after the arrow, because every letter is summed and the result is a single number.
The rule has three parts, and the tour below uses all of them. Multiply: entries with the same letter value are multiplied. Sum: letters not after the arrow are added up. Keep: letters after the arrow become the axes of the result, in that order.
A tour of small examples
With a = [1, 2, 3], b = [4, 5, 6], M = [[1, 2, 3], [4, 5, 6]] (shape (2, 3)) and S = [[1, 2], [3, 4]]:
'i->'sums all entries: (a.sum()).'i,i->'is the dot product: (a @ b).'i,j->ij'is the outer product, every pair:[[4 5 6] [8 10 12] [12 15 18]](np.outer(a, b)).'ij->i'sums over , the row sums:[6 15](M.sum(axis=1)).'ij->j'sums over , the column sums:[5 7 9](M.sum(axis=0)).'ij->ji'swaps the axes, the transpose: shape(3, 2)(M.T).'ii->'adds the diagonal, the trace: forS(np.trace(S)).'ii->i'is the diagonal:[1 4]forS(np.diag(S)).'ij,j->i'is matrix times vector:[14 32]forManda(M @ a).'ik,kj->ij'is the matrix product: see the cell below (A @ B).'ij,ij->ij'is the entry by entry product:[[1 4 9] [16 25 36]](M * M).'ij,ij->'multiplies entry by entry, then adds everything: ((M * M).sum()).'i,ij,j->'is with three inputs: for(1, 2),M,a(x @ M @ y).
A letter repeated inside one input ('ii') means “take the diagonal”: the two axes are tied to the same index. The 'ii->' line is the trace, and 'ii->i' keeps the diagonal as a vector.
Now explore. Pick an example, or type your own spec. Each distinct letter gets a size you can change with the small buttons, the inputs are filled with small whole numbers, and you can select any cell of the result to see exactly which input cells are multiplied and which products are added.
Things to try:
- Start with matrix product and select each of the four result cells in turn. For
R[i=0, j=1]the marked cells are the whole first row ofAand the whole second column ofB: . The letterkran over its 3 values, which is why there are 3 products. - Click dot product, then outer product. The dot product has one result cell made from every input cell; the outer product has 6 result cells, each made from one pair and nothing added (no summed letters, so one product per cell).
- Click transpose and select a cell: it is built from a single input cell, nothing is multiplied, the number is only moved.
- Click trace: the matrix has the letter
itwice, so only the diagonal cells are marked. - In batched matrix product, the two slices (
b = 0andb = 1) are separate matrix products; the result cell forb = 1uses only cells of slice 1. - Type
ik,kj(no arrow) and compare withik,kj->ij: the status line explains the rule for the implicit form. Then typeba: the result is the transpose. - Break it on purpose. Type
ij->ijk(a result letter that was never named on the left) andij,jk->ikk(a letter kept twice), and read the messages.
Intuition
Think of a spreadsheet. Each input array is a sheet, and each letter is the name of a row or column dimension. The result is a new sheet. To fill one cell of the result, you let the summed letters run through all their values, take one product per combination, and add. The letters after the arrow pick which cell of the result you are filling.
Why is that useful? Because the line tells you the shapes. In 'bqd,bkd->bqk' you can see that b (batch) is on both inputs and on the result, d is on both inputs only (so it is summed), and q and k come from one input each. You can read the output shape off the spec: batch, then queries, then keys. The same line with @ needs a transpose and a leading-axes rule in your head. The analogy has a limit: einsum is only for multiply-and-sum patterns. Taking a maximum along an axis, or applying a function such as a softmax, is not an einsum.
Math
Einsum is the sum formula with the summation signs dropped. Write the result entries as a function of the kept indices and sum over every index that does not appear on the left:
Examples in the notation of P1.A3 and P1.B6:
'i,i->'is .'ik,kj->ij'is .'bik,bkj->bij'is .'bqd,bkd->bqk'is .
The naive loop visits every combination of values of all the letters (summed or kept) once, so the work is the product of all the sizes. For 'ik,kj->ij' with , , of sizes that is , the same count as a naive matrix product.
Code
import numpy as np
a = np.array([1, 2, 3]); b = np.array([4, 5, 6])
M = np.array([[1, 2, 3], [4, 5, 6]])
N = np.array([[1, 0], [2, 1], [0, 3]])
np.einsum('i,i->', a, b) # 32, the dot product
np.einsum('ik,kj->ij', M, N) # [[5 11] [14 23]], the same as M @ N
np.einsum('ij->ji', M) # the transpose, shape (3, 2)torch.einsum takes the same specs (P2.6).
Explicit and implicit mode
When you write -> it is explicit mode: you decide the result axes. When you leave it out, NumPy is in implicit mode and applies a rule: the result keeps the letters that appear exactly once in the whole spec, sorted alphabetically; letters that appear twice or more are summed.
'ij,jk'hasionce,jtwice,konce, so the result is'ik': the matrix product.'ik,kj'gives'ij', also the matrix product.'ii'hasitwice, so nothing is kept: the trace.'ij,ij'sums everything: forMabove.'i,j'keeps both letters: the outer product.'ba'keepsaandbin alphabetical order,'ab'. The input’s first axis is labelledb, so the result is the transpose: forMof shape(2, 3)the result has shape(3, 2). Written explicitly,'ba->ba'returnsMunchanged.
The third case is the trap: the names you choose can change the result in implicit mode (the kept letters are sorted alphabetically), but never in explicit mode. So: write -> yourself. It documents the output shape and cannot be changed by a renamed letter.
Batches and attention
The batched matrix product from P1.B14, a stack of matrices, is one letter more:
# the same as X @ Y for 3-axis arrays
np.einsum('bik,bkj->bij', X, Y)
b is on both inputs and on the result, so it is kept: the batch items stay separate. k is summed. The attention scores of P7.3 are one more line of the same shape. With queries Q of shape (B, T_q, d) and keys K of shape (B, T_k, d):
# shape (B, T_q, T_k)
scores = np.einsum('bqd,bkd->bqk', Q, K)
For every example b, every query q and every key k, the score is the dot product over the feature letter d. Here the letter k means “key position”, while in the matrix product above it was the summed letter: a letter’s meaning is local to one spec. With a head axis h it becomes 'bhtd,bhsd->bhts' (P1.B14, P7.5), and the scaling by and the softmax over the last axis (P7.4) are separate steps: einsum does the multiply-and-sum only.
Go deeper Three inputs, ellipsis, and the order of the work
An einsum can have any number of inputs. np.einsum('i,ij,j->', x, M, y) is , a bilinear form. NumPy can do it as one triple loop, or as two smaller steps (first M @ y, then a dot product with x). The cheaper order may be very different from the naive one, which is what optimize=True is for (next section).
An ellipsis ... stands for “any leading axes, whatever they are”, so one spec works with and without batch axes: '...ik,...kj->...ij' is X @ Y for any number of leading axes, and '...ij->...ji' transposes the last two axes of anything. This visualizer does not draw ellipsis specs, but NumPy and PyTorch accept them.
Speed: einsum against @
For the same job, a plain np.einsum call is not always as fast as @. A matrix product with @ is handed to an optimised linear-algebra library; the default einsum runs its own loops. On the computer used to write this lesson, a plain np.einsum('ik,kj->ij', A, B) of two matrices was many times slower than A @ B (25 times there; about 2 times on another computer), and with optimize=True it was about as fast. The gap depends on your machine, so measure.
optimize=True(oroptimize='optimal') lets NumPy plan the work: it can pick a cheaper order for three or more inputs, and call matrix-product routines where it can.np.einsum_pathshows the plan and an estimate of the cost.- With three or more inputs the order matters a lot. For
'ij,jk,k->i'it is much cheaper to multiply the matrix by the vector first (about work) than to form the matrix product first (about ):optimize=Truefinds the cheap order. - Use
@when the operation is a matrix product and the shapes are what@expects. Use einsum when the line is clearer with names (a transpose in the middle, a batch and head axis, a diagonal), or when no combination of@,.Tandsumsays it simply.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Common einsum mistakes
- Using the same letter for two axes that are not the same. If
'ij,ij->ij'was meant to be a matrix product, it is not: both inputs share both letters, so it multiplies entry by entry. Letters link axes: reusing one says “these two axes have the same index”. - A size mismatch.
'ik,kj->ij'withAof shape(2, 3)andBof shape(4, 2)raises aValueErrorwhose message begins “operands could not be broadcast together with remapped shapes”. Read it as “the sizes of a shared letter do not agree”. Note that NumPy’seinsumis lenient about this: an axis of size 1 can stand in for a longer one, so'ij,jk->ik'with shapes(2, 3)and(1, 2)runs without an error (it gave a result filled with 3s with the NumPy version we tried). The documentation does not promise this, so do not rely on it; check shapes. - A letter after the arrow that was never named before it (
'ij->ijk'):ValueError: einstein sum subscripts string included output subscript 'k' which never appeared in an input. - The wrong number of letters for an input:
'ijk->ij'for a 2-axis array raises “too many subscripts for operand 0”; and giving the wrong number of arrays for the terms in the spec raises aValueErrorabout operands (NumPy’s wording for this one is confusing, so count your arrays and your commas). - Relying on implicit mode. A renamed letter can transpose the result. Write the arrow.
- Thinking einsum can do anything. It multiplies and sums. A maximum, an average of absolute values or a softmax needs other functions (the mean is a sum divided by the count: divide afterwards).
Where you will meet it next
- The forward pass (P4.5, P4.10). A layer on a batch is
X @ W.T + b, and the bias is the broadcast from this lesson. - Normalisation (P4.19). Each normalisation layer is
(x - mean) / sqrt(var + eps)with the mean and variance over chosen axes andkeepdims=True: the standardise pattern, with the axes changed. - Attention (P7.3 to P7.5) and masks (P7.8). The score einsum, the padding mask and the causal mask are the ones you built here.
- Nearest neighbours and clustering (P3.B1, P3.C1). All pairwise distances.
- PyTorch (P2.6).
torch.einsumhas the same notation, and broadcasting follows the same rule.
Common mistakes
Check your understanding
Xhas shape(100, 5). Which line standardises each column (mean 0, standard deviation 1)?The column means have shape
(5,), which lines up with the last axis ofX, so one mean and one standard deviation is used for each column. The version that takes means along the other axis gives shape(100,), which clashes with the last axis of size 5 and raises an error. Subtracting one overall mean centres the whole table, not each column, and dividing by the total sum does not centre or rescale anything column by column.labelsis an integer array of shape(6,)with values from 0 to 3. Which expression gives a(6, 4)array whose rowiis the one-hot vector oflabels[i]?A column of labels
(6, 1)compared with a row of class numbers(4,)broadcasts to(6, 4): entry(i, c)islabels[i] == c. Comparing the flat array of 6 labels with 4 class numbers fails (sizes 6 and 4 clash). Putting the class numbers in a column and the labels in a row gives the transpose,(4, 6). A row of labels(1, 6)against(4,)is again a clash on the last axis.Ahas shape(3, 4)andxhas shape(4,). Which call is the same asA @ x?In
A @ xevery row ofAis dotted withx: the column indexjis shared and summed, and the row indexiis kept, giving shape(3,). The other specs mean something else:'ij,i->j'labelsxwith the letteriof size 3, butxhas length 4, so it is an error;'ij,j->j'keepsjand sumsi, giving a length-4 vector (the column sums ofAtimesx); and'ij,j->ij'keeps both letters, giving the(3, 4)array of entry by entry products.AandBboth have shape(3, 4). What doesnp.einsum("ij,ij->", A, B)compute?Both letters are shared by the two inputs, so entries with the same
(i, j)are multiplied, and both letters are missing after the arrow, so everything is summed into one number. The matrix product would need one shared letter only (and shapes(3, 4)and(3, 4)cannot be multiplied that way). Keeping both letters gives the entry by entry product, and keeping onlyigives the row sums.Mhas shape(2, 3). What is the shape ofnp.einsum("ba", M)?Without an arrow NumPy is in implicit mode: the letters that appear once are kept in alphabetical order, so the result axes are
athenb. The letterblabels the first axis ofM(size 2) andathe second (size 3), so the result hasa(size 3) first andb(size 2) second, which is the transpose. A missing arrow is allowed, and nothing is summed because no letter is repeated.Ahas shape(n, d)andBhas shape(m, d). How many numbers does the intermediate arrayA[:, None, :] - B[None, :, :]hold?The subtraction stretches both arrays to
(n, m, d), one difference for every pair of points and every feature, so the result holds numbers (the inputs themselves are not copied). The count is the size of the finished table of distances, after the sum over the feature axis, and the other two are the sizes of the inputs.
Exercises
- Standardise the columns of (use NumPy’s default standard deviation, dividing by ). What is the result?
Show answer
The means are and the standard deviations are and . Both columns become , because the second column is 5 times the first plus 5, and standardising removes a shift and a positive scale. In code:(X - X.mean(axis=0)) / X.std(axis=0). - Write one line that builds the table of for .
Show answer
i = np.arange(4); np.abs(i[:, None] - i[None, :]), which is[[0 1 2 3] [1 0 1 2] [2 1 0 1] [3 2 1 0]]. - One-hot encode
labels = [1, 3, 0]for 4 classes in one line.Show answer
(np.array([1, 3, 0])[:, None] == np.arange(4)).astype(int)gives[[0 1 0 0] [0 0 0 1] [1 0 0 0]]. - For
A = [[0, 0], [1, 0]]andB = [[0, 3], [4, 0]], compute the table of squared distances by hand, and say how many numbersA[:, None, :] - B[None, :, :]holds.Show answer
(for example has squared length ). The difference array has shape(2, 2, 2), so numbers. For and the same array would hold numbers, 800 MB in 64-bit floats. - Write an einsum for , which is the trace of the matrix product , without forming the product.
Show answer
np.einsum('ij,ji->', A, B). Letteriis the row ofAand the column ofB,jthe other way round, and both are summed. ForA = [[1, 2], [3, 4]]andB = [[5, 6], [7, 8]]it gives , the same asnp.trace(A @ B). ('ij,ij->'would give 70, a different number.) - Shapes
(5, 2, 3)and(5, 3, 4): what is the shape ofnp.einsum('bij,bjk->bik', X, Y)? What happens ifYhas shape(5, 4, 3)?Show answer
(5, 2, 4): the batch letterband the lettersiandkare kept,jis summed. WithYof shape(5, 4, 3)the shared letterjhas size 3 inXand size 4 inY: aValueError(“operands could not be broadcast together with remapped shapes”). Ahas shape(2, 3)andBhas shape(4, 3). What doesnp.einsum('ij,kj', A, B)return, and which ordinary NumPy expression is it?Show answer
Without an arrow, the letters that appear once areiandk, so the output is'ik', shape(2, 4);jappears twice and is summed. It isA @ B.T: every row ofAdotted with every row ofB.- Code: for the rows of
X = [[1, 0], [1, 1], [0, 2]], build the table of cosine similarities (P1.B3) using row normalisation and one matrix product.Show answer
Xn = X / np.linalg.norm(X, axis=1, keepdims=True)andXn @ Xn.T. The result is[[1, 0.707, 0], [0.707, 1, 0.707], [0, 0.707, 1]](rounded). Normalising the rows first is why a single matrix product gives all the cosines (P1.B3).