时间:2022-07-05 13:50:02 | 栏目:Python代码 | 点击:次
view()相当于reshape、resize,重新调整Tensor的形状。
import torch a1 = torch.arange(0,16) print(a1) # tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
a2 = a1.view(8, 2) a3 = a1.view(2, 8) a4 = a1.view(4, 4) print(a2) #tensor([[ 0, 1], # [ 2, 3], # [ 4, 5], # [ 6, 7], # [ 8, 9], # [10, 11], # [12, 13], # [14, 15]]) print(a3) #tensor([[ 0, 1, 2, 3, 4, 5, 6, 7], # [ 8, 9, 10, 11, 12, 13, 14, 15]]) print(a4) #tensor([[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11], # [12, 13, 14, 15]])
view中一个参数定为-1,代表自动调整这个维度上的元素个数,以保证元素的总数不变。
v1 = torch.arange(0,16) print(v1) # tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) v2 = v1.view(-1, 16) v2 # tensor([[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]]) v2 = v1.view(-1, 8) v2 # tensor([[ 0, 1, 2, 3, 4, 5, 6, 7], # [ 8, 9, 10, 11, 12, 13, 14, 15]]) v2 = v1.view(-1, 4) v2 #tensor([[ 0, 1, 2, 3], # [ 4, 5, 6, 7], # [ 8, 9, 10, 11], # [12, 13, 14, 15]]) v2 = v1.view(-1, 2) v2 #tensor([[ 0, 1], # [ 2, 3], # [ 4, 5], # [ 6, 7], # [ 8, 9], # [10, 11], # [12, 13], # [14, 15]])
v3 = v1.view(4*4, -1) v3 # tensor([[ 0], # [ 1], # [ 2], # [ 3], # [ 4], # [ 5], # [ 6], # [ 7], # [ 8], # [ 9], # [10], # [11], # [12], # [13], # [14], # [15]])