Let’s throw some “Torch” on Tensor Operations

Discussing on 5 Basic most used Tensor Operations

Deep learning allows us to carry out a very wide range of complicated tasks. In order to carry out our tasks effectively, we need a tool which is flexible. Pytorch gives us this option because of its simplicity. It provides accelerated operations using GPU’s (Graphical Processing Units). Due to this reason of Pytorch being a high performance library that it has gained its popularity. The below notebook consists of some essential functions which are very useful in carrying out tensor operations. These operations are used for multi-dimensional tensors & for arithmetic operations.

# Windows
# !pip install numpy torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio==0.7.0 -f https://download.pytorch.org/whl/torch_stable.html
# Import torch and other required modules
import torch

1. General Operations — Inverse Function

a = torch.randn(2,3,3)
print(a)
torch.inverse(a)
a = torch.rand(4,4)
print(a)
torch.inverse(a)
a = torch.rand(4,3)
print(a)
torch.inverse(a)
RuntimeError: A must be batches of square matrices, but they are 3 by 4 matrices

2. Creation Operations — Complex Function

real = torch.tensor([2,1], dtype=torch.float32)
imag = torch.tensor([2,3], dtype=torch.float32)
a= torch.complex(real, imag)
a.dtype
real = torch.rand(2,3)
imag = torch.rand(1,3)
print(real)
print(imag)
x = torch.complex(real, imag,)
print(x)
real = torch.tensor(2., 4)
imag = torch.tensor(7., 3)
x = torch.complex(real, imag,)
x
TypeError: tensor() takes 1 positional argument but 2 were given

3. Mutating Tensor Data — Transpose Function

a = torch.rand(2,3,5)
print(a)
torch.transpose(a,1,2)
a = torch.rand(2,5)
print(a)
torch.transpose(a, -1, 0)
a = torch.rand(2,5)
print(a)
torch.transpose(a)
TypeError: transpose() received an invalid combination of arguments - got (Tensor), but expected one of: * (Tensor input, name dim0, name dim1) * (Tensor input, int dim0, int dim1)

Arithematic Operations — Add Function

a = torch.randn(10)
print(a)
torch.add(a,5)
a = torch.rand(5)
b = torch.rand(5)
print(a)
print(b)
torch.add(a,b)
a = torch.rand(10)
b = torch.rand(5)
torch.add(a,b)
RuntimeError: The size of tensor a (10) must match the size of tensor b (5) at non-singleton dimension 0

Reduction Operations — Amax Function

a = torch.rand(3,2)
print(a)
torch.amax(a, dim = -1)
a = torch.rand(5)
print(a)
torch.amax(a, dim=-2)
a = torch.tensor([[3,2], [1,2], [4,7],[6,5]])
print(a)
torch.amax(a, dim = 1)
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got -2)

Conclusion

Reference Links

M.Sc Data Analytics (QUB 2021-22 batch) l Experienced HR Analyst l Travel-freak l French beginner l

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store