MCPcopy Create free account
hub / github.com/lingeringlight/START / RandomDomainSampler

Class RandomDomainSampler

data/samplers.py:62–114  ·  view source on GitHub ↗

Randomly samples N domains each with K images to form a minibatch of size N*K. Args: data_source (list): list of Datums. batch_size (int): batch size. n_domain (int): number of domains to sample in a minibatch.

Source from the content-addressed store, hash-verified

60
61
62class RandomDomainSampler(Sampler):
63 """Randomly samples N domains each with K images
64 to form a minibatch of size N*K.
65 Args:
66 data_source (list): list of Datums.
67 batch_size (int): batch size.
68 n_domain (int): number of domains to sample in a minibatch.
69 """
70
71 def __init__(self, data_source, batch_size, n_domain):
72 self.data_source = data_source
73
74 # Keep track of image indices for each domain
75 self.domain_dict = defaultdict(list)
76 for i, item in enumerate(data_source):
77 self.domain_dict[item.domain].append(i)
78 self.domains = list(self.domain_dict.keys())
79
80 # Make sure each domain has equal number of images
81 if n_domain is None or n_domain <= 0:
82 n_domain = len(self.domains)
83 assert batch_size % n_domain == 0
84 self.n_img_per_domain = batch_size // n_domain
85
86 self.batch_size = batch_size
87 # n_domain denotes number of domains sampled in a minibatch
88 self.n_domain = n_domain
89 self.length = len(list(self.__iter__()))
90
91 def __iter__(self):
92 domain_dict = copy.deepcopy(self.domain_dict)
93 final_idxs = []
94 stop_sampling = False
95
96 while not stop_sampling:
97 selected_domains = random.sample(self.domains, self.n_domain)
98
99 for domain in selected_domains:
100 idxs = domain_dict[domain]
101 selected_idxs = random.sample(idxs, self.n_img_per_domain)
102 final_idxs.extend(selected_idxs)
103
104 for idx in selected_idxs:
105 domain_dict[domain].remove(idx)
106
107 remaining = len(domain_dict[domain])
108 if remaining < self.n_img_per_domain:
109 stop_sampling = True
110
111 return iter(final_idxs)
112
113 def __len__(self):
114 return self.length
115
116
117class SeqDomainSampler(Sampler):

Callers 1

build_samplerFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…