Batch data that have similar aspect ratio together. In this implementation, images whose aspect ratio < (or >) 1 will be batched together. This improves training speed because the images then need less padding to form a batch. It assumes the underlying dataset produces dict
| 150 | |
| 151 | |
| 152 | class AspectRatioGroupedDataset(data.IterableDataset): |
| 153 | """ |
| 154 | Batch data that have similar aspect ratio together. |
| 155 | In this implementation, images whose aspect ratio < (or >) 1 will |
| 156 | be batched together. |
| 157 | This improves training speed because the images then need less padding |
| 158 | to form a batch. |
| 159 | |
| 160 | It assumes the underlying dataset produces dicts with "width" and "height" keys. |
| 161 | It will then produce a list of original dicts with length = batch_size, |
| 162 | all with similar aspect ratios. |
| 163 | """ |
| 164 | |
| 165 | def __init__(self, dataset, batch_size): |
| 166 | """ |
| 167 | Args: |
| 168 | dataset: an iterable. Each element must be a dict with keys |
| 169 | "width" and "height", which will be used to batch data. |
| 170 | batch_size (int): |
| 171 | """ |
| 172 | self.dataset = dataset |
| 173 | self.batch_size = batch_size |
| 174 | self._buckets = [[] for _ in range(2)] |
| 175 | # Hard-coded two aspect ratio groups: w > h and w < h. |
| 176 | # Can add support for more aspect ratio groups, but doesn't seem useful |
| 177 | |
| 178 | def __iter__(self): |
| 179 | for d in self.dataset: |
| 180 | w, h = d["width"], d["height"] |
| 181 | bucket_id = 0 if w > h else 1 |
| 182 | bucket = self._buckets[bucket_id] |
| 183 | bucket.append(d) |
| 184 | if len(bucket) == self.batch_size: |
| 185 | yield bucket[:] |
| 186 | del bucket[:] |
no outgoing calls
no test coverage detected