1. ndarray.ndim
使用ndarray.ndim可以查看array中轴的数量(axes)
例如:
>>> array_example = np.array([[[0, 1, 2, 3],
... [4, 5, 6, 7]],
...
... [[0, 1, 2, 3],
... [4, 5, 6, 7]],
...
... [[0 ,1 ,2, 3],
... [4, 5, 6, 7]]])
运行:
>>> array_example.ndim
3
知道轴的数量后还需要了解轴的方向,如图所示:
注1: 列总是最后一维。
注2: numpy和pytorch均可以按照轴方向进行运算
2. 形状操作
获取形状:
>>> array_example.shape
(3, 2, 4)
更改数组形状
>>> a = np.arange(6)
>>> print(a)
[0 1 2 3 4 5]
>>> b = a.reshape(3, 2)
>>> print(b)
[[0 1]
[2 3]
[4 5]]
或者使用np.reshape:
>>> numpy.reshape(a, newshape=(1, 6))
array([[0, 1, 2, 3, 4, 5]])
数组转置:arr.transpose()或arr.T
>>> arr = np.arange(6).reshape((2, 3))
>>> arr
array([[0, 1, 2],
[3, 4, 5]])
>>> arr.transpose()
array([[0, 3],
[1, 4],
[2, 5]])
>>> arr.T
array([[0, 3],
[1, 4],
[2, 5]])
调整轴axis顺序:
>>> a = np.random.randint(0,10,(2,3,4,5))
>>> print("原数组形状:",a.shape)
>>> print("transpose:",np.transpose(a,(1,2,0,3)).shape)#重新指定轴0到3的顺序
>>> 原数组形状: (2, 3, 4, 5)
>>> transpose: (3, 4, 2, 5)
交换两个轴:
>>> print("swapaxes:",np.swapaxes(a,1,2).shape)#交换轴1和2
>>> swapaxes: (2, 4, 3, 5)
3.维度增加
1)np.newaxis
将1维数组变成行向量:
# 1D array to 2D array
>>> row_vector = a[np.newaxis, :]
>>> row_vector.shape
(1, 6)
将1维数组变成列向量:
>>> col_vector = a[:, np.newaxis]
>>> col_vector.shape
(6, 1)
2)np.expand_dims
将1维数组变成行向量:
# 1D array to 2D array
>>> row_vector = np.expand_dims(a,axis=0)
>>> row_vector.shape
(1, 6)
将1维数组变成列向量:
>>> col_vector = np.expand_dims(a,axis=1)
>>> col_vector.shape
(6, 1)