# Change sampler every epoch

**URL:** <https://discuss.pytorch.org/t/change-sampler-every-epoch/40792>\
**Category:** Uncategorized\
**Created:** [March 25, 2019, 4:24am UTC](https://discuss.pytorch.org/t/change-sampler-every-epoch/40792 "2019-03-25T04:24:55Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![satrialoka](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/satrialoka/32/7417_2.png) [@satrialoka](https://discuss.pytorch.org/u/satrialoka)\
**Post date:** [March 25, 2019, 4:24am UTC](https://discuss.pytorch.org/t/change-sampler-every-epoch/40792/1 "2019-03-25T04:24:55Z")

</div>

I would like to filter out my dataset every epoch by changing the sampler for the data loader, but when I change the sampler it gives me :  
`ValueError: sampler attribute should not be set after DataLoader is initialized`

here’s my sample code :

```auto
def train_test():  
        epoch = epoch_n
        for e in range(epoch):
                train_loss, train_acuracy, losses = train(train_loader,criterion,optimizer,e+1,True)
                test_loss, test_acuracy = test(test_loader,criterion,optimizer,e+1,True)
                print('Epoch %d, Training Loss/Acc: %f//%f, Testing Loss/Acc: %f//%f' % (e+1,train_loss,train_acuracy,test_loss,test_acuracy))
                indexsorted = rankloss(losses)
                indexcuted = cutdataset(indexsorted)
                train_loader.sampler = sampler.SubsetRandomSampler(indexcuted)

```

is there a way to do this ?

---

<div class="post-metadata">

**Author:** ![Oli](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/oli/32/9773_2.png) [@Oli](https://discuss.pytorch.org/u/Oli)\
**Post date:** [March 25, 2019, 4:14pm UTC](https://discuss.pytorch.org/t/change-sampler-every-epoch/40792/2 "2019-03-25T16:14:08Z")

</div>

You could create a new dataloader with the new sampler every epoch. If you don’t want to do this, do you mind sharing what the differences in the samplers are? Perhaps you can create one sampler that can take the behavior of all the samplers you need

---

<div class="post-metadata">

**Author:** ![satrialoka](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/satrialoka/32/7417_2.png) [@satrialoka](https://discuss.pytorch.org/u/satrialoka)\
**Post date:** [March 27, 2019, 7:28am UTC](https://discuss.pytorch.org/t/change-sampler-every-epoch/40792/3 "2019-03-27T07:28:43Z")

</div>

solved by creating custom sampler by writing a method to update the sampler’s properties. Thank you

---

<div class="post-metadata">

**Author:** ![mzimmer](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/mzimmer/32/31510_2.png) [@mzimmer](https://discuss.pytorch.org/u/mzimmer)\
**Post date:** [July 23, 2022, 6:46am UTC](https://discuss.pytorch.org/t/change-sampler-every-epoch/40792/4 "2022-07-23T06:46:32Z")

</div>

Mind to share your code?
