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

Some Common Tensor Operations

But not necessarily intuitive

A short introduction about PyTorch and about the chosen functions.

  • Tensor.permute
  • Tensor.transpose
  • torch.stack
  • Tensor.unsqueeze
  • Tensor.view
# Import torch and other required modules
import torch
from PIL import Image
import numpy as np
import cv2

Tensor.permute(*dims)

This function is very useful because Pytorch has a different ordering of dimensions than some common source of data like cv2 or PIL images or the numpy arrays we use to represent images. But this is only one use. During the various operations in a Feedforward Network, one tensor operation output is an input to another one and this can repeat dozens or even hundreds for modern networks, so it's imperative to use this function enough to make it second nature.

To ilustrate its use, let's use images just for fun.

# Credit: https://www.sciencealert.com/can-you-catch-covid-19-from-your-pets-here-s-the-science
pil_image = Image.open('images/cat.jpg')