Hello programmers, in this article, we will discuss the Numpy squeeze function in Python. The squeeze() function removes single-dimensional entries from an array’s shape. Whenever we want to change the shape of a three-dimensional array to a two-dimensional array, we use the squeeze() function.
The Numpy squeeze() function returns the input array with the subset of the dimension having a length equal to one removed from the array. Before we cite examples to show the working of numpy.squeeze() function, let me briefly brief you about the syntax, parameters, and return type.
Syntax of Numpy squeeze
Parameters of Numpy Squeeze:
- a: Represents the Input data.
- axis: Signifies an int or tuple of int values. It selects a subset of the single-dimensional entries in the shape. An error is raised, If an axis is selected with a shape entry greater than one.
Return type of Squeeze
This squeeze() function returns an output array similar to input array input, but with all or a subset of the dimensions of length 1 removed.
Example of Squeeze Function in Python
import numpy as np a = np.array([[, , ]]) print(a.shape) b = np.squeeze(a).shape print(b)
(1, 3, 1) (3)
The above example is a very basic implementation of the squeeze function. An array ‘a’ of shape (1, 3, 1) is obtained. On passing ‘a’ to the squeeze() function, its shape (3) i.e., removing all the dimensions of length 1.
Numpy Squeeze for axis = 0
import numpy as np a = np.arange(9).reshape(1, 3, 3) print ("Input array : ", a) b = np.squeeze(a , axis = 0) print ("output array : ", b) print("The shapes of Input and Output array : ") print(a.shape, b.shape)
Input array : [[[0 1 2] [3 4 5] [6 7 8]]] output array : [[0 1 2] [3 4 5] [6 7 8]] The shapes of Input and Output array : (1, 3, 3) (3, 3)
In the above example, an array s defined using numpy.arrange() function of shape specified as (1, 3, 3). This array passed to the squeeze() function, which returns the input array having the same dimension and number of elements. It removes all the dimensions of length 1. Hence the shape is retuned as (3,3). The axis parameter controls the operations transversion. In this case, it’s 0. It means the squeezed axis is not of length 1.
Matrix squeeze in Python
import numpy as np # make matrix with numpy a = np.matrix('[, ]') # applying matrix.squeeze() method b = a.squeeze() print(b)
[[ 4 8]]
With the help of Numpy
matrix.squeeze() method, we are able to squeeze the size of a matrix. In this method, the Nx1 size of the input matrix is given out as a 1xN size of the output matrix. In the above example, a numpy matrix is defined using the np.matrix function. And then the numpy squeeze function is used to squeeze the matrix and give the output as [[ 4 8 ]] from the originally created matrix i.e., [ ,  ].
In this article, we have seen the example and implementation of Numpy Squeeze in Python. We have also seen the use of Squeeze in a matrix as well. Refer to this article for any queries related to the Squeeze function.