一、Numpy

1.1 维度替换

swapaxes。将数组n个维度中两个维度进行调换,不扭转原数组据,resize能够扭转原数组的数据。

import numpy as npa = np.random.randint(1,10,(3,4))print(a.shape)      # out:(3,4)a = a.swapaxes(0,1)print(a.shape)      # out:(4,3)

1.2 减少维度

np.newaxis和np.expand_dims。只能增加shape为1的维度

import numpy as npa = np.random.randint(1,10,(3,4))print(a.shape)      # out:(3,4) # 第一种形式:增加第0维a1 = a[np.newaxis, :]print(a1.shape)     # out:(1,3,4) # 第二种形式:增加第1维a2 = np.expand_dims(a, axis=1)print(a2.shape)     # out:(3,1,4)

1.3 删除维度

np.squeeze。只能删除shape为1的维度

  1. axis用于指定须要删除的维度,然而指定的维度必须为单维度,否则将会报错;
  2. axis的取值可为Noneinttuple of ints, 可选。若axis为空,则删除所有单维度的条目;
import numpy as npa = np.random.randint(1,10,(3,1,4))print(a.shape)      # out:(3,4)a = np.squeeze(a,axis = 1)   # 或:a = a.squeeze(axis = 1)print(a.shape)      # out:(3,4)

1.4 拉直

import numpy as npa = np.random.randint(1,10,(3,1,4))print(a.shape)      # out:(3,4)a = a.flatten()print(a.shape)      # out:(12,)

二、Pytorch

2.1 维度调整

view和reshape性能是一样的,先展平所有元素再依照给定shape排列,然而最终的总数量必须放弃不变。

import torcha = torch.rand(28,2,4,28)  # 四维张量print(a.shape)                      # out:torch.Size([28, 2, 4, 28])# 维度转换成一维,总大小不变print(a.view(28,2*4,28).shape)      # out:torch.Size([28, 8, 28])# -1 示意任意维度(pytorch依据,前面的维度本人推导,如总维度是 28*2*4*28=6272,此时-1代表的维度就是 6272 / 14 =448 )print(a.view(-1,14).shape)          # out:torch.Size([448, 14])

2.2 维度替换

transpose 实现两个维度相互交换

import torcha = torch.rand(4,3,17,32)  # 四维张量# transpose 后须要接 contiguous 保证数据在内存的连续性b = a.transpose(1,3).contiguous()print(b.shape)      # out:torch.Size([4, 32, 17, 3])

permute 实现任意维度的替换

import torcha = torch.rand(4,3,17,32) b = a.permute(0,3,1,2).contiguous() # 按各维度的索引进行排列print(b.shape)  # out:torch.Size([4, 32, 17, 3])

2.3 减少维度

unsuqeeze 。只能增加shape为1的维度

import torcha = torch.rand(4,2,16,28)   # out:torch.Size([4, 2, 16, 28])print(a.shape)a1 = a.unsqueeze(0)         # 最后面减少一个维度a2 = a.unsqueeze(1)         # 在第1,2个维度两头减少一个维度a3 = a.unsqueeze(-1)        # 在最初面减少一个维度print(a1.shape)             # out:torch.Size([1, 4, 2, 16, 28])print(a2.shape)             # out:torch.Size([4, 1, 2, 16, 28])print(a3.shape)             # out:torch.Size([4, 2, 16, 28, 1])# 办法2:a1 = a[None, ...]

2.4 删除维度

suqeeze 。只能删数shape为1的维度

import torcha = torch.rand(4,2,28,17,1,1)  # 四维张量print(a.shape)              # out:torch.Size([4, 2, 28, 17, 1, 1])a1 = a.squeeze()         # 删除所有维度为1的维度a2 = a.squeeze(4)        # 删除指定地位维度为1的维度print(a1.shape)             # out:torch.Size([4, 2, 28, 17])print(a2.shape)             # out:torch.Size([4, 2, 28, 17, 1])

2.5 反复维度

repeat就是将每个地位的维度都反复至指定的次数,以造成新的Tensor,性能与expand一样,然而repeat会从新申请内存空间,repeat()参数示意各个维度指定的反复次数。

import torcha = torch.Tensor(1, 3, 1, 1)print(a.shape)b = a.repeat(64, 1, 600, 800)   # 3这里不想进行反复,所以就相当于"反复至1次"print(b.shape)      # out:torch.Size([64, 3, 600, 800])