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

5 Interesting torch.Tensor Functions

torch.Tensor - Multi-Dimensional Matrix

PyTorch is an open-source Python machine learning library that offers 2 high-level features:

  • Tensor computation (similar to NumPy) with GPU acceleration
  • Automatic differentiation for building and training neural networks

PyTorch can be easily integrated and extended using popular Python packages like NumPy, SciPy, and Cython. PyTorch was developed by FAIR (Facebook’s AI Research Lab) and can be used in various applications ranging from computer vision to natural language processing.

Before diving deep into PyTorch, it is pertinent to master the most fundamental PyTorch concept – the Tensor. Conceptually, PyTorch Tensor is very similar to NumPy but with GPU support to accelerate numeric computations. Here we will look at 5 interesting torch.Tensor functions, their usage and limitations. The 5 functions that will be reviewed include:

  • torch.erfc : Computes the complementary error function of each element of input
  • torch.where : Choose output based on condition
  • torch.eig : Computes the eigenvalues and eigenvectors of a real square matrix
  • torch.lstsq : Computes the solution to the least squares and least norm problems
  • torch.svd : Singular value decomposition of an input
# Import torch and other required modules
import torch
import numpy as np

Function 1 - torch.erfc

Computes the complementary error function of each element of input.
Complementary error function: 1 - erf(x)

torch.erfc(input, out=None) → Tensor

  • input(Tensor) - the input tensor
  • out(Tensor, optional) - output tensor
# Example 1 - working
a = torch.randn(2,2)
print("a:\n", a)
erfc_a = torch.erfc(a)
print("\nerfc(a):\n", erfc_a)
a: tensor([[-0.5205, -0.2268], [-0.3516, -0.9108]]) erfc(a): tensor([[1.5383, 1.2516], [1.3810, 1.8023]])

Example 1:

  • a is (2 by 2) random normal tensor
  • Using torch.erfc(a) - the complementary error function of each element of a was computed