Torch和Numpy——形状变换与维度增减

输入

 1 import torch
 2 
 3 a = torch.randn([2,3,2])  #生成2组3x2的随机矩阵
 4 print(a)
 5 b=a.reshape(3,4)  #转化为1组3x4列的
 6 print(b)
 7 print("_____________________________________________")
 8 c=a.reshape(1,12)  #转化成行
 9 print(c)
10 d = a.reshape(12,1)  #转化为一列
11 print("*******************************************")
12 print(d)
13 e = a.reshape(12)  #同上
14 print(e)
15 print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
16 f = torch.unsqueeze(e,1)  #加上一个维度并将其变换为一列
17 print(f)
18 g = torch.squeeze(c,0)  #降低一个微电影并将其变换为一行
19 print(g)

输出

 1 tensor([[[ 0.6470, -1.0670],
 2          [-1.0981,  1.4381],
 3          [-0.8501,  0.0617]],
 4 
 5         [[ 0.6577, -0.6435],
 6          [-0.3520,  0.6506],
 7          [ 0.7744, -0.6745]]])
 8 tensor([[ 0.6470, -1.0670, -1.0981,  1.4381],
 9         [-0.8501,  0.0617,  0.6577, -0.6435],
10         [-0.3520,  0.6506,  0.7744, -0.6745]])
11 _____________________________________________
12 tensor([[ 0.6470, -1.0670, -1.0981,  1.4381, -0.8501,  0.0617,  0.6577, -0.6435,
13          -0.3520,  0.6506,  0.7744, -0.6745]])
14 *******************************************
15 tensor([[ 0.6470],
16         [-1.0670],
17         [-1.0981],
18         [ 1.4381],
19         [-0.8501],
20         [ 0.0617],
21         [ 0.6577],
22         [-0.6435],
23         [-0.3520],
24         [ 0.6506],
25         [ 0.7744],
26         [-0.6745]])
27 tensor([ 0.6470, -1.0670, -1.0981,  1.4381, -0.8501,  0.0617,  0.6577, -0.6435,
28         -0.3520,  0.6506,  0.7744, -0.6745])
29 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
30 tensor([[ 0.6470],
31         [-1.0670],
32         [-1.0981],
33         [ 1.4381],
34         [-0.8501],
35         [ 0.0617],
36         [ 0.6577],
37         [-0.6435],
38         [-0.3520],
39         [ 0.6506],
40         [ 0.7744],
41         [-0.6745]])
42 tensor([ 0.6470, -1.0670, -1.0981,  1.4381, -0.8501,  0.0617,  0.6577, -0.6435,
43         -0.3520,  0.6506,  0.7744, -0.6745])

 

posted @ 2020-07-20 20:30  前尘•昨夜•此刻  阅读(300)  评论(0)    收藏  举报