Learn practical skills, build real-world projects, and advance your career

Pytorch Tensor Views

Pytorch is a popular Deep learning framework and a replacement of numpy which leverage the use of GPU. Here we are going to cover few basic Tensor operations available in PyTorch.

Here we are going to cover few Tensor View functions available in Pytorch. A tensor can be a 'View' of an another existing Tensor. A view of tensor shares same underlying memory and data of a base tensor. This allows us to do fast and efficient slicing, reshaping and element-wise operations.

The Tensor view functions which we cover here are:

  • torch.tensor.view()

  • torch.squeeze()

  • torch.transpose()

  • torch.expand()

  • torch.chunk()

# Importing torch Module
import torch

Function 1 - torch.tensor.view()

The view function returns a tensor with a different specified shape of the self tensor, which still has the same data of the self tensor with different shape.

view(*shape) - Input Shape (torch size or Int)

The desired output shape is given as a input to the view()

# Example 1

tensor1 = torch.randn(3,2)
print(tensor1,'\t', tensor1.size(), '\n')

tensor2 = tensor1.view(6)
print(tensor2,'\t', tensor2.size(), '\n')

tensor3 = tensor1.view(-1,2)
print(tensor3,'\t', tensor2.size())
tensor([[-1.1734, -0.4212], [ 0.0891, 1.1350], [ 0.5129, -2.1631]]) torch.Size([3, 2]) tensor([-1.1734, -0.4212, 0.0891, 1.1350, 0.5129, -2.1631]) torch.Size([6]) tensor([[-1.1734, -0.4212], [ 0.0891, 1.1350], [ 0.5129, -2.1631]]) torch.Size([6])

Here in this example the tensor2 and tensor3 are just a view of tensor1 with different shapes.