Two-Dimensional Tensors in Pytorch
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.
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.
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]])
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().
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 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.
tensor([[[11, 12, 13], [14, 15, 16], [17, 18, 19]]]) tensor([[[10, 11, 12], [13, 14, 15], [16, 17, 18]]])
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course