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

Basic PyTorch Tensor Operations for creating tensors

PyTorch is an open source machine learning library used for various applications and is developed by Facebook's AI Research lab (FAIR). Its primary interface is Python but PyTorch also has a C++ interface. A number of pieces of Deep Learning software are built on top of PyTorch.

Two high-level features of PyTorch are:

  • Tensor computing via graphics processing units (GPU)
  • Deep neural networks

A tensor is a number, vector, matrix, or any n-dimensional array and is PyTorch is a library for processing tensors. PyTorch Tensors are similar to NumPy Arrays and PyTorch supports various sub-types of Tensors.

  • torch.from_numpy
  • torch.arange
  • torch.ones
  • torch.complex
  • torch.full

Before we begin, let's install and import PyTorch

# Uncomment and run the appropriate command for your operating system, if required

# Linux / Binder
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# Windows
!pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html

# MacOS
# !pip install numpy torch torchvision torchaudio
Looking in links: https://download.pytorch.org/whl/torch_stable.html Requirement already satisfied: numpy in /opt/conda/lib/python3.8/site-packages (1.19.2) Requirement already satisfied: torch==1.7.0+cpu in /opt/conda/lib/python3.8/site-packages (1.7.0+cpu) Requirement already satisfied: torchvision==0.8.1+cpu in /opt/conda/lib/python3.8/site-packages (0.8.1+cpu) Requirement already satisfied: torchaudio==0.7.0 in /opt/conda/lib/python3.8/site-packages (0.7.0) Requirement already satisfied: dataclasses in /opt/conda/lib/python3.8/site-packages (from torch==1.7.0+cpu) (0.6) Requirement already satisfied: future in /opt/conda/lib/python3.8/site-packages (from torch==1.7.0+cpu) (0.18.2) Requirement already satisfied: typing-extensions in /opt/conda/lib/python3.8/site-packages (from torch==1.7.0+cpu) (3.7.4.3) Requirement already satisfied: pillow>=4.1.1 in /opt/conda/lib/python3.8/site-packages (from torchvision==0.8.1+cpu) (8.0.0)
# Import torch and other required modules
import torch
import numpy as np

Function 1 - torch.from_numpy

  • torch.from_numpy(ndarray) → Tensor

Creates a Tensor from a numpy.ndarray. The function torch.from_numpy() helps to convert the numpy array into a tensor in PyTorch. It takes the input as a numpy array of nd dimensions and the output type is tensor. The returned tensor and ndarray share the same memory. The returned tensor can be resized.

# Example 1 - Creating a tensor from numpy array
arr =np.array([[10, 11, 12], [18, 19, 20]])
arr
array([[10, 11, 12],
       [18, 19, 20]])