本文将分别介绍基于numpy的数组的维度增减方法
增加维度: expand_dims(),np.newaxis
减少维度: 0替换通道,squeeze()
矩阵叠加: np.stack()
一、增加维度
expand_dims
示例:
import numpy as np
a = np.zeros((32,32))
print(a.shape)
a1 = np.expand_dims(a,0)
print(a1.shape)
(32,32) (1,32,32)
None(np.newaxis)
示例:
import numpy as np
a = np.zeros((32,32))
print(a.shape)
a1 = a[None,:,:]
print(a1.shape)
(32,32) (1,32,32)
二、删除通道
squeeze()
示例:
import numpy as np
a = np.zeros((1,32,32))
print(a.shape)
a1 = a.squeeze()
print(a1.shape)
(1,32,32) (32,32)
0减去对应维度
示例:
import numpy as np
a = np.zeros((3,32,32))
print(a.shape)
a1 = a[0,:,:]
print(a1.shape)
(3,32,32) (32,32)
三、np.stack()
示例:
使用np.stack会自动对原始数组增加一个维度比如(32,32)会被转换为(1,32,32),并有三个(1,32,32)叠加成(3,32,32)所以在确定axis时,axis = 0
import numpy as np
a = np.zeros((32,32))
print(a.shape)
a1 = np.stack([a,a,a],axis = 0)
print(a1.shape)
(3,32,32) (32,32)