When developing neural networks with PyTorch, there might be cases where you find random tensors are useful, such as when you need synthetic data for testing or experimentation purposes or when you want to sample from a probability distribution or perform stochastic operations.
This practical, example-based article will walk you through a couple of different ways to generate random tensors in PyTorch. Without any further ado, let’s get to the main points.
Using torch.rand(*size) function
You can use the torch.rand(*size) function to create a tensor filled with random numbers from a uniform distribution on the interval [0, 1). The shape of the tensor is defined by the variable argument size.
The example below creates a random tensor of shape (4, 4):
import torch
random_tensor = torch.rand(4, 4)
print(random_tensor)
If you want to get the same result every time you re-run your code, just add a seed:
import torch
torch.manual_seed(111)
random_tensor = torch.rand(4, 4)
print(random_tensor)
Output:
tensor([[0.7156, 0.9140, 0.2819, 0.2581],
[0.6311, 0.6001, 0.9312, 0.2153],
[0.6033, 0.7328, 0.1857, 0.5101],
[0.7545, 0.2884, 0.5775, 0.0358]])
See also: Using manual_seed() function in PyTorch.
In the rest of this article, I will use seed 111 so that we will get the same outputs. This is optional, you can omit the seed if you don’t like it.
Using torch.randint(low=0, high, size) function
The torch.randint(low=0, high, size) can be used to create a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive). The shape of the tensor is defined by the variable argument size.
This example creates a tensor of shape (3, 3) filled with random integers generated uniformly between -5 (inclusive) and 5 (exclusive):
import torch
torch.manual_seed(111)
random_tensor = torch.randint(-5, 5, (3, 3))
print(random_tensor)
Output:
tensor([[-5, -3, 1],
[ 3, -3, 2],
[-4, 1, -1]])
Using torch.rand_like(input) function
What if you already have a tensor and what you want is another tensor of the same size but filled with random values? When this is the case, you can use the torch.rand_like(input) function. It will create a tensor with the same size as the input that is filled with random numbers from a uniform distribution on the interval [0, 1).
Example:
import torch
torch.manual_seed(111)
# Create a tensor of shape (2, 2) filled with ones
input_tensor = torch.ones(2, 2)
# Create a tensor with the same size as input_tensor that is filled with random numbers from a uniform distribution on the interval [0, 1)
random_tensor = torch.rand_like(input_tensor)
print(random_tensor)
Output:
ensor([[0.7156, 0.9140],
[0.2819, 0.2581]])