PyTorch torch.randint() method “returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive).”
Syntax
torch.randint(low=0, high, size, \*, generator=None, out=None, dtype=None,
layout=torch.strided, device=None, requires_grad=False)
Parameters
- low (int, optional): Lowest integer to be drawn from the distribution. Default: 0.
- high (int): One above the highest integer to be drawn from the distribution.
- size (tuple): A tuple defining the shape of the output tensor.
- out (Tensor, optional): The output tensor.
- dtype (torch.dtype, optional): The desired data type of the returned tensor. Default: torch.long.
- layout (torch.layout, optional): The desired layout of the returned tensor. Default: torch.strided.
- device (torch.device, optional): The desired device of the returned tensor. Default: If None, use the current device for the default tensor type.
- requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False.
Example 1: Generating a 2×3 tensor with integers between 0 and 4 (inclusive)
import torch
rand_int_tensor = torch.randint(5, (2, 3))
print(rand_int_tensor)
Output
tensor([[0, 2, 4],
[3, 2, 1]])
Example 2: Generating a 2×2 tensor with integers between 3 (inclusive) and 8 (exclusive)
import torch
rand_int_tensor_range = torch.randint(3, 8, (2, 2))
print(rand_int_tensor_range)
Output
tensor([[3, 4],
[4, 6]])
Example 3: Generating a 3×3 tensor with integers between 0 and 10 (inclusive) with a data type of torch.float32
import torch
rand_int_tensor_dtype = torch.randint(11, (3, 3), dtype=torch.float32)
print(rand_int_tensor_dtype)
Output
tensor([[ 5., 5., 2.],
[10., 6., 6.],
[ 0., 4., 3.]])
That’s it!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Machine Learning frameworks like PyTorch and Tensorflow is a testament to his versatility and commitment to the craft.