sampler.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from torch.utils.data.sampler import Sampler
  2. from collections import defaultdict
  3. import copy
  4. import random
  5. import numpy as np
  6. class RandomIdentitySampler(Sampler):
  7. """
  8. Randomly sample N identities, then for each identity,
  9. randomly sample K instances, therefore batch size is N*K.
  10. Args:
  11. - data_source (list): list of (img_path, pid, camid).
  12. - num_instances (int): number of instances per identity in a batch.
  13. - batch_size (int): number of examples in a batch.
  14. """
  15. def __init__(self, data_source, batch_size, num_instances):
  16. self.data_source = data_source
  17. self.batch_size = batch_size
  18. self.num_instances = num_instances
  19. self.num_pids_per_batch = self.batch_size // self.num_instances
  20. self.index_dic = defaultdict(list) #dict with list value
  21. #{783: [0, 5, 116, 876, 1554, 2041],...,}
  22. for index, (pid, _, _, _) in enumerate(self.data_source):
  23. self.index_dic[pid].append(index)
  24. self.pids = list(self.index_dic.keys())
  25. # estimate number of examples in an epoch
  26. self.length = 0
  27. for pid in self.pids:
  28. idxs = self.index_dic[pid]
  29. num = len(idxs)
  30. if num < self.num_instances:
  31. num = self.num_instances
  32. self.length += num - num % self.num_instances
  33. def __iter__(self):
  34. batch_idxs_dict = defaultdict(list)
  35. for pid in self.pids:
  36. idxs = copy.deepcopy(self.index_dic[pid])
  37. if len(idxs) < self.num_instances:
  38. idxs = np.random.choice(idxs, size=self.num_instances, replace=True)
  39. random.shuffle(idxs)
  40. batch_idxs = []
  41. for idx in idxs:
  42. batch_idxs.append(idx)
  43. if len(batch_idxs) == self.num_instances:
  44. batch_idxs_dict[pid].append(batch_idxs)
  45. batch_idxs = []
  46. avai_pids = copy.deepcopy(self.pids)
  47. final_idxs = []
  48. while len(avai_pids) >= self.num_pids_per_batch:
  49. selected_pids = random.sample(avai_pids, self.num_pids_per_batch)
  50. for pid in selected_pids:
  51. batch_idxs = batch_idxs_dict[pid].pop(0)
  52. final_idxs.extend(batch_idxs)
  53. if len(batch_idxs_dict[pid]) == 0:
  54. avai_pids.remove(pid)
  55. return iter(final_idxs)
  56. def __len__(self):
  57. return self.length