0
0
NumPydata~20 mins

np.einsum() for efficient computation in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Einsum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.einsum for matrix multiplication
What is the output of the following code using np.einsum to multiply two matrices?
NumPy
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = np.einsum('ik,kj->ij', A, B)
print(result)
A
[[17 20]
 [39 46]]
B
[[12 14]
 [30 32]]
C
[[19 22]
 [43 50]]
D
[[5 12]
 [21 32]]
Attempts:
2 left
💡 Hint
Think about how matrix multiplication sums over the shared dimension.
data_output
intermediate
1:30remaining
Sum of diagonal elements using np.einsum
What is the output of this code that sums the diagonal elements of a matrix using np.einsum?
NumPy
import numpy as np
M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
diag_sum = np.einsum('ii', M)
print(diag_sum)
A45
B15
C9
D6
Attempts:
2 left
💡 Hint
The diagonal elements are where the row and column indices are equal.
visualization
advanced
2:00remaining
Visualizing outer product with np.einsum
Which option shows the correct 2D array output of the outer product computed by np.einsum?
NumPy
import numpy as np
x = np.array([1, 2, 3])
y = np.array([4, 5])
out = np.einsum('i,j->ij', x, y)
print(out)
A
[[4 5]
 [8 10]
 [12 15]]
B
[[4 8 12]
 [5 10 15]]
C
[[5 4]
 [10 8]
 [15 12]]
D
[[1 2 3]
 [4 5 6]]
Attempts:
2 left
💡 Hint
Outer product multiplies each element of x by each element of y.
🧠 Conceptual
advanced
2:30remaining
Understanding einsum subscripts for tensor contraction
Given two 3D arrays A and B with shapes (2,3,4) and (3,4,5), which einsum subscript string correctly contracts over the last two axes of A and the first two axes of B to produce a (2,5) array?
A'ijk,ljk->il'
B'ijk,klj->il'
C'ijk,jlk->il'
D'ijk,jkl->il'
Attempts:
2 left
💡 Hint
Look for matching indices in the middle dimensions to sum over.
🔧 Debug
expert
2:00remaining
Identify the error in this einsum usage
What error does the following code raise when executed?
NumPy
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
result = np.einsum('ij,jkl->ik', A, B)
print(result)
AValueError: einstein sum subscripts string contains too many subscripts for operand 1
BTypeError: unsupported operand type(s) for einsum
CNo error, prints [[19 22]\n [43 50]]
DSyntaxError: invalid syntax in einsum string
Attempts:
2 left
💡 Hint
Check the number of indices in the subscript string vs array dimensions.