|
| 1 | +import torch.nn as nn |
| 2 | +import torchvision |
| 3 | + |
| 4 | + |
| 5 | +class ResNetFeature(nn.Module): |
| 6 | + |
| 7 | + def __init__(self, depth=34, pretrained=True): |
| 8 | + super().__init__() |
| 9 | + assert depth in [18, 34, 50, 101, 152] |
| 10 | + |
| 11 | + if depth == 18: |
| 12 | + base_model = torchvision.models.resnet18(pretrained=pretrained) |
| 13 | + self.len_feature = 512 |
| 14 | + self.features = nn.Sequential(*list(base_model.children())[:-2]) |
| 15 | + elif depth == 34: |
| 16 | + base_model = torchvision.models.resnet34(pretrained=pretrained) |
| 17 | + self.len_feature = 512 |
| 18 | + self.features = nn.Sequential(*list(base_model.children())[:-2]) |
| 19 | + elif depth == 50: |
| 20 | + base_model = torchvision.models.resnet50(pretrained=pretrained) |
| 21 | + self.len_feature = 2048 |
| 22 | + self.features = nn.Sequential(*list(base_model.children())[:-2]) |
| 23 | + elif depth == 101: |
| 24 | + base_model = torchvision.models.resnet101(pretrained=pretrained) |
| 25 | + self.len_feature = 2048 |
| 26 | + self.features = nn.Sequential(*list(base_model.children())[:-2]) |
| 27 | + elif depth == 152: |
| 28 | + base_model = torchvision.models.resnet152(pretrained=pretrained) |
| 29 | + self.len_feature = 2048 |
| 30 | + self.features = nn.Sequential(*list(base_model.children())[:-2]) |
| 31 | + else: |
| 32 | + raise NotImplementedError(f'ResNet-{depth} is not implemented!') |
| 33 | + |
| 34 | + def forward(self, x): |
| 35 | + x = self.features(x) |
| 36 | + |
| 37 | + # Attention! No reshape! |
| 38 | + return x |
| 39 | + |
| 40 | + |
| 41 | +class ResNetClassifier(nn.Module): |
| 42 | + |
| 43 | + def __init__(self, n_class, len_feature): |
| 44 | + super().__init__() |
| 45 | + self.len_feature = len_feature |
| 46 | + self.classifier = nn.Linear(self.len_feature, n_class) |
| 47 | + |
| 48 | + def forward(self, x): |
| 49 | + # -> batch_size x C x N |
| 50 | + x = x.view(x.size(0), x.size(1), -1) |
| 51 | + |
| 52 | + # -> batch_size x C |
| 53 | + x = x.mean(dim=-1) |
| 54 | + |
| 55 | + x = self.classifier(x) |
| 56 | + return x |
0 commit comments