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
- n (int): The upper bound (exclusive) on the range of random integers to generate.
- out (Tensor, optional): The output tensor.
- dtype (torch.dtype, optional): The desired data type of the output tensor. Default: torch.int64.
- layout (torch.layout, optional): The desired layout of the output tensor. Default: torch.strided.
- device (torch.device, optional): The desired device of the output 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: 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
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

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.