TORCH.TENSOR
A torch.Tensor is a multi-dimensional matrix containing elements of a single data type. Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.
Torch defines nine CPU tensor types and nine GPU tensor types:
A tensor can be constructed from a Python list or sequence using the torch.tensor() constructor
WHAT IS PYTORCH?
It’s a Python-based scientific computing package targeted at two sets of audiences:
A replacement for NumPy to use the power of GPUs
a deep learning research platform that provides maximum flexibility and speed
Chosen functions.
- torch.diagonal()
- torch.matmul()
- torch.inverse()
- torch.squeeze()
- torch.unique()
# Import torch and other required modules
import torch
import numpy as np
Function 1
torch.diagonal(input, offset=0, dim1=0, dim2=1)
Returns a partial view of input
with the its diagonal elements with respect to dim1
and dim2
appended as a dimension at the end of the shape.
The argument offset
controls which diagonal to consider:
-
If
offset
= 0, it is the main diagonal. -
If
offset
> 0, it is above the main diagonal. -
If
offset
< 0, it is below the main diagonal.
Applying torch.diag_embed()
to the output of this function with the same arguments yields a diagonal matrix with the diagonal entries of the input. However, torch.diag_embed()
has different default dimensions, so those need to be explicitly specified.
-
input (Tensor) – the input tensor. Must be at least 2-dimensional.
-
offset (int, optional) – which diagonal to consider. Default: 0 (main diagonal).
-
dim1 (int, optional) – first dimension with respect to which to take diagonal. Default: 0.
-
dim2 (int, optional) – second dimension with respect to which to take diagonal. Default: 1.
# Example 1 - working
a = torch.randn(3, 3)
a
tensor([[ 1.3418, 1.3554, 0.8112],
[-1.1586, 0.2967, 3.0477],
[-1.2395, 0.2124, 0.7688]])
torch.diagonal(a, 0)
tensor([1.3418, 0.2967, 0.7688])