pytorch
  1. pytorch-two-dimensional-tensor

Two-Dimensional Tensor - ( Tensors in PyTorch )

Heading h2

Syntax

import torch

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

# Accessing individual elements of the tensor
elem = tensor[0][1]

# Performing arithmetic operations on tensors
sum = tensor + tensor
diff = tensor - tensor
prod = tensor * tensor
div = tensor / tensor

Example

import torch

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

# Accessing individual elements of the tensor
elem = tensor[0][1]

# Performing arithmetic operations on tensors
sum = tensor + tensor
diff = tensor - tensor
prod = tensor * tensor
div = tensor / tensor

# Printing the results
print("Original Tensor:\n", tensor)
print("Accessing element at index [0,1]:\n", elem)
print("Sum:\n", sum)
print("Difference:\n", diff)
print("Product:\n", prod)
print("Division:\n", div)

Output

Original Tensor:
 tensor([[1, 2],
         [3, 4]])
Accessing element at index [0,1]:
 tensor(2)
Sum:
 tensor([[2, 4],
         [6, 8]])
Difference:
 tensor([[0, 0],
         [0, 0]])
Product:
 tensor([[ 1,  4],
         [ 9, 16]])
Division:
 tensor([[1., 1.],
         [1., 1.]])

Explanation

In PyTorch, a tensor is a multi-dimensional array of numbers used to represent and perform operations on numerical data. A 2-D tensor is a matrix, which can be thought of as an array of arrays.

The syntax for creating a 2-D tensor in PyTorch is as follows:

import torch

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

Individual elements of a 2-D tensor can be accessed by providing the row and column indices. For example, to access the element at row 0 and column 1, we can use the following syntax:

elem = tensor[0][1]

Arithmetic operations can also be performed on tensors. The various operations, such as addition, subtraction, multiplication, and division can be performed using the standard arithmetic operators. For example, to add two tensors, we can use the following syntax:

sum = tensor + tensor

Use

Two-dimensional tensors are commonly used for performing matrix operations, such as matrix multiplication, matrix addition, and matrix inversion. They can be used in a variety of applications, such as image processing, natural language processing, and machine learning.

Important Points

  • A 2-D tensor is a matrix, represented as an array of arrays
  • Arithmetic operations, such as addition, subtraction, multiplication, and division can be performed on tensors
  • Two-dimensional tensors are commonly used for performing matrix operations, such as matrix multiplication, matrix addition, and matrix inversion

Summary

In summary, a two-dimensional tensor is a matrix in PyTorch and is represented as an array of arrays. You can perform arithmetic operations on 2-D tensors and they are commonly used for performing matrix operations in various applications.

Published on: