.randperm()
Published Mar 16, 2025
Contribute to Docs
In PyTorch, the .randperm()
function generates a random permutation of integers from 0
to n-1
. This function is useful when there is a need to shuffle indices, such as for batch sampling or dataset shuffling.
Syntax
torch.randperm(n, *, generator=None, out=None, dtype=torch.int64, ...)
n
(int): The upper bound (exclusive) for the range of integers.generator
(Optional): Generates a pseudorandom number for sampling.out
(Optional): The output tensor to store the result.dtype
(Optional): The desired data type of the returned tensor.
Note: The ellipsis (…) in the syntax indicates that there can be additional optional parameters beyond those listed here.
Example
The following example demonstrates the usage of the .randperm()
function:
import torch# Generate a random permutation of integers from 0 to 9perm = torch.randperm(10)# Print the resultant tensorprint(perm)
The above code produces the following output:
tensor([0, 1, 5, 6, 4, 2, 8, 7, 3, 9])
Note: Since the
.randperm()
function generates a random permutation of integers, the output may vary each time the code is run.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PyTorch on Codecademy
- Career path
Data Scientist: Machine Learning Specialist
Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.Includes 27 CoursesWith Professional CertificationBeginner Friendly95 hours - Free course
Intro to PyTorch and Neural Networks
Learn how to use PyTorch to build, train, and test artificial neural networks in this course.Intermediate3 hours