torch.tensor.view(*args)
阿新 • • 發佈:2018-12-12
view(*args) → Tensor 返回一個有相同資料但大小不同的tensor。 返回的tensor必須有與原tensor相同的資料和相同數目的元素,但可以有不同的大小。一個tensor必須是連續的contiguous()才能被檢視。
import torch x = torch.randn(4, 5) print('tensor原型:',x) print('tensor維度變換,由(4,5)到(20,1):',x.view(20, 1)) #由(4,5)到(-1,1)的tensor維度變換,其中-1是tensor在1下的另一個維度的大小,即為20/1=20,也就是說在這裡-1=20 print('tensor維度變換,由(4,5)到(-1,1):',x.view(-1, 1)) print('tensor維度變換,由(4,5)到(1,20):',x.view(1, 20)) #由(4,5)到(1, -1)的tensor維度變換,其中-1是tensor在1下的另一個維度的大小,即為20/1=20,也就是說在這裡-1=20 print('tensor維度變換,由(4,5)到(1,-1):',x.view(1, -1))
程式碼執行結果:
tensor原型: tensor([[ 0.2278, -0.6850, 0.6527, -0.3206, -2.5704], [ 0.8447, 0.2473, -0.5029, 0.6311, -0.4551], [ 0.8049, -0.3084, 0.5642, 0.2411, 0.5785], [-0.6099, -0.8746, -0.9222, 2.0989, 1.5902]]) tensor維度變換,由(4,5)到(20,1): tensor([[ 0.2278], [-0.6850], [ 0.6527], [-0.3206], [-2.5704], [ 0.8447], [ 0.2473], [-0.5029], [ 0.6311], [-0.4551], [ 0.8049], [-0.3084], [ 0.5642], [ 0.2411], [ 0.5785], [-0.6099], [-0.8746], [-0.9222], [ 2.0989], [ 1.5902]]) tensor維度變換,由(4,5)到(-1,1): tensor([[ 0.2278], [-0.6850], [ 0.6527], [-0.3206], [-2.5704], [ 0.8447], [ 0.2473], [-0.5029], [ 0.6311], [-0.4551], [ 0.8049], [-0.3084], [ 0.5642], [ 0.2411], [ 0.5785], [-0.6099], [-0.8746], [-0.9222], [ 2.0989], [ 1.5902]]) tensor維度變換,由(4,5)到(1,20): tensor([[ 0.2278, -0.6850, 0.6527, -0.3206, -2.5704, 0.8447, 0.2473, -0.5029, 0.6311, -0.4551, 0.8049, -0.3084, 0.5642, 0.2411, 0.5785, -0.6099, -0.8746, -0.9222, 2.0989, 1.5902]]) tensor維度變換,由(4,5)到(1,-1): tensor([[ 0.2278, -0.6850, 0.6527, -0.3206, -2.5704, 0.8447, 0.2473, -0.5029, 0.6311, -0.4551, 0.8049, -0.3084, 0.5642, 0.2411, 0.5785, -0.6099, -0.8746, -0.9222, 2.0989, 1.5902]])