SoFunction
Updated on 2024-11-10

An introduction to the use of the .view function in pytorch

I. General usage (manual resizing)

view() is equivalent to reshape, resize, and reshape the Tensor.

import torch
a1 = (0,16)
print(a1)
# tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
a2 = (8, 2)
a3 = (2, 8)
a4 = (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]])

II. Special Usage: Parameter -1 (auto-size)

A parameter in view is set to -1, which represents an automatic adjustment of the number of elements in this dimension to keep the total number of elements constant.

v1 = (0,16)
print(v1)
# tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15])
v2 = (-1, 16)
v2
# tensor([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15]])
v2 = (-1, 8)
v2
# tensor([[ 0,  1,  2,  3,  4,  5,  6,  7],
#         [ 8,  9, 10, 11, 12, 13, 14, 15]])
v2 = (-1, 4)
v2
#tensor([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11],
#        [12, 13, 14, 15]])
v2 = (-1, 2)
v2
#tensor([[ 0,  1],
#        [ 2,  3],
#        [ 4,  5],
#        [ 6,  7],
#        [ 8,  9],
#        [10, 11],
#        [12, 13],
#        [14, 15]])
v3 = (4*4, -1)
v3
# tensor([[ 0],
#         [ 1],
#         [ 2],
#         [ 3],
#         [ 4],
#         [ 5],
#         [ 6],
#         [ 7],
#         [ 8],
#         [ 9],
#         [10],
#         [11],
#         [12],
#         [13],
#         [14],
#         [15]])

to this article on the use of pytorch .view() function is introduced to this article, more related pytorch .view() function content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future!