pytorch
  1. pytorch-tensors-introduction

Tensors Introduction - ( Tensors in PyTorch )

Heading h2

Syntax

import torch

# Creating a tensor
x = torch.tensor([1, 2, 3])

# Accessing values in a tensor
print(x[0])       # Output: 1
print(x.size())   # Output: torch.Size([3])

# Operations on tensors
y = torch.tensor([4, 5, 6])
z = x + y
print(z)          # Output: tensor([5, 7, 9])

Example

import torch

# Creating a 2x2 tensor
x = torch.tensor([[1, 2], [3, 4]])

# Accessing values in a tensor
print(x[0][0])        # Output: 1
print(x[1][0])        # Output: 3
print(x.size())       # Output: torch.Size([2, 2])

# Operations on tensors
y = torch.tensor([[5, 6], [7, 8]])
z = x + y
print(z)              # Output: tensor([[ 6,  8],
                      #                 [10, 12]])

Output

1
torch.Size([3])
tensor([5, 7, 9])

Explanation

A tensor is a multi-dimensional array of numerical values, similar to arrays in other programming languages. Tensors are a fundamental concept in PyTorch, which is a popular machine learning library in Python.

Tensors can have any number of dimensions and can be created using the torch.tensor() function. You can access values in a tensor using indexing and perform operations on tensors, such as addition, subtraction, multiplication, and more.

Use

Tensors are used heavily in PyTorch for numerical computations required in machine learning and deep learning applications. Tensors can represent features, input data, and output data in machine learning models.

Important Points

  • Tensors are multi-dimensional arrays of numerical values
  • Tensors can be created using the torch.tensor() function
  • You can access values in a tensor using indexing
  • Tensors can be used for numerical computations required in machine learning and deep learning applications

Summary

In summary, tensors are a fundamental concept in PyTorch and are used heavily in machine learning and deep learning applications. Tensors represent multi-dimensional arrays of numerical values and can be created using the torch.tensor() function. You can access values in a tensor using indexing and perform various operations on tensors.

Published on: