如何重新排列火炬数据加载器的样本顺序?

How to rearrange the sample order of a torch dataloader?

我有一个“torch.utils.data.DataLoader”。我想重新排列样本的顺序。可能吗?

是的,您可以使用 torch.utils.data.Subset 并指定索引。

import numpy as np
import torch
from torch.utils.data import DataLoader, Subset, TensorDataset


data = np.arange(5) ** 2
dataset = TensorDataset(torch.tensor(data))

# Subset with entire Dataset in rearranged order
dataset_ordered = Subset(dataset, indices=[2, 1, 3, 4, 0])

for x in DataLoader(dataset_ordered):
    print(x)

# [tensor([4])]
# [tensor([1])]
# [tensor([9])]
# [tensor([16])]
# [tensor([0])]