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

Assignment 1 - All About torch.Tensor

5 interesting functions related to PyTorch tensors

  • function 1 - torch.transpose()
  • function 2 - torch.sort()
  • function 3 - torch.det()
  • function 4 - torch.std()
  • function 5 - torch.add()
# Import torch and other required modules
import torch

Function 1 - torch.transpose (input)

Matrix transpose is an operation, which often appears in data analysis tasks.
As we know "a torch.Tensor is a multi-dimensional matrix containing elements of a single data type".
We can transpose tensors as well.
We transpose tensor, regardless of how many rows and columns it has. Square matrices, with an equal number of rows and columns, are most commonly transposed.

  • During linear regression lecture t() function was used to transpose the tensor. It is interesting, is it the same as transpose()?
# Example 1 - working 
A=torch.tensor([[1, 2, 3], [4., 5, 6], [7, 8, 9]])
print('Our Tensor:', A)
B=torch.transpose(A, 0, 1)
print('Transposed Tensor:', B)
C=torch.t(A)
print('Transposed Tensor:', C)
Our Tensor: tensor([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]]) Transposed Tensor: tensor([[1., 4., 7.], [2., 5., 8.], [3., 6., 9.]]) Transposed Tensor: tensor([[1., 4., 7.], [2., 5., 8.], [3., 6., 9.]])

The transposition of a square matrix. First row become a the first column, the second row - the second column, and so forth. So, we see that t() and transpose() can give the same result.