MCPcopy Create free account
hub / github.com/LAMDA-CL/CVPR22-Fact / MYNET

Class MYNET

models/base/Network.py:10–110  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8
9
10class MYNET(nn.Module):
11
12 def __init__(self, args, mode=None):
13 super().__init__()
14
15 self.mode = mode
16 self.args = args
17 # self.num_features = 512
18 if self.args.dataset in ['cifar100','manyshotcifar']:
19 self.encoder = resnet20()
20 self.num_features = 64
21 if self.args.dataset in ['mini_imagenet','manyshotmini','imagenet100','imagenet1000', 'mini_imagenet_withpath']:
22 self.encoder = resnet18(False, args) # pretrained=False
23 self.num_features = 512
24 if self.args.dataset in ['cub200','manyshotcub']:
25 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
26 self.num_features = 512
27 self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
28
29 self.fc = nn.Linear(self.num_features, self.args.num_classes, bias=False)
30
31 def forward_metric(self, x):
32 x = self.encode(x)
33 if 'cos' in self.mode:
34 x = F.linear(F.normalize(x, p=2, dim=-1), F.normalize(self.fc.weight, p=2, dim=-1))
35 x = self.args.temperature * x
36
37 elif 'dot' in self.mode:
38 x = self.fc(x)
39 x = self.args.temperature * x
40 return x
41
42 def encode(self, x):
43 x = self.encoder(x)
44 x = F.adaptive_avg_pool2d(x, 1)
45 x = x.squeeze(-1).squeeze(-1)
46 return x
47
48 def forward(self, input):
49 if self.mode != 'encoder':
50 input = self.forward_metric(input)
51 return input
52 elif self.mode == 'encoder':
53 input = self.encode(input)
54 return input
55 else:
56 raise ValueError('Unknown mode')
57
58 def update_fc(self,dataloader,class_list,session):
59 for batch in dataloader:
60 data, label = [_.cuda() for _ in batch]
61 data=self.encode(data).detach()
62
63 if self.args.not_data_init:
64 new_fc = nn.Parameter(
65 torch.rand(len(class_list), self.num_features, device="cuda"),
66 requires_grad=True)
67 nn.init.kaiming_uniform_(new_fc, a=math.sqrt(5))

Callers 1

__init__Method · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected