Torch和Numpy——形状变换与轴交换
输入
1 import numpy as np 2 import torch 3 4 #numpy创建 5 a = np.arange(1,12,2).reshape([2,3]) #生成一个由1到12之间的数组成的步长为2的2x3矩阵 6 print(a) 7 b=a.T #对a进行转置 8 print(b) 9 print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&') 10 11 c = np.arange(12).reshape([2,2,3]) #生成一个由0到11的数字组成的形状为2组2x3的矩阵 12 print(c) 13 print("_________________________________________________________________") 14 15 #torch创建 16 a1 = torch.arange(12).reshape([3,4]) 17 print(a1) 18 b1 = a1.T #或者 b1 = a1.t() 19 print(b1) 20 print("**********************************************************************") 21 22 23 c1 = torch.arange(12).reshape([2,2,3]) #生成一个有0到11的数字组成的形状为2组2x3的矩阵 24 print(c1) 25 26 d = torch.transpose(c1,0,2) #将c1的0轴和2轴进行交换 27 print(d) 28 d1 = torch.transpose(d,1,2) 29 print(d1) 30 print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^") 31 32 d2 = c1.permute([2,0,1]) #第二种交换c1的3个轴的方法 33 print(d2) 34 35 e = np.reshape(c,[3,2,2]) #矩阵变形 36 print(e)
输出
[[ 1 3 5] [ 7 9 11]] [[ 1 7] [ 3 9] [ 5 11]] &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& [[[ 0 1 2] [ 3 4 5]] [[ 6 7 8] [ 9 10 11]]] _________________________________________________________________ tensor([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) tensor([[ 0, 4, 8], [ 1, 5, 9], [ 2, 6, 10], [ 3, 7, 11]]) ********************************************************************** tensor([[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7, 8], [ 9, 10, 11]]]) tensor([[[ 0, 6], [ 3, 9]], [[ 1, 7], [ 4, 10]], [[ 2, 8], [ 5, 11]]]) tensor([[[ 0, 3], [ 6, 9]], [[ 1, 4], [ 7, 10]], [[ 2, 5], [ 8, 11]]]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ tensor([[[ 0, 3], [ 6, 9]], [[ 1, 4], [ 7, 10]], [[ 2, 5], [ 8, 11]]]) [[[ 0 1] [ 2 3]] [[ 4 5] [ 6 7]] [[ 8 9] [10 11]]]

浙公网安备 33010602011771号