# How to sample dataset according to the index

**URL:** </static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-sample-dataset-according-to-the-index%2F12940%3E%5C
**Category:** 🤗Datasets\
**Created:** [December 18, 2021, 8:19am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-sample-dataset-according-to-the-index%2F12940 "2021-12-18T08:19:11Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ezio98](https://avatars.discourse-cdn.com/v4/letter/e/b9e5f3/32.png) [@ezio98](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fezio98)%5C
**Post date:** [December 18, 2021, 8:19am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-sample-dataset-according-to-the-index%2F12940%2F1 "2021-12-18T08:19:11Z")

</div>

Hi, I am training BERT and use the dataset wikipedia. Only a subset of the inputs are needed and I have got the indicecs of them. However, problems occur when I want to use the sub-dataset. This code is extremely slow :  
`subdataset=wikidataset[selected_indices]`.  
, where the selected\_indices is a one-dimension vector. I thought this may due to the dataset is too large. Is there any way to sample the dataset efficiently?

By the way, I also considered to use `SubsetRandomSampler`, but it seems this sampler does not work in the distributed training.

---

<div class="post-metadata">

**Author:** ![lhoestq](https://sea2.discourse-cdn.com/hellohellohello/user_avatar/discuss.huggingface.co/lhoestq/32/64813_2.png) [@lhoestq](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Flhoestq)%5C
**Post date:** [January 10, 2022, 11:46am UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-sample-dataset-according-to-the-index%2F12940%2F2 "2022-01-10T11:46:41Z")

</div>

Hi ! when you use `wikidataset[some_indices]`, it tries to load all the indices you requested in memory, as a python dictionary. This can take some time and fill up your memory.

If you just want to select a subset of your dataset and later train on model on it, you can do

```python
subdataset = wikidataset.select(some_indices)

```

This returns a new `Dataset` object that only contains the indices you requested. Moreover this doesn’t bring any data on memory and is pretty fast 🙂

---

<div class="post-metadata">

**Author:** ![ezio98](https://avatars.discourse-cdn.com/v4/letter/e/b9e5f3/32.png) [@ezio98](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Fu%2Fezio98)%5C
**Post date:** [January 10, 2022, 12:03pm UTC](/static-proxy?url=https%3A%2F%2Fdiscuss.huggingface.co%2Ft%2Fhow-to-sample-dataset-according-to-the-index%2F12940%2F3 "2022-01-10T12:03:25Z")

</div>

Thanks! This is exactly what I want.
