What is the purpose of unsqueeze in numpy?

The purpose of the unsqueeze function in numpy is to add a new dimension at a specified axis. Specifically, it expands the dimensions of the input array by one, turning it into a higher-dimensional array.

The syntax of the unsqueeze function is as follows:

numpy.unsqueeze(a, axis)

In this case, a represents the input array, and axis represents the dimension where a new dimension is to be added. The range of values for the axis parameter is [- (n + 1), n + 1], where n is the number of dimensions in the array a. If the axis parameter is a negative number, it indicates an offset relative to the end dimension of the array.

It is important to note that the unsqueeze function does not alter the contents of the input array, but rather returns a new array. The new array will have one additional dimension, with a length of 1.

For example, consider a two-dimensional array, let’s call it array a:

a = np.array([[1, 2], [3, 4]])

You can use the unsqueeze function to add a new dimension at the second axis.

b = np.unsqueeze(a, 1)

At this point, the array b has dimensions of (2, 1, 2), meaning the original array has added a dimension of length 1 on the second dimension.

bannerAds