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

Different Ways to Create a Tensor In PyTorch

An short introduction about PyTorch and about the chosen functions. Simply put, PyTorch is a library for processing tensors. A tensor is a number, vector, matrix, or any n-dimensional array. Let's create a tensor with a single number. To perform various operations with tensors, PyTorch provides us numerous methods or functions. Today, we will discuss about methods that are used to create tensors.

Methods for creating a tensor

  • zeros
  • ones
  • full
  • arange
  • linspace
  • rand
  • randint
  • eye
  • complex

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



# ### Methods for operations involving tensors
# - cat
# - chunk
# - dstack
# - gather
# - hstack
# - vstack
# - narrow
# - reshape
# - split
# - transpose
# Import torch and other required modules
import torch

Function 1 - zeros

This method returns a tensor where all elements are zeros, of specified size (shape). The size can be given as a tuple or a list or neither.

# Example 1 - working (change this)
zeros_tensor1 = torch.zeros(3,2)
zeros_tensor1
tensor([[0., 0.],
        [0., 0.],
        [0., 0.]])