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

5 Tensor Operations for Linear Algebra and Data Processing with PyTorch

A short introduction about PyTorch and about the following functions:

  • torch.roll(input, shifts, dims);
  • torch.svd(input, some=True, compute_uv=True, out=None);
  • torch.eig(eigenvectors=False);
  • torch.nonzero(input, out=None, as_tuple=False);
  • torch.norm(input, p='fro', dim=None, keepdim=False, out=None, dtype=None).
# Import torch
import torch
# Creating 2D tensors for further processing
mat = []

print('Original matrices:')
for i in range(4):
    m = (i+1) * torch.ones(3,3, dtype=torch.int32)
    mat.append(m)
    print("Matrix {}:\n{}\n".format(i+1,m.numpy()))
Original matrices: Matrix 1: [[1 1 1] [1 1 1] [1 1 1]] Matrix 2: [[2 2 2] [2 2 2] [2 2 2]] Matrix 3: [[3 3 3] [3 3 3] [3 3 3]] Matrix 4: [[4 4 4] [4 4 4] [4 4 4]]

Function 1 - roll(shifts, dims) → Tensor

Rolls a tensor along the chosen dimensions per specified amount of shifts.

# Example 1 - preparing original tensor:
x = torch.ones(3,3)
X = torch.stack((x, 2*x), dim=0)
X
tensor([[[1., 1., 1.],
         [1., 1., 1.],
         [1., 1., 1.]],

        [[2., 2., 2.],
         [2., 2., 2.],
         [2., 2., 2.]]])