0
0
NumPydata~15 mins

np.expand_dims() and np.squeeze() in NumPy - Mini Project: Build & Apply

Choose your learning style9 modes available
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 values
Create a variable called axis_to_expand to specify where to add a new dimension
Use np.expand_dims() to add a new dimension to image and save it as expanded_image
Use np.squeeze() to remove single-dimensional entries from expanded_image and save it as squeezed_image
Print 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
1
Create the initial 2D image array
Create a 2D NumPy array called image with these exact values: [[10, 20, 30], [40, 50, 60]]
NumPy
Need a hint?

Use np.array() to create the array with the given nested list.

2
Set the axis to expand
Create a variable called axis_to_expand and set it to 0 to add a new dimension as the first axis
NumPy
Need a hint?

Just assign the number 0 to the variable axis_to_expand.

3
Add a new dimension using np.expand_dims()
Use np.expand_dims() with image and axis_to_expand to create expanded_image that has a new dimension added
NumPy
Need a hint?

Call np.expand_dims() with image and axis=axis_to_expand.

4
Remove single-dimensional entries using np.squeeze() and print shapes
Use np.squeeze() on expanded_image to create squeezed_image. Then print the shapes of image, expanded_image, and squeezed_image each on a new line.
NumPy
Need a hint?

Use np.squeeze() on expanded_image. Then print the .shape attribute of each array.