# How to use BatchSampler with \_\_getitem\_\_ dataset

**URL:** <https://discuss.pytorch.org/t/how-to-use-batchsampler-with-getitem-dataset/78788>\
**Category:** Uncategorized\
**Created:** [April 28, 2020, 7:39am UTC](https://discuss.pytorch.org/t/how-to-use-batchsampler-with-getitem-dataset/78788 "2020-04-28T07:39:28Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [April 28, 2020, 8:25am UTC](https://discuss.pytorch.org/t/how-to-use-batchsampler-with-getitem-dataset/78788/4 "2020-04-28T08:25:40Z")

</div>

Maybe this code snippet might be helpful:

```python
class MyDataset(Dataset):
    def __init__ (self):
        self.data = torch.arange(100).view(100, 1).float()
        
    def __getitem__ (self, index):
        x = self.data[index]
        return x
    
    def __len__ (self):
        return len(self.data)

dataset = MyDataset()        
sampler = torch.utils.data.sampler.BatchSampler(
    torch.utils.data.sampler.RandomSampler(dataset),
    batch_size=10,
    drop_last=False)

loader = DataLoader(
    dataset,
    sampler=sampler)

for data in loader:
    print(data)

```

The `index` inside ` __getitem__ ` will contain 10 random indices, which are used to create the batch in:

```python
x = self.data[index]

```

You could replace this with your expensive data loading operation.

Let me know, if that helps.

---

_[View the full topic](https://discuss.pytorch.org/t/how-to-use-batchsampler-with-getitem-dataset/78788)._
