Challenge - 5 Problems
Einsum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Think about how matrix multiplication sums over the shared dimension.
✗ Incorrect
The einsum string 'ik,kj->ij' performs standard matrix multiplication by summing over the k index. The result matches the dot product of A and B.
❓ data_output
intermediate1: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)
Attempts:
2 left
💡 Hint
The diagonal elements are where the row and column indices are equal.
✗ Incorrect
The einsum string 'ii' sums elements where the two indices are the same, which are the diagonal elements 1, 5, and 9. Their sum is 15.
❓ visualization
advanced2: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)
Attempts:
2 left
💡 Hint
Outer product multiplies each element of x by each element of y.
✗ Incorrect
The einsum string 'i,j->ij' computes the outer product, resulting in a matrix where each row is x[i] times all elements of y.
🧠 Conceptual
advanced2: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?
Attempts:
2 left
💡 Hint
Look for matching indices in the middle dimensions to sum over.
✗ Incorrect
The subscript 'ijk,jkl->il' sums over j and k, contracting the last two axes of A and first two of B, resulting in shape (2,5).
🔧 Debug
expert2: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)
Attempts:
2 left
💡 Hint
Check the number of indices in the subscript string vs array dimensions.
✗ Incorrect
The subscript 'ij,jkl->ik' expects B to have 3 dimensions (indices j,k,l), but B has shape (2,2) with only 2 dimensions, so einsum raises a ValueError.