PyTorch torch.randint() Method

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

  1. low (int, optional): Lowest integer to be drawn from the distribution. Default: 0.
  2. high (int): One above the highest integer to be drawn from the distribution.
  3. size (tuple): A tuple defining the shape of the output tensor.
  4. out (Tensor, optional): The output tensor.
  5. dtype (torch.dtype, optional): The desired data type of the returned tensor. Default: torch.long.
  6. layout (torch.layout, optional): The desired layout of the returned tensor. Default: torch.strided.
  7. device (torch.device, optional): The desired device of the returned tensor. Default: If None, use the current device for the default tensor type.
  8. 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

torch.randn()

torch.stack()

torch.cat()

torch.matmul()

torch.split()

torch.unsqueeze()

Leave a Comment