| 8 | |
| 9 | |
| 10 | class MYNET(nn.Module): |
| 11 | |
| 12 | def __init__(self, args, mode=None): |
| 13 | super().__init__() |
| 14 | |
| 15 | self.mode = mode |
| 16 | self.args = args |
| 17 | if self.args.dataset in ['cifar100','manyshotcifar']: |
| 18 | self.encoder = resnet20() |
| 19 | self.num_features = 64 |
| 20 | if self.args.dataset in ['mini_imagenet','manyshotmini','imagenet100','imagenet1000']: |
| 21 | self.encoder = resnet18(False, args) # pretrained=False |
| 22 | self.num_features = 512 |
| 23 | if self.args.dataset == 'cub200': |
| 24 | self.encoder = resnet18(True, args) # pretrained=True follow TOPIC, models for cub is imagenet pre-trained. https://github.com/xyutao/fscil/issues/11#issuecomment-687548790 |
| 25 | self.num_features = 512 |
| 26 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) |
| 27 | |
| 28 | |
| 29 | self.pre_allocate = self.args.num_classes |
| 30 | self.fc = nn.Linear(self.num_features, self.pre_allocate, bias=False) |
| 31 | |
| 32 | nn.init.orthogonal_(self.fc.weight) |
| 33 | self.dummy_orthogonal_classifier=nn.Linear(self.num_features, self.pre_allocate-self.args.base_class, bias=False) |
| 34 | self.dummy_orthogonal_classifier.weight.requires_grad = False |
| 35 | |
| 36 | self.dummy_orthogonal_classifier.weight.data=self.fc.weight.data[self.args.base_class:,:] |
| 37 | print(self.dummy_orthogonal_classifier.weight.data.size()) |
| 38 | |
| 39 | print('self.dummy_orthogonal_classifier.weight initialized over.') |
| 40 | |
| 41 | def forward_metric(self, x): |
| 42 | x = self.encode(x) |
| 43 | if 'cos' in self.mode: |
| 44 | |
| 45 | x1 = F.linear(F.normalize(x, p=2, dim=-1), F.normalize(self.fc.weight, p=2, dim=-1)) |
| 46 | x2 = F.linear(F.normalize(x, p=2, dim=-1), F.normalize(self.dummy_orthogonal_classifier.weight, p=2, dim=-1)) |
| 47 | |
| 48 | x = torch.cat([x1[:,:self.args.base_class],x2],dim=1) |
| 49 | |
| 50 | x = self.args.temperature * x |
| 51 | |
| 52 | elif 'dot' in self.mode: |
| 53 | x = self.fc(x) |
| 54 | x = self.args.temperature * x |
| 55 | return x |
| 56 | |
| 57 | def forpass_fc(self,x): |
| 58 | x = self.encode(x) |
| 59 | if 'cos' in self.mode: |
| 60 | |
| 61 | x = F.linear(F.normalize(x, p=2, dim=-1), F.normalize(self.fc.weight, p=2, dim=-1)) |
| 62 | x = self.args.temperature * x |
| 63 | |
| 64 | elif 'dot' in self.mode: |
| 65 | x = self.fc(x) |
| 66 | x = self.args.temperature * x |
| 67 | return x |