Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In linear algebra, matrix multiplication, and deep learning libraries (TensorFlow, PyTorch), the dimensionality of an array must frequently be adjusted to satisfy shape requirements. For example, multiplying a 1D vector of length $N$ by a 2D matrix of shape $(N, M)$ requires expanding the 1D vector into a formal 2D column matrix of shape $(N, 1)$ or row matrix of shape $(1, N)$.
NumPy provides intuitive tools to inject or eliminate singleton dimensions (dimensions of size 1):
np.newaxisnp.expand_dims()np.squeeze()A common conceptual hurdle for beginners is distinguishing between:
(N,)(1, N)(N, 1)np.newaxis?Under the hood, np.newaxis is simply an alias for Python's None. Whenever np.newaxis (or None) is used in an index slice, NumPy inserts a new axis with length 1 at that position:
np.expand_dims()While np.newaxis is concise, np.expand_dims(arr, axis) provides explicit programmatic control over the target insertion axis:
np.squeeze()The inverse of dimension expansion is squeezing. np.squeeze() strips out all dimensions of size 1, collapsing the array back to its minimal dimensional representation:
np.squeeze() that does not have a size of 1 (e.g. np.squeeze(padded_array, axis=1) where dimension size is 28), NumPy raises ValueError: cannot select an axis to squeeze out which has size not equal to one.np.newaxis evaluate to in Python?arr = np.array([5, 10, 15]), what is the shape of arr[:, np.newaxis]?np.expand_dims(np.zeros((10, 20)), axis=1)?np.squeeze(np.ones((1, 5, 1, 8))) return?np.squeeze(np.zeros((3, 4)), axis=0)?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.