PyTorch torch.randperm() Method

PyTorch torch.randperm() method “returns a random permutation of integers from 0 to n – 1.”

Syntax

torch.randperm(n, out=None, dtype=torch.int64, 
              layout=torch.strided, device=None, requires_grad=False)

Parameters

  1. n (int): The upper bound (exclusive) on the range of random integers to generate.
  2. out (Tensor, optional): The output tensor.
  3. dtype (torch.dtype, optional): The desired data type of the output tensor. Default: torch.int64.
  4. layout (torch.layout, optional): The desired layout of the output tensor. Default: torch.strided.
  5. device (torch.device, optional): The desired device of the output tensor. Default: If None, use the current device for the default tensor type.
  6. requires_grad (bool, optional): If autograd should record operations on the returned tensor. Default: False.

Example 1: How to Use torch.randperm() method

import torch

permuted_indices = torch.randperm(5)
print(permuted_indices)

Output

tensor([4, 3, 2, 0, 1])

Example 2: Shuffling a Tensor using a torch.randperm() method

import torch

# Define a sample tensor
data = torch.tensor([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9],
                     [10, 11, 12]])

# Generate random permutation of row indices
permuted_indices = torch.randperm(data.size(0))

# Shuffle rows of the tensor
shuffled_data = data[permuted_indices]

print(shuffled_data)

Output

Shuffling a Tensor using a torch.randperm() method

Example 3: Splitting a Tensor into Training and Testing sets

Suppose you have a tensor of data, and you want to split it into a training set (80%) and a testing set (20%) randomly.

import torch

# Define a sample tensor
data = torch.tensor([[1, 2, 3],
                     [4, 5, 6],
                     [7, 8, 9],
                     [10, 11, 12],
                     [13, 14, 15]])

# Generate random permutation of indices
permuted_indices = torch.randperm(data.size(0))

# Calculate the size of the training set (80% of total data)
train_size = int(0.8 * data.size(0))

# Split the tensor into training and testing sets
train_data = data[permuted_indices[:train_size]]
test_data = data[permuted_indices[train_size:]]

print("Training Data:")
print(train_data)

print("\nTesting Data:")
print(test_data)

Output

Training Data:
tensor([[ 7, 8, 9],
        [13, 14, 15],
        [10, 11, 12],
        [ 4, 5, 6]])

Testing Data:
tensor([[1, 2, 3]])

That’s it!

Related posts

torch.randint()

torch.randn()

torch.stack()

torch.cat()

torch.matmul()

torch.split()

torch.unsqueeze()

Leave a Comment