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

5 Functions of the PyTorch Tensors for Beginners

Introduction

  • What is PyTorch?

    On its official site, PyTorch is defined as a Python-based scientific computing package that targets to replace NumPy, and use the power of GPUs. It is also a platform to perform deep learning algorithms

  • What is a Tensor?

    A tensor is a number, vector, matrix. Tensors and matrix are often confused with one another. Tensors are more generalized vectors. Tensors are arrays but not every arrays are tensors See more.

Now that you have a basic understanding of Pytorch and Tensors, we start with the honorary mention of the torch.tensor() and move on with the list of 5 interesting functions to know.

  1. Function 1 - torch.randn()
  2. Function 2 - torch.reshape()
  3. Function 3 - torch.from_numpy()
  4. Function 4 - torch.isnan()
  5. Function 5 - torch.argmax()
# Import torch and other required modules
import torch

Honorary Mention - torch.tensor()

torch.tensor is a multi-dimensional matrix containing elements of a single data type.

# Example 1 - working
t1 = torch.tensor(1)
t2 = torch.tensor(1.)
tbool = torch.tensor(True)
print(f't1 has type {t1.dtype}\nt2 has type {t2.dtype}\n\
tbool has type {tbool.dtype}')
t1 has type torch.int64 t2 has type torch.float32 tbool has type torch.bool

Tensors can be defined as either an integer, floating point or a boolean value. Torch defines nine tensor types. Note: It is preferred to use floating point type than integer type.