|
15 | 15 | import unittest
|
16 | 16 | import numpy as np
|
17 | 17 |
|
18 |
| -def convLayer(in_planes, out_planes, stride=1, padding = 1, bias = True): |
| 18 | +def convLayer(in_planes, out_planes, useDropout = False): |
19 | 19 | "3x3 convolution with padding"
|
20 |
| - return nn.Sequential( |
| 20 | + seq = nn.Sequential( |
21 | 21 | nn.Conv2d(in_planes, out_planes, kernel_size=3,
|
22 |
| - stride=stride, padding=padding, bias=bias), |
| 22 | + stride=1, padding=1, bias=True), |
23 | 23 | nn.BatchNorm2d(out_planes),
|
24 |
| - nn.LeakyReLU(0.2), |
25 |
| - nn.MaxPool2d(kernel_size=2, stride=2), |
26 |
| - nn.Dropout(0) |
| 24 | + nn.ReLU(True), |
| 25 | + nn.MaxPool2d(kernel_size=2, stride=2) |
27 | 26 | )
|
| 27 | + if useDropout: # Add dropout module |
| 28 | + list_seq = list(seq.modules())[1:] |
| 29 | + list_seq.append(nn.Dropout(0.1)) |
| 30 | + seq = nn.Sequential(*list_seq) |
28 | 31 |
|
| 32 | + return seq |
29 | 33 |
|
30 | 34 | class Classifier(nn.Module):
|
31 |
| - def __init__(self, layer_sizes, num_channels = 1, keep_prob = 0.5): |
| 35 | + def __init__(self, layer_sizes, nClasses = 0, num_channels = 1, useDropout = False): |
32 | 36 | super(Classifier, self).__init__()
|
33 | 37 |
|
34 | 38 | """
|
35 | 39 | Builds a CNN to produce embeddings
|
36 | 40 | :param layer_sizes: A list of length 4 containing the layer sizes
|
| 41 | + :param nClasses: If nClasses>0, we want a FC layer at the end with nClasses size. |
37 | 42 | :param num_channels: Number of channels of images
|
| 43 | + :param useDroput: use Dropout with p=0.1 in each Conv block |
38 | 44 | """
|
39 | 45 | assert len(layer_sizes)==4, "layer_sizes should be a list of length 4"
|
| 46 | + self.useClassification = False |
40 | 47 |
|
41 |
| - self.layer1 = convLayer(num_channels, layer_sizes[0]) |
42 |
| - self.layer2 = convLayer(layer_sizes[0], layer_sizes[1]) |
43 |
| - self.layer3 = convLayer(layer_sizes[1], layer_sizes[2]) |
44 |
| - self.layer4 = convLayer(layer_sizes[2], layer_sizes[3]) |
| 48 | + self.layer1 = convLayer(num_channels, layer_sizes[0], useDropout) |
| 49 | + self.layer2 = convLayer(layer_sizes[0], layer_sizes[1], useDropout) |
| 50 | + self.layer3 = convLayer(layer_sizes[1], layer_sizes[2], useDropout) |
| 51 | + self.layer4 = convLayer(layer_sizes[2], layer_sizes[3], useDropout) |
45 | 52 |
|
| 53 | + if nClasses>0: # We want a linear |
| 54 | + self.useClassification = True |
| 55 | + self.layer5 = nn.Linear(layer_sizes[3],nClasses) |
46 | 56 |
|
47 | 57 | self.weights_init(self.layer1)
|
48 | 58 | self.weights_init(self.layer2)
|
@@ -70,6 +80,8 @@ def forward(self, image_input):
|
70 | 80 | x = self.layer3(x)
|
71 | 81 | x = self.layer4(x)
|
72 | 82 | x = torch.squeeze(x)
|
| 83 | + if self.useClassification: |
| 84 | + x = self.layer5(x) |
73 | 85 | return x
|
74 | 86 |
|
75 | 87 |
|
|
0 commit comments