Operational memory for a single class.
| 3 | |
| 4 | |
| 5 | class ClassMemory(object): |
| 6 | """ Operational memory for a single class.""" |
| 7 | |
| 8 | def __init__(self, label, init_prototype, metric_shape, qi_len=1, gpu=True): |
| 9 | if init_prototype is not None: |
| 10 | assert len(init_prototype.shape) == 2, "<batch dim, feat size> required" |
| 11 | assert qi_len >= 0 |
| 12 | assert isinstance(label, int) |
| 13 | self.label = label |
| 14 | self.shape = metric_shape |
| 15 | |
| 16 | self.prototype = self.init_prototype_val(self.shape) if init_prototype is None else init_prototype.cuda() |
| 17 | self.p_tmp, self.p_tmp_cnt = self.init_zeros(self.shape), 0 # For update over multiple iterations |
| 18 | self.q = torch.Tensor() # Up-to-date Q used for the loss |
| 19 | self.q_orig = torch.Tensor() # Q with last updated |
| 20 | self.qi_len = qi_len |
| 21 | self.qi = torch.Tensor() # Raw input imgs |
| 22 | self.qi_score = torch.Tensor(self.qi_len) # score for each input img |
| 23 | self.update_age = torch.Tensor() |
| 24 | self.seen_cnt = 0 # How many samples seen of this class |
| 25 | |
| 26 | if gpu: |
| 27 | self.prototype = self.prototype.cuda() |
| 28 | self.p_tmp = self.p_tmp.cuda() |
| 29 | self.q = self.q.cuda() |
| 30 | self.qi = self.qi.cuda() |
| 31 | self.qi_score = self.qi_score.cuda() |
| 32 | self.update_age = self.update_age.cuda() |
| 33 | |
| 34 | @staticmethod |
| 35 | def init_prototype_val(feat_len): |
| 36 | p = torch.nn.functional.normalize(torch.empty((1, feat_len[-1])).uniform_(0, 1), p=2, dim=1).detach() |
| 37 | return p |
| 38 | |
| 39 | def init_zeros(self, feat_len=None): |
| 40 | if feat_len is None: |
| 41 | feat_len = self.shape |
| 42 | return torch.zeros((1, feat_len[-1])) |
| 43 | |
| 44 | def __str__(self): |
| 45 | res = [] |
| 46 | res.append("{: >5}".format("Class {}:".format(self.label))) |
| 47 | res.append("{: >5} ".format("")) |
| 48 | res.append("p ({}):\n {: >40} ".format(list(self.prototype.shape), str(self.prototype))) |
| 49 | res.append("Mem ({}):\n {: >40} ".format(list(self.q.shape), str(self.q))) |
| 50 | return "\n".join(res) |
| 51 | |
| 52 | |
| 53 | class MemoryScheme(object): |