PyTorch Basics
PyTorch Tensors: Creation, Manipulation, and Operations
The basic building block of PyTorch are the Tensors which are data structures similar to the NumPy Arrays. They are similar to the arrays and matrices that we can use to encode and decode inputs and outputs of a model as well as the model’s parameters. The main difference between the NumPy array and tensors is that tensors can run on tensors can run on GPUs or other hardware accelerators.
Tensor_name = torch.tensor([value 1 , value 2 , ….. Value n ])
Where the ‘torch.tensor() is the method to create the tensors.
The below code snippets show the creation of Tensors and their manipulation through the operations. In this example, we are creating tensor1 and tensor2 to store the data and perform the operations.
Python
import torch # Create a tensor from a list tensor1 = torch.tensor([ 1 , 2 , 3 ]) print ( "Tensor from list:" , tensor1) # Create a tensor of zeros with shape (2, 3) tensor2 = torch.zeros( 2 , 3 ) print ( "Tensor of zeros:" , tensor2) # Create a random tensor with shape (3, 2) tensor3 = torch.rand( 3 , 2 ) print ( "Random tensor:" , tensor3) # Performing operations on Tensors # Addition result_add = tensor1 + tensor2 print ( "Addition result:" , result_add) # Multiplication result_mul = tensor2 * 5 print ( "Multiplication result:" , result_mul) # Matrix multiplication result_matmul = torch.matmul(tensor2, tensor3) print ( "Matrix multiplication result:" , result_matmul) |
Output:
Tensor from list: tensor([1, 2, 3])
Tensor of zeros: tensor([[0., 0., 0.],
[0., 0., 0.]])
Random tensor: tensor([[0.9161, 0.3915],
[0.7185, 0.7726],
[0.4831, 0.0832]])
Addition result: tensor([[1., 2., 3.],
[1., 2., 3.]])
Multiplication result: tensor([[0., 0., 0.],
[0., 0., 0.]])
Matrix multiplication result: tensor([[0., 0.],
[0., 0.]])
Start learning PyTorch for Beginners
Machine Learning helps us to extract meaningful insights from the data. But now, it is capable of mimicking the human brain. This is done using neural networks, which contain the various interconnected layers of nodes containing the data. This data is passed to forward layers. Subsequently, the model learns from the data and predicts output for the new data.
PyTorch helps us to create and train these neural networks that act like our brains and learn from the data.
Table of Content
- What is Pytorch?
- Why use PyTorch?
- How to install Pytorch ?
- PyTorch Basics
- Autograd: Automatic Differentiation in PyTorch
- Neural Networks in PyTorch
- Working with Data in PyTorch
- Intermediate Topics in PyTorch
- Validation and Testing
- Frequently Asked Questions