Sampler that sample from each cell category equally The hierarchy_match defines the cell category for each class. if None then each class will be category of it's own.
(crops, hierarchy_match=None)
| 55 | |
| 56 | |
| 57 | def define_sampler(crops, hierarchy_match=None): |
| 58 | """ |
| 59 | Sampler that sample from each cell category equally |
| 60 | The hierarchy_match defines the cell category for each class. |
| 61 | if None then each class will be category of it's own. |
| 62 | """ |
| 63 | labels = np.array([c._label for c in crops]) |
| 64 | if hierarchy_match is not None: |
| 65 | labels = np.array([hierarchy_match[str(l)] for l in labels]) |
| 66 | |
| 67 | unique_labels = np.unique(labels) |
| 68 | class_sample_count = {t: len(np.where(labels == t)[0]) for t in unique_labels} |
| 69 | weight = {k: sum(class_sample_count.values()) / v for k, v in class_sample_count.items()} |
| 70 | samples_weight = np.array([weight[t] for t in labels]) |
| 71 | samples_weight = torch.from_numpy(samples_weight) |
| 72 | return WeightedRandomSampler(samples_weight.double(), len(samples_weight)) |
| 73 | |
| 74 | |
| 75 | if __name__ == "__main__": |