Basic operations in PyTorch
Before we start building neural networks with PyTorch, it is essential to understand the basics of how to manipulate data using this library. In PyTorch, the fundamental unit of data is the tensor, a generalization of matrices to an arbitrary number of dimensions (also known as a multidimensional array).
Getting ready
A tensor can be a number (a 0D tensor), a vector (a 1D tensor), a matrix (a 2D tensor), or any multi-dimensional data (a 3D tensor, a 4D tensor, and so on). PyTorch provides various functions to create and manipulate tensors.
How to do it…
Let’s start by importing PyTorch:
import torch
We can create a tensor in PyTorch using various techniques. Let’s start by creating tensors from lists:
t1 = torch.tensor([1, 2, 3]) print(t1) t2 = torch.tensor([[1, 2], [3, 4]]) print(t2)
PyTorch can seamlessly integrate with NumPy, allowing for easy tensor creation from NumPy arrays:
import numpy as np np_array...