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

5 Powerful Interesting Pytorch functions For Data Science Beginners

WHAT IS PYTORCH?
It’s a Python-based scientific computing package targeted at two sets of audiences:

A replacement for NumPy to use the power of GPUs
a deep learning research platform that provides maximum flexibility and speed

What are Tensors?
Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.
The following are the 5 powerful functions

  • torch.from_numpy()
  • torch.split()
  • torch.transpose()
  • torch.unbind()
  • torch.randint()

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
# Import torch and other required modules
import torch

Function 1 - torch.from_numpy

A numpy array can be easily converted to a tensor using the functioin above

# Example 1 - Given a numpy array below

import numpy as np

x = np.array([[10., 20.], [30., 40.]])
 
# this can be change to tensor as follows
y = torch.from_numpy(x)
x, y
(array([[10., 20.],
        [30., 40.]]),
 tensor([[10., 20.],
         [30., 40.]], dtype=torch.float64))