Pytorch Torch Randperm
# PyTorch torch.randperm Function
`torch.randperm` function is used to generate 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), i.e., the length of the generated sequence.
- **out** (Tensor, optional): Output tensor.
- **dtype** (`torch.dtype`, optional): The desired data type of the returned tensor. Default: `torch.int64`.
- **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.
- **requires_grad** (bool, optional): Whether to record operations on the returned tensor for automatic differentiation.
### Return Value
Returns a 1D tensor containing a random permutation of integers from 0 to n-1.
### Example
```python
import torch
# Generate a random permutation from 0 to 9
result = torch.randperm(10)
print(result)
```
Output result:
```
tensor([4, 1, 5, 0, 8, 2, 9, 3, 6, 7])
```
### Application Scenarios
`torch.randperm` is commonly used in the following scenarios:
1. **Data shuffling**: Randomly shuffling the order of data during training.
2. **Random sampling**: Generating random indices for data sampling.
3. **Cross-validation**: Randomly splitting dataset.
### Example: Data Shuffling
```python
import torch
# Create sample data
data = torch.tensor([10, 20, 30, 40, 50])
# Generate random indices
indices = torch.randperm(len(data))
# Shuffle data
shuffled_data = data
print("Original data:", data)
print("Random indices:", indices)
print("Shuffled data:", shuffled_data)
```
Output result:
```
Original data: tensor([10, 20, 30, 40, 50])
Random indices: tensor([2, 0, 4, 1, 3])
Shuffled data: tensor([30, 10, 50, 20, 40])
```
### Notes
- The generated permutation is random, and results will vary each time you run it.
- If you need reproducible results, you can set a random seed:
```python
import torch
torch.manual_seed(42)
result = torch.randperm(5)
print(result) # Output: tensor([0, 4, 2, 3, 1])
```
YouTip