Randomly samples N classes each with K instances to form a minibatch of size N*K. Modified from https://github.com/KaiyangZhou/deep-person-reid. Args: data_source (list): list of Datums. batch_size (int): batch size. n_ins (int): number of instances per clas
| 167 | |
| 168 | |
| 169 | class RandomClassSampler(Sampler): |
| 170 | """Randomly samples N classes each with K instances to |
| 171 | form a minibatch of size N*K. |
| 172 | Modified from https://github.com/KaiyangZhou/deep-person-reid. |
| 173 | Args: |
| 174 | data_source (list): list of Datums. |
| 175 | batch_size (int): batch size. |
| 176 | n_ins (int): number of instances per class to sample in a minibatch. |
| 177 | """ |
| 178 | |
| 179 | def __init__(self, data_source, batch_size, n_ins): |
| 180 | if batch_size < n_ins: |
| 181 | raise ValueError( |
| 182 | "batch_size={} must be no less " |
| 183 | "than n_ins={}".format(batch_size, n_ins) |
| 184 | ) |
| 185 | |
| 186 | self.data_source = data_source |
| 187 | self.batch_size = batch_size |
| 188 | self.n_ins = n_ins |
| 189 | self.ncls_per_batch = self.batch_size // self.n_ins |
| 190 | self.index_dic = defaultdict(list) |
| 191 | for index, item in enumerate(data_source): |
| 192 | self.index_dic[item.label].append(index) |
| 193 | self.labels = list(self.index_dic.keys()) |
| 194 | assert len(self.labels) >= self.ncls_per_batch |
| 195 | |
| 196 | # estimate number of images in an epoch |
| 197 | self.length = len(list(self.__iter__())) |
| 198 | |
| 199 | def __iter__(self): |
| 200 | batch_idxs_dict = defaultdict(list) |
| 201 | |
| 202 | for label in self.labels: |
| 203 | idxs = copy.deepcopy(self.index_dic[label]) |
| 204 | if len(idxs) < self.n_ins: |
| 205 | idxs = np.random.choice(idxs, size=self.n_ins, replace=True) |
| 206 | random.shuffle(idxs) |
| 207 | batch_idxs = [] |
| 208 | for idx in idxs: |
| 209 | batch_idxs.append(idx) |
| 210 | if len(batch_idxs) == self.n_ins: |
| 211 | batch_idxs_dict[label].append(batch_idxs) |
| 212 | batch_idxs = [] |
| 213 | |
| 214 | avai_labels = copy.deepcopy(self.labels) |
| 215 | final_idxs = [] |
| 216 | |
| 217 | while len(avai_labels) >= self.ncls_per_batch: |
| 218 | selected_labels = random.sample(avai_labels, self.ncls_per_batch) |
| 219 | for label in selected_labels: |
| 220 | batch_idxs = batch_idxs_dict[label].pop(0) |
| 221 | final_idxs.extend(batch_idxs) |
| 222 | if len(batch_idxs_dict[label]) == 0: |
| 223 | avai_labels.remove(label) |
| 224 | |
| 225 | return iter(final_idxs) |
| 226 |
no outgoing calls
no test coverage detected
searching dependent graphs…