一、普通用法 (手动调整size)
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]])
二、特殊用法:参数-1 (自动调整size)
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]])
到此这篇关于pytorch中的 .view()函数的用法介绍的文章就介绍到这了,更多相关pytorch .view()函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!