Views
No views yet
1class UNet(nn.Module, PyTorchModelHubMixin):
2 def __init__(self, in_channels, out_channels):
3 super(UNet, self).__init__()
4
5 # Contracting Path (Encoder)
6 self.down_conv1 = DoubleConv(in_channels, 64)
7 self.down_conv2 = DoubleConv(64, 128)
8 self.down_conv3 = DoubleConv(128, 256)
9 self.down_conv4 = DoubleConv(256, 512)
10 self.down_conv5 = DoubleConv(512, 1024)
11
12 # Downsampling
13 self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
14
15 # Upsampling layers using nn.Upsample
16 self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
17
18 # Decoder (Expanding Path)
19 self.up_conv1 = DoubleConv(1024 + 512, 512)
20 self.up_conv2 = DoubleConv(512 + 256, 256)
21 self.up_conv3 = DoubleConv(256 + 128, 128)
22 self.up_conv4 = DoubleConv(128 + 64, 64)
23
24 # Final 1x1 convolution to get desired number of output channels
25 self.final_conv = nn.Conv2d(64, out_channels, kernel_size=1)
26
27 def forward(self, x):
28 x1 = self.down_conv1(x)
29 x2 = self.down_conv2(self.maxpool(x1))
30 x3 = self.down_conv3(self.maxpool(x2))
31 x4 = self.down_conv4(self.maxpool(x3))
32 x5 = self.down_conv5(self.maxpool(x4))
33
34 x = self.upsample(x5)
35 x = torch.cat([x4, x], dim=1)
36 x = self.up_conv1(x)
37
38 x = self.upsample(x)
39 x = torch.cat([x3, x], dim=1)
40 x = self.up_conv2(x)
41
42 x = self.upsample(x)
43 x = torch.cat([x2, x], dim=1)
44 x = self.up_conv3(x)
45
46 x = self.upsample(x)
47 x = torch.cat([x1, x], dim=1)
48 x = self.up_conv4(x)
49
50 return self.final_conv(x)
51
52
53class PatchGANDiscriminator(nn.Module, PyTorchModelHubMixin):
54 def __init__(self, in_channels=6):
55 super().__init__()
56
57 self.layers = nn.Sequential(
58 nn.Conv2d(in_channels, 64, kernel_size=4, stride=2, padding=1),
59 nn.LeakyReLU(0.2, inplace=True),
60 nn.Conv2d(64, 128, kernel_size=4, stride=2, padding=1),
61 nn.InstanceNorm2d(128),
62 nn.LeakyReLU(0.2, inplace=True),
63 nn.Conv2d(128, 256, kernel_size=4, stride=2, padding=1),
64 nn.InstanceNorm2d(256),
65 nn.LeakyReLU(0.2, inplace=True),
66 nn.Conv2d(256, 512, kernel_size=4, stride=1, padding=1),
67 nn.InstanceNorm2d(512),
68 nn.LeakyReLU(0.2, inplace=True),
69 nn.Conv2d(512, 1, kernel_size=4, stride=1, padding=1),
70 )
71
72 def forward(self, x):
73 return self.layers(x)