Tensor Manipulation

Learn to manipulate PyTorch tensors.

In the coming lessons, we’ll explore neural networks with the PyTorch library. Images are a form of data easily consumable by a neural network. Therefore, in many situations, neural networks can help us in automated inspection.

Before diving into the internal operators of a neural network, we must take a closer look at the data format that each component will process as input and output: the tensor.

What is a tensor?

A tensor is a multidimensional array.

Note: If you have used the NumPy module, you’ve probably manipulated numpy.array objects, which are tensors.

You can create a numpy.array object and convert it to a torch.Tensor object with the function torch.from_numpy().

Press + to interact
import torch # import PyTorch
import numpy as np
arr1 = np.array([[1., 2., 3.], [4., 5., 6.]])
arr1_tsr = torch.from_numpy(arr1)
print(f"arr1: \n{arr1}\n")
print(f"arr1_tsr: \n{arr1_tsr}")

In line 5, we create a torch.Tensor object from a numpy.array object.

Conversely, we can create a numpy.array object from a tensor with the Tensor.numpy() method.

Press + to interact
import torch
import numpy as np
# Create a tensor of normally distributed random numbers (mu=0, sigma=1) of size (3, 4)
t1 = torch.randn(3, 4)
t1_arr = t1.numpy()
print(f"t1: \n{t1}\n")
print(f"t1_arr: \n{t1_arr}")

In line 5, we create a random tensor sampled from a normal distribution (μ= ...