1.Numpy1.1维度交换swapaxes。交换数组的n维中的两个而不改变原始数组的数据。resize可以改变原数组的数据。将numpy导入为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的维度importnumpyasnpa=np.random.randint(1,10,(3,4))print(a.shape)#out:(3,4)#第一种方式:addThe0thdimensiona1=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.只能删除形状为1的维度。axis用于指定要删除的维度,但是指定的维度必须是单个维度,否则会报错;axis的值可以是None或int或int的元组,可选。如果axis为空,则删除所有单维条目;importnumpyasnpa=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拉直importnumpyasnpa=np.random.randint(1,10,(3,1,4))print(a.shape)#out:(3,4)a=a.flatten()print(a.shape)#out:(12,)二、Pytorch2.1维度调整view和reshape函数相同,先把所有元素压平,然后按照给定的形状排列,但最终的总数必须保持不变。importtorcha=torch.rand(28,2,4,28)#四维张量print(a.shape)#out:torch.Size([28,2,4,28])#维度转换为一维,totalsize不变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维度交换转置实现两个维度的交换importtorch=torch.rand(4,3,17,32)#四维张量#转置后需要contiguous保证连续性ofdatainmemoryb=a.transpose(1,3).contiguous()print(b.shape)#out:torch.Size([4,32,17,3])permute实现任意维度的交换importtorch=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的维度importtorch=torch.rand(4,2,16,28)#out:torch.Size([4,2,16,28])print(a.shape)a1=A。unsqueeze(0)#在前面加一个维度a2=a.unsqueeze(1)#在第一和第二个维度之间加一个维度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])#方法二:a1=a[None,...]2.4删除维度suqeeze.只能删除shape为1的维度importtorch=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.5repeatingdimensionrepeat是每个位置的维度Repeat到指定的次数,形成一个新的Tensor。功能同expand,只是repeat会重新申请内存空间。repeat()参数指示每个维度的指定重复次数。importtorch=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])
