PyTorch Basic Operations

Goal

This post aims to introduce basic PyTorch operations e.g., addition, multiplication,

Libraries

In [2]:
import numpy as np
import pandas as pd
import torch

Create a Tensor

In [5]:
t_x1 = torch.Tensor([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9]])

t_x2 = torch.Tensor([[9, 8, 7],
                     [6, 5, 4],
                     [3, 2, 1]])
print(t_x1)
print(t_x2)
tensor([[1., 2., 3.],
        [4., 5., 6.],
        [7., 8., 9.]])
tensor([[9., 8., 7.],
        [6., 5., 4.],
        [3., 2., 1.]])

Addition

+ operator

In [6]:
t_x1 + t_x2
Out[6]:
tensor([[10., 10., 10.],
        [10., 10., 10.],
        [10., 10., 10.]])

torch.add method

In [7]:
torch.add(t_x1, t_x2)
Out[7]:
tensor([[10., 10., 10.],
        [10., 10., 10.],
        [10., 10., 10.]])
In [8]:
torch.add(t_x1, -t_x2)
Out[8]:
tensor([[-8., -6., -4.],
        [-2.,  0.,  2.],
        [ 4.,  6.,  8.]])

Multiplication

Operator

In [9]:
t_x1 * t_x2
Out[9]:
tensor([[ 9., 16., 21.],
        [24., 25., 24.],
        [21., 16.,  9.]])

torch.mm method

In [11]:
torch.mm(t_x1, t_x2)
Out[11]:
tensor([[ 30.,  24.,  18.],
        [ 84.,  69.,  54.],
        [138., 114.,  90.]])

Inner product torch.dot

In [13]:
print(t_x1[:, 1], t_x2[:, 1])
torch.dot(t_x1[:, 1], t_x2[:, 1])
tensor([2., 5., 8.]) tensor([8., 5., 2.])
Out[13]:
tensor(57.)

Trace

In [15]:
torch.trace(t_x1)
Out[15]:
tensor(15.)

Diag

In [16]:
torch.diag(t_x1)
Out[16]:
tensor([1., 5., 9.])

Determinant

In [17]:
torch.det(t_x1)
Out[17]:
tensor(0.)

Comments

Comments powered by Disqus