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

Pytorch and tensor operations

A gentle introduction to some of Pytorch's functions

Pytorch is an open-source Python library used for Machine Learning. Developed by Facebook, it has quickly gained popularity versus alternatives like Tensorflow.

  • torch.cross()
  • torch.flatten()
  • torch.save()
  • torch.load()
  • torch.reshape()
# Import torch and other required modules
import torch

Function 1 - torch.cross()

The cross product in Mathematics refers to an operation on two vector that results in a new vector that's perpendicular to both of these.

This function takes the following parameters:

  • input (Tensor) – the input tensor.
  • other (Tensor) – the second input tensor
  • dim (int, optional) – the dimension to take the cross-product in.
  • out (Tensor, optional) – the output tensor.

inputand other are pretty self-explanatory. As for dim, it refers to the dimension or level inside the tensor. For example, a dim of 1

# Example 1 - working
a = torch.randn(3, 3)
b = torch.randn(3, 3)

torch.cross(a, b, dim=1)

In this example we generate two tensors used as inputs. Then we run torch.cross on both of them, using a dimension value of 1.