0
0
NumPydata~20 mins

np.expand_dims() and np.squeeze() in NumPy - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Numpy Dimension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of np.expand_dims() on a 1D array
What is the output shape of the array after applying np.expand_dims() on a 1D array along axis 0?
NumPy
import numpy as np
arr = np.array([1, 2, 3])
expanded = np.expand_dims(arr, axis=0)
print(expanded.shape)
A(3,)
B(3, 1)
C(1, 3)
D(1,)
Attempts:
2 left
💡 Hint
Think about adding a new dimension at the start of the shape.
Predict Output
intermediate
2:00remaining
Effect of np.squeeze() on a 3D array
Given a 3D array with shape (1, 4, 1), what is the shape after applying np.squeeze()?
NumPy
import numpy as np
arr = np.zeros((1, 4, 1))
squeezed = np.squeeze(arr)
print(squeezed.shape)
A(1, 4, 1)
B(4,)
C(4, 1)
D(1, 4)
Attempts:
2 left
💡 Hint
np.squeeze removes all dimensions of size 1.
🔧 Debug
advanced
2:00remaining
Identify the error in np.expand_dims usage
Which option will cause an error when trying to expand dimensions of a 2D array with shape (3, 4) using np.expand_dims()?
NumPy
import numpy as np
arr = np.ones((3, 4))
expanded = np.expand_dims(arr, axis=3)
print(expanded.shape)
Aaxis=4
Baxis=3
Caxis=-1
Daxis=2
Attempts:
2 left
💡 Hint
Check if the axis value is valid for the array's dimensions.
data_output
advanced
2:00remaining
Result of squeezing with specific axis
What is the shape of the array after applying np.squeeze() with axis=0 on an array of shape (1, 5, 1)?
NumPy
import numpy as np
arr = np.zeros((1, 5, 1))
squeezed = np.squeeze(arr, axis=0)
print(squeezed.shape)
A(5, 1)
B(1, 5)
C(5,)
D(1, 5, 1)
Attempts:
2 left
💡 Hint
Only the specified axis with size 1 is removed.
🚀 Application
expert
3:00remaining
Using np.expand_dims and np.squeeze to reshape data
You have a 1D array of shape (10,). You want to reshape it to (10, 1) for a machine learning model input, then later revert it back to (10,) after prediction. Which sequence of operations correctly achieves this?
NumPy
import numpy as np
arr = np.arange(10)
# reshape for model input
arr_expanded = np.expand_dims(arr, axis=1)
# ... model prediction happens ...
# revert to original shape
arr_reverted = np.squeeze(arr_expanded, axis=1)
print(arr_reverted.shape)
AUse np.expand_dims(arr, axis=0) then np.squeeze(arr_expanded)
BUse np.expand_dims(arr, axis=0) then np.squeeze(arr_expanded, axis=0)
CUse np.expand_dims(arr, axis=1) then np.squeeze(arr_expanded)
DUse np.expand_dims(arr, axis=1) then np.squeeze(arr_expanded, axis=1)
Attempts:
2 left
💡 Hint
Match the axis used in expand_dims and squeeze to correctly revert shape.