Using np.expand_dims() and np.squeeze() in NumPy
📖 Scenario: Imagine you are working with image data in a simple computer vision project. Images are stored as arrays, but sometimes you need to add or remove extra dimensions to prepare the data for a model.
🎯 Goal: You will learn how to add a new dimension to a NumPy array using np.expand_dims() and how to remove single-dimensional entries using np.squeeze(). This helps in reshaping data correctly for processing.
📋 What You'll Learn
Create a 2D NumPy array called
image with exact valuesCreate a variable called
axis_to_expand to specify where to add a new dimensionUse
np.expand_dims() to add a new dimension to image and save it as expanded_imageUse
np.squeeze() to remove single-dimensional entries from expanded_image and save it as squeezed_imagePrint the shapes of
image, expanded_image, and squeezed_image to see the changes💡 Why This Matters
🌍 Real World
In real-world data science, reshaping arrays is common when preparing data for machine learning models, especially in image processing and deep learning.
💼 Career
Understanding how to manipulate array dimensions is essential for data scientists and machine learning engineers to correctly format data inputs and outputs.
Progress0 / 4 steps