basic_pytorch
PyTorch Basics
import torch
print(torch.cuda.is_available(), torch.cuda.device_count(), torch.cuda.get_device_name())True 1 NVIDIA GeForce GTX 1660 Ti
# Creating Tensor of random values
print(torch.rand(2, 2))
tensor([[0.9737, 0.4745],
[0.4930, 0.8542]])
# creating tensor from given list
x = torch.tensor([[0,0,1],[1,1,1],[0,0,0]])
print(x)tensor([[0, 0, 1],
[1, 1, 1],
[0, 0, 0]])
# editing tensors using python indexing
x[0][0] = 5
print(x)tensor([[5, 0, 1],
[1, 1, 1],
[0, 0, 0]])
# special creation functions
t_one = torch.ones(2, 2)
t_zero = torch.zeros(2, 2)
print(t_one)
print(t_zero)tensor([[1., 1.],
[1., 1.]])
tensor([[0., 0.],
[0., 0.]])
## standard mathematical operations
# adding matrices
print(t_zero + t_one)tensor([[1., 1.],
[1., 1.]])
# pulling out the value from a rank 0 tensor
val = torch.rand(1).item()
print(val)0.5833820700645447
## shifting tensors between CPU and GPU using `.to()` method
# CPU tensor
t_cpu = torch.rand(2)
print(t_cpu.device)
t_gpu = t_cpu.to("cuda")
print(t_gpu.device)cpu
cuda:0
# finding largest element and position of a tensor
t = torch.rand(2,2)
t_max = t.max()
t_arg = t.argmax()
val = t_max.item() # Converting tensor to python value
pos = t_arg.item()
print(t)
print(val, pos)tensor([[0.3132, 0.4692],
[0.8079, 0.9207]])
0.9206789135932922 3
# Change datatype being used by tensor
long_tensor = torch.tensor([[0,0,1],[1,1,1],[0,0,0]])
print(long_tensor.type())
float_tensor = long_tensor.to(dtype=torch.float32)
print(float_tensor.type())torch.LongTensor
torch.FloatTensor
# using in-place functions (denoted by `_` at the end) to conserve memory by not creating new tensors
random_tensor = torch.rand(2,2)
t_out = random_tensor.log2() # new tensor created
print(t_out)
print(random_tensor)
t_in = random_tensor.log2_() # in-place operation
print(t_in)
print(random_tensor)tensor([[-9.9785e-01, -2.3328e+00],
[-4.6030e-03, -5.5391e+00]])
tensor([[0.5007, 0.1985],
[0.9968, 0.0215]])
tensor([[-9.9785e-01, -2.3328e+00],
[-4.6030e-03, -5.5391e+00]])
tensor([[-9.9785e-01, -2.3328e+00],
[-4.6030e-03, -5.5391e+00]])
# reshaping tensors
flat_tensor = torch.rand(784)
viewed_tensor = flat_tensor.view(1,28,28)
print(viewed_tensor.shape)
reshaped_tensor = flat_tensor.reshape(1,28,28)
print(reshaped_tensor.shape)torch.Size([1, 28, 28])
torch.Size([1, 28, 28])
# rearranging the dimentions of tensors
hwc_tensor = torch.rand(640, 480, 3)
chw_tensor = hwc_tensor.permute(2,0,1)
print(chw_tensor.shape)torch.Size([3, 640, 480])
# Broadcasting smaller tensor to larger tensor
# requirement to boadcast (looking at dims from backwards) :
# - The two dimensions are equal.
# - One of the dimensions is 1
t_add = torch.rand(3, 3) + torch.rand(1, 3)
print(t_add)tensor([[0.6281, 0.1686, 0.4985],
[0.6248, 0.9454, 0.1637],
[0.4713, 0.7593, 0.3255]])