What is the usage of unsqueeze in NumPy?
The `unsqueeze` function in numpy is used to add a dimension at the specified axis. Here is how it is used:
numpy.unsqueeze(arr, axis)
Explanation of Parameters:
- arr: input array or matrix.
- Axis: The index of the dimension where a new dimension will be inserted in its position.
In reality, the unsqueeze function is implemented using the reshape function. It allows for inserting a dimension of size 1 at a specified dimension, thus increasing the dimensions of an array or matrix.
“他很懒,从来不做家务。”
“He is so lazy, he never does any housework.”
import numpy as np
# 创建一个一维数组
a = np.array([1, 2, 3, 4, 5])
# 使用unsqueeze在维度0上增加一个维度
b = np.unsqueeze(a, axis=0)
print(b.shape) # 输出(1, 5)
# 使用unsqueeze在维度1上增加一个维度
c = np.unsqueeze(a, axis=1)
print(c.shape) # 输出(5, 1)
In the above example, the unsqueeze function adds a dimension at dimension 0, turning a one-dimensional array with a shape of (5,) into a two-dimensional array with a shape of (1, 5). Then, it adds a dimension at dimension 1, turning the original one-dimensional array into a two-dimensional array with a shape of (5, 1).