Indices of the batch where I use SubsetRandomSampler

I want to print the indices of the batch where I use SubsetRandomSampler.

train_dataset = datasets.MNIST(root=’./train’, train=True,download=True,transform=transform)
train_loader = DataLoader(train_dataset, batch_size=32,sampler=SubsetRandomSampler(range(len(train_dataset))))

for train_x, train_label in train_loader:
# I need to print the indices of each batch which should be a random number between 0-59999

You could create a custom Dataset and return the index with the data and target tensors in the __getitem__ method. To do so, take a look at this tutorial and or override the MNIST dataset with your custom __getitem__ implementation.

I think the best approach depends on your actual use case.
If you want to get the index used to load the current sample, I would write a custom Dataset and just return it. This would avoid any issues with using another sampler or any kind of shuffling etc. since the index will be directly returned. On the other hand, if you are more interested in the sampler indices for a particular reason, you might want to check its implementation or write a custom one etc. (in that case I’m not sure I understand the question correctly).

Thank you @ptrblck. Yes, I customized the dataset and I could get the indices throught getitem.

I made things complicated at the beginning. Thank you again for your help.