pytorch
  1. pytorch-basics-of-pytorch

Basics of PyTorch - ( PyTorch Tutorial )

Heading h2

Syntax

PyTorch

import torch

# Create a Tensor
x = torch.Tensor([1, 2, 3, 4])
print(x)

# Indexing a Tensor
print(x[0])

# Reshaping a Tensor
x = x.view(2, 2)
print(x)

# Creating a Random Tensor
r = torch.rand(2, 2)
print(r)

# Matrix multiplication
m = torch.ones(2, 2)
n = torch.ones(2, 2)
p = torch.mm(m, n)
print(p)

Example

PyTorch

import torch

# Create a Tensor
x = torch.Tensor([1, 2, 3, 4])
print(x)

# Indexing a Tensor
print(x[0])

# Reshaping a Tensor
x = x.view(2, 2)
print(x)

# Creating a Random Tensor
r = torch.rand(2, 2)
print(r)

# Matrix multiplication
m = torch.ones(2, 2)
n = torch.ones(2, 2)
p = torch.mm(m, n)
print(p)

Output

PyTorch

tensor([1., 2., 3., 4.])
tensor(1.)
tensor([[1., 2.],
        [3., 4.]])
tensor([[0.7565, 0.7031],
        [0.1428, 0.0927]])
tensor([[2., 2.],
        [2., 2.]])

Explanation

PyTorch is a machine learning library based on the Torch library. It is used for applications such as computer vision, natural language processing, and deep learning. PyTorch is based on tensors, which are similar to arrays in Numpy.

In the above example, we create a PyTorch tensor and perform various operations on it. We create a tensor using the torch.Tensor function, index the tensor using square brackets, and reshape it using the view function. We also create a random tensor using the torch.rand function and perform matrix multiplication using the mm function.

Use

PyTorch is used in a variety of machine learning applications including computer vision, natural language processing, and deep learning. It is especially useful for deep learning because it provides automatic differentiation, a technique for computing the gradient of a function.

Important Points

  • PyTorch is a machine learning library based on the Torch library
  • PyTorch is based on tensors, which are similar to arrays in Numpy
  • PyTorch supports automatic differentiation, a technique for computing the gradient of a function

Summary

In this PyTorch tutorial, we learned how to create tensors, index tensors, reshape tensors, create random tensors, and perform matrix multiplication. We also learned about automatic differentiation, a technique for computing the gradient of a function, which is a core feature of PyTorch. PyTorch is a powerful library for machine learning and deep learning and is used in a variety of applications including computer vision and natural language processing.

Published on: