File size: 1,854 Bytes
61ce884
5a128ba
 
cdc317a
 
5a128ba
cdc317a
 
 
 
5a128ba
cdc317a
 
5a128ba
 
 
 
 
cdc317a
61ce884
 
d1c85fc
61ce884
 
 
d1c85fc
 
 
 
033fb72
7fcff1a
61ce884
 
 
d1c85fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9a0c51
d1c85fc
 
61ce884
 
 
 
 
cdc317a
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import torch.nn as nn


class BackboneWithFC(nn.Module):
    """Frozen ResNet18 backbone + trainable FC classifier head."""

    def __init__(self, backbone: nn.Module, num_classes: int, dropout: float = 0.4, fc_dim: int = 256):
        super().__init__()
        self.backbone = backbone
        self.classifier = nn.Sequential(
            nn.Dropout(dropout),
            nn.Linear(512, fc_dim),
            nn.ReLU(inplace=True),
            nn.Dropout(dropout),
            nn.Linear(fc_dim, num_classes),
        )

    def forward(self, x):
        return self.classifier(self.backbone(x))


class SimpleCNN(nn.Module):
    def __init__(
        self,
        num_classes: int,
        num_conv_blocks: int = 3,
        base_filters: int = 32,
        kernel_size: int = 3,
        use_batchnorm: bool = True,
        dropout: float = 0.4,
        fc_dim: int = 256,
    ):
        super().__init__()

        padding = kernel_size // 2
        layers = []
        in_channels = 3

        for i in range(num_conv_blocks):
            out_channels = min(base_filters * (2 ** i), 512)
            layers.append(nn.Conv2d(in_channels, out_channels, kernel_size, padding=padding))
            if use_batchnorm:
                layers.append(nn.BatchNorm2d(out_channels))
            layers.append(nn.ReLU(inplace=True))
            layers.append(nn.MaxPool2d(2, 2))
            in_channels = out_channels

        self.features = nn.Sequential(*layers)
        self.pool = nn.AdaptiveAvgPool2d(1)

        self.classifier = nn.Sequential(
            nn.Dropout(dropout),
            nn.Linear(in_channels, fc_dim),
            nn.ReLU(inplace=True),
            nn.Dropout(dropout),
            nn.Linear(fc_dim, num_classes),
        )

    def forward(self, x):
        x = self.pool(self.features(x))
        return self.classifier(x.flatten(1))