np.einsum() helps you do math with arrays in a fast and clear way. It lets you write complex calculations simply and runs them efficiently.
np.einsum() for efficient computation in NumPy
np.einsum(subscripts, *operands, optimize=False)subscripts is a string that tells how to multiply and sum array elements.
operands are the arrays you want to calculate with.
a and b.np.einsum('i,i->', a, b)A and B.np.einsum('ij,jk->ik', A, B)M.np.einsum('ii->i', M)T.np.einsum('ijk->ik', T)This program shows how to use np.einsum() to do a dot product and matrix multiplication. It prints the results clearly.
import numpy as np # Define two 1D arrays a = np.array([1, 2, 3]) b = np.array([4, 5, 6]) # Dot product using np.einsum result_dot = np.einsum('i,i->', a, b) # Define two 2D arrays for matrix multiplication A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) # Matrix multiplication using np.einsum result_matmul = np.einsum('ij,jk->ik', A, B) # Print results print('Dot product:', result_dot) print('Matrix multiplication:\n', result_matmul)
Use simple letters like i, j, k to label array axes in the subscripts.
np.einsum() can replace many common numpy functions like dot, sum, and transpose.
It often runs faster because it avoids creating temporary arrays.
np.einsum() lets you write complex array math clearly and efficiently.
It uses a string to describe how to multiply and sum array elements.
Great for dot products, matrix multiplication, and custom sums without slow loops.
Practice
np.einsum() in numpy?Solution
Step 1: Understand the function's goal
np.einsum()uses Einstein summation notation to express complex array operations clearly and efficiently.Step 2: Compare with other options
Options B, C, and D describe unrelated numpy functions like random generation, sorting, and reshaping.Final Answer:
To perform efficient and readable array operations using Einstein summation notation -> Option AQuick Check:
Purpose of np.einsum() = To perform efficient and readable array operations using Einstein summation notation [OK]
- Confusing einsum with random array creation
- Thinking einsum sorts or reshapes arrays
- Assuming einsum is only for dot products
A and B using np.einsum()?Solution
Step 1: Recall matrix multiplication indices
Matrix multiplication of A (shape ixj) and B (shape jxk) results in shape ixk, summing over j.Step 2: Match einsum subscripts
np.einsum('ij,jk->ik', A, B) uses 'ij,jk->ik', which correctly sums over j and produces ixk output.Final Answer:
np.einsum('ij,jk->ik', A, B) -> Option AQuick Check:
Matrix product einsum = np.einsum('ij,jk->ik', A, B) [OK]
- Mixing up indices order in the subscript string
- Using wrong output indices after ->
- Confusing which axis to sum over
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = np.einsum('ij,ij->i', A, B)
print(result)What is the output?
Solution
Step 1: Understand the einsum subscripts 'ij,ij->i'
This sums element-wise multiplication over the second index j, keeping the first index i.Step 2: Calculate for each i
For i=0: (1*5)+(2*6)=5+12=17; For i=1: (3*7)+(4*8)=21+32=53.Final Answer:
[17 53] -> Option DQuick Check:
Element-wise sum over j = [17 53] [OK]
- Summing over wrong axis
- Confusing output indices in einsum
- Calculating element-wise product incorrectly
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = np.einsum('ij,jk->ik', A, B)
print(result)and choose the correct fix.
Solution
Step 1: Check array shapes and einsum subscripts
A and B both have shape (2,2). The subscript 'ij,jk->ik' expects B's first dimension (j) to match A's second dimension (j), which it does.Step 2: Verify if code runs
Shapes match perfectly for matrix multiplication. No error; the code runs correctly.Final Answer:
No error; code runs correctly -> Option BQuick Check:
No error; code runs correctly [OK]
- Assuming code errors without checking shapes
- Changing subscripts incorrectly
- Swapping arrays unnecessarily
data with shape (10, 5, 4) representing 10 samples, 5 features, and 4 time points. Using np.einsum(), how do you compute the sum of products of features and time points for each sample, resulting in a 1D array of length 10?Solution
Step 1: Understand the dimensions and desired output
Data shape is (samples=10, features=5, time=4). We want to sum over features and time, keeping samples dimension.Step 2: Use einsum to sum over j and k, keep i
Subscript 'ijk,ijk->i' multiplies element-wise and sums over j and k, resulting in length 10 array.Final Answer:
np.einsum('ijk,ijk->i', data, data) -> Option CQuick Check:
Sum over features and time = np.einsum('ijk,ijk->i', data, data) [OK]
- Summing over wrong axes
- Confusing output indices in einsum
- Expecting 2D output instead of 1D
Ready to prove it?
Pass the test and this pattern moves unknown
