🎓 A1Learner
🔍
0 of 79 lessons completed

PyTorch Random Tensors

Random tensors hold values drawn by chance inside a chosen range. A seed makes the same chance values appear again on the next run.

Uniform values with rand

A seed is the number that starts the random drawing. With seed 7, rand draws the same decimals every run.

import torch
torch.manual_seed(7)
print(torch.rand(3))

Bell-shaped values with randn

Randn draws decimals centred on 0. Most values land near 0 and a few land far away.

torch.manual_seed(7)
print(torch.randn(3))

Whole numbers with randint

Randint draws whole numbers in a range. The range 1 to 10 stops before 10, so 9 is the largest draw.

torch.manual_seed(7)
print(torch.randint(1, 10, (4,)))

The seed repeats the result

Setting the same seed again restarts the drawing. The second draw then matches the first.

torch.manual_seed(3)
print(torch.rand(2))
torch.manual_seed(3)
print(torch.rand(2))

Example

import torch

torch.manual_seed(42)
first = torch.rand(2, 3)
print(first)
torch.manual_seed(42)
second = torch.rand(2, 3)
print(second)

Key points

  • Random values are drawn by chance inside set limits
  • Seed: the number that starts a run of random draws
  • Use torch.manual_seed to set the seed before drawing
  • Use rand to draw decimals between 0 and 1
  • Use randn to draw decimals centred on 0
  • Use randint to draw whole numbers, with the size giving the shape

In this example, the program sets the seed to 42. It draws a table of two rows and three columns with rand. It then sets the seed to 42 again. The second draw prints the same table. The seed makes the random table repeat exactly.

Note

With no seed set, each run draws different values, so seeded draws keep lessons repeatable.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does torch.manual_seed(42) do?