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()
.
import torch # import PyTorchimport numpy as nparr1 = 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 ...
Get hands-on with 1400+ tech skills courses.