MCPcopy Create free account
hub / github.com/apple/ml-pointersect / BucketSampler

Class BucketSampler

cdslib/core/data/dataloader/bucket_sampler.py:16–215  ·  view source on GitHub ↗

The class assembles batches by grouping data of similar length. It returns indices of the data in the dataset within a batch. Here is an example to use the bucket sampler: .. code-block:: python from bucket_sampler import Bucket_Sampler import numpy as np

Source from the content-addressed store, hash-verified

14
15
16class BucketSampler:
17 """
18 The class assembles batches by grouping data of similar length.
19 It returns indices of the data in the dataset within a batch.
20
21 Here is an example to use the bucket sampler:
22
23 .. code-block:: python
24
25 from bucket_sampler import Bucket_Sampler
26 import numpy as np
27
28 dataset_size = 50
29 dataset_lengths = np.random.randint(1, 100, dataset_size)
30 print(dataset_lengths)
31
32 batch_size = 4
33 drop_last = True
34 shuffle = True
35 bucket_boundaries = [10,20,30,40,50,60,70,80,90] # I hand-assigned here, but it can be created by np.histogram_bin_edges
36 batch_sampler = Bucket_Sampler(dataset_lengths, bucket_boundaries, batch_size, drop_last, shuffle)
37
38 print('num batches = %d' % (len(batch_sampler)))
39 for batch_idx, data_idxs in enumerate(batch_sampler):
40 print('%d: '% batch_idx, end='' )
41 print(data_idxs)
42
43 # no need to assign batch_size, shuffle, drop_last, since batch_sampler determines them
44 dataloader = torch.utils.data.DataLoader(
45 self.dataset,
46 batch_sampler=bucket_sampler,
47 num_workers=self.num_workers,
48 collate_fn=self.dataset.collate_fn
49 )
50
51 """
52
53 def __init__(
54 self,
55 batch_size,
56 drop_last,
57 shuffle,
58 bucket_boundaries=None,
59 max_batch_combined_size=-1,
60 ):
61 """
62 Args:
63 batch_size:
64 batch size
65 drop_last:
66 whether to drop the last few data that cannot form a batch (recommanded True).
67 shuffle:
68 whether to shuffle the data slightly (according to their length of course).
69 bucket_boundaries:
70 int (number of bins) or a list (containing the edges in ascending order,
71 excluding two outmost boundaries).
72
73 edge 0 1 2

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected