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

PyTorch and tensors

I/O

One of the hairiest problems is always data loading and converting from one library to another. We'll take a look at examples of this, specifically interacting with Numpy. It is also important to create dummy tensors to test, we'll see this too.

  • from_numpy
  • numpy
  • zeros
  • new_zeros
  • rand
# Import torch and other required modules
import torch

Function 1 - torch.from_numpy

It is very common to need to interact with numpy, converting arrays to and from Pytorch tensors.

# Example 1 - Get a tensor from a numpy array

import numpy as np

np_inputs = np.array([[1, 2], [3, 4.]])
print(np_inputs)
tensor_input = torch.from_numpy(np_inputs)

print(tensor_input)
[[1. 2.] [3. 4.]] tensor([[1., 2.], [3., 4.]], dtype=torch.float64)

Simple list to numpy array, numpy array to tensor example.