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

PyTorch Functions

Interesting and Useful

PyTorch is ML framework with added flexibility which is perfect for researchers of ML work with it.

  • from_numpy / numpy
  • ones / randn / new_full
  • device
  • view
  • backward
# Import torch and other required modules
import torch
import numpy as np

Function 1 - from_numpy() / numpy()

It is very easy to change from numpy array to tensor in torch.

# Example 1 
n_array = np.array([[1, 2], [3, 4]])
t_tensor = torch.from_numpy(n_array) # tensor from numpy array
n_array_sec = t_tensor.numpy() # numpy array from tensor
print(n_array)
print(t_tensor)
print(n_array_sec)
[[1 2] [3 4]] tensor([[1, 2], [3, 4]], dtype=torch.int32) [[1 2] [3 4]]

We first created a numpy array n_array. Then we easily changed it to torch tensor t_tensor. Lastly, we changed from torch tensor to numpy array again which is n_array_sec