Two-Dimensional Tensors in Pytorch
Last Updated :
30 Aug, 2021
PyTorch is a python library developed by Facebook to run and train machine learning and deep learning models. In PyTorch everything is based on tensor operations.
Two-dimensional tensors are nothing but matrices or vectors of two-dimension with specific datatype, of n rows and n columns.
Representation: A two-dimensional tensor has the below representation.
torch.tensor([[3,2,1]
[6,5,4]
[9,8,7]])
Creation of Two-Dimensional Tensors:
We can create a tensor by passing a list of data, or randomly generating values with randn and also with arrange function that takes values within certain intervals.
Example :
Python3
# importing library
import torch
# list of data in 1d form
y=torch.tensor([2.5,5.6,8.1,4.6,3.2,6.7])
# reshaping it to 2d
x=y.view(2,3)
print('First tensor is: {}'.format(x),'\nSize of it:{}'.format(x.size()),
'\ntype of tensor:{}\n'.format(x.dtype))
# random values of size 2X2
x2=torch.randn(2,2)
print('Second tensor is: {}'.format(x2),'\nSize of it:{}'.format(x2.size()),
'\ntype of tensor:{}\n'.format(x2.dtype))
# integers within this range
y1=torch.arrange(0,8)
x1=y1.view(4,2)
print('Third tensor is: {}'.format(x1),'\nSize of it:{}'.format(x1.size()),
'\ntype of tensor:{}'.format(x1.dtype))
Output:
First tensor is: tensor([[2.5000, 5.6000, 8.1000],
[4.6000, 3.2000, 6.7000]])
Size of it:torch.Size([2, 3])
type of tensor:torch.float32
Second tensor is: tensor([[1.2532, 1.3558],
[0.5496, 1.7828]])
Size of it:torch.Size([2, 2])
type of tensor:torch.float32
Third tensor is: tensor([[0, 1],
[2, 3],
[4, 5],
[6, 7]])
Size of it:torch.Size([4, 2])
type of tensor:torch.int64
Multiplication of tensors
Multiplication of tensors can be either element-wise multiplication(multiplying each element by element) or metrics multiplication (multiplying the corresponding column with the corresponding row). In deep learning, we use the concept of metrics multiplication with the required size.
Example :
Python3
import torch
a=torch.arrange(0,9)
# reshaping data
a=mat_a.view(3,3)
b=torch.arrange(0,9)
# reshaping data
b=mat_b.view(3,3)
mat_mul=torch.matmul(mat_a,mat_b)
elem_mul=torch.mul(mat_a,mat_b)
print('Tensor after elementwise multiplication:{}'.format(elem_mul),
'\n Tensor after matrix multiplication: {}'.format(mat_mul))
Output:
Tensor after elementwise multiplication:tensor([[ 0, 1, 4],
[ 9, 16, 25],
[36, 49, 64]])
Tensor after matrix multiplication: tensor([[ 15, 18, 21],
[ 42, 54, 66],
[ 69, 90, 111]])
Accessing elements:
In the tensor, we can access any column or row values through slicing, and for the particular elements we use indexing. To obtain only the value in the tensor we use .item().
Example :
Python3
import torch
# defining the tensor
x4=torch.arrange(4,13)
y4=x4.view(3,3)
# slicing is performed
print('First column has the values:{}'.format(y4[:,0]))
print('Second row has the values:{}'.format(y4[1,:]))
# indexing a particular element
print('Data at the index 1,2 :{}'.format(y4[1][2]))
Output:
First column has the values:tensor([ 4, 7, 10])
Second row has the values:tensor([7, 8, 9])
Data at the index 1,2 :9
Three-dimensional tensors:
Three-dimensional tensors are nothing but matrices or vectors of rank 3. A 3d tensor is created by adding another level with brackets to that of the two-dimensional vector. In image processing, we use RGB images that have 3 dimensions of color pixels.
Python3
import torch
# tensor with 3 dimension
x=torch.tensor([[[11,12,13],[14,15,16],[17,18,19]]])
# 1d tensor
x1=torch.arrange(10,19)
# reshaping it to 3d tensor
x1=x1.view(1,3,3)
print(x,'\n',x1)
Output:
tensor([[[11, 12, 13],
[14, 15, 16],
[17, 18, 19]]])
tensor([[[10, 11, 12],
[13, 14, 15],
[16, 17, 18]]])
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read