Do a tutorial - random numbers in pytorch

Ulf Hamster 2 min.
python pytorch tutorial

boilerplate

%%capture 
!pip install torch==1.1.0
# load packages
import torch
import numpy as np

# check version
print(torch.__version__)

# set GPU if available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)

# reproducibility
np.random.seed(42)  # numpy seed
torch.manual_seed(42)  # pytorch seed
if torch.backends.cudnn.enabled:  # CuDNN deterministic mode
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False
1.1.0
cuda:0

Random Numbers

torch.manual_seed(42)
x = torch.rand(size=(3, 4), device=device)
print(x)
tensor([[0.7332, 0.8099, 0.8759, 0.9129],
        [0.2111, 0.7770, 0.0193, 0.9539],
        [0.1923, 0.4240, 0.3189, 0.7902]], device='cuda:0')
# repeat it
torch.manual_seed(42)
x = torch.rand(size=(3, 4), device=device)
print(x)
tensor([[0.7332, 0.8099, 0.8759, 0.9129],
        [0.2111, 0.7770, 0.0193, 0.9539],
        [0.1923, 0.4240, 0.3189, 0.7902]], device='cuda:0')

Normal Distributed

torch.manual_seed(42)
x = torch.randn(size=(3, 4), device=device)
print(x)
tensor([[ 0.6226,  0.8774,  1.1547,  1.3588],
        [-0.8027,  0.7622, -2.0681,  1.6839],
        [-0.8694, -0.1916, -0.4707,  0.8071]], device='cuda:0')

Random Integers

torch.manual_seed(42)
x = torch.randint(size=(3, 4), high=99, device=device)
print(x)
tensor([[63, 60, 68, 44],
        [84, 73, 32, 30],
        [12, 66, 10, 86]], device='cuda:0')

Permutation

torch.manual_seed(42)
x = torch.randperm(n=100, device=device)
print(x)
tensor([42, 96, 62, 98, 46, 95, 60, 24, 78, 16, 68, 70, 11, 13, 97, 52, 99, 19,
        71, 10, 89, 86, 18, 40,  5, 38,  9, 82, 83, 43, 32, 94, 67, 93, 75, 59,
        79,  1, 50, 73, 66, 45, 63, 58, 22,  3, 87,  4, 61, 51, 12, 74, 21, 20,
         6, 35, 44, 48, 37, 33, 15, 88, 31, 69, 27, 81, 85, 56,  7, 65, 47, 41,
        29, 80, 57, 84, 36, 17, 34, 72,  2, 91,  8, 53, 30, 90, 26, 23, 54, 76,
        14, 55,  0, 64, 77, 39, 25, 92, 49, 28], device='cuda:0')

Links