FolashadeO commited on
Commit
4769c60
·
verified ·
1 Parent(s): 282b1e3

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +47 -106
model.py CHANGED
@@ -1,119 +1,60 @@
1
- """U-Net model for binary medical image segmentation.
2
-
3
- The assignment requires an output mask of shape ``1 x H x W``. This module
4
- therefore returns one logit channel per pixel; sigmoid activation is applied
5
- inside the loss/metric code or during inference, not inside the model.
6
- """
7
-
8
- from __future__ import annotations
9
-
10
  import torch
11
- from torch import nn
12
- from torch.nn import functional as F
13
-
14
 
15
  class DoubleConv(nn.Module):
16
- """Two convolution blocks used throughout the U-Net encoder and decoder."""
17
-
18
- def __init__(self, in_channels: int, out_channels: int) -> None:
19
  super().__init__()
20
- self.block = nn.Sequential(
21
  nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
22
  nn.BatchNorm2d(out_channels),
23
  nn.ReLU(inplace=True),
24
  nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False),
25
  nn.BatchNorm2d(out_channels),
26
- nn.ReLU(inplace=True),
27
- )
28
-
29
- def forward(self, x: torch.Tensor) -> torch.Tensor:
30
- return self.block(x)
31
-
32
-
33
- class DownBlock(nn.Module):
34
- """Encoder block: reduce spatial size, then extract richer features."""
35
-
36
- def __init__(self, in_channels: int, out_channels: int) -> None:
37
- super().__init__()
38
- self.block = nn.Sequential(
39
- nn.MaxPool2d(kernel_size=2, stride=2),
40
- DoubleConv(in_channels, out_channels),
41
  )
42
-
43
- def forward(self, x: torch.Tensor) -> torch.Tensor:
44
- return self.block(x)
45
-
46
-
47
- class UpBlock(nn.Module):
48
- """Decoder block with learned upsampling and a U-Net skip connection."""
49
-
50
- def __init__(self, in_channels: int, skip_channels: int, out_channels: int) -> None:
51
- super().__init__()
52
- self.up = nn.ConvTranspose2d(
53
- in_channels,
54
- out_channels,
55
- kernel_size=2,
56
- stride=2,
57
- )
58
- self.conv = DoubleConv(out_channels + skip_channels, out_channels)
59
-
60
- def forward(self, x: torch.Tensor, skip: torch.Tensor) -> torch.Tensor:
61
- x = self.up(x)
62
-
63
- # Resize defensively in case an input dimension is not perfectly divisible
64
- # by 16. The default 256 x 256 preprocessing does not need this path.
65
- if x.shape[-2:] != skip.shape[-2:]:
66
- x = F.interpolate(
67
- x,
68
- size=skip.shape[-2:],
69
- mode="bilinear",
70
- align_corners=False,
71
- )
72
-
73
- return self.conv(torch.cat([skip, x], dim=1))
74
-
75
 
76
  class UNet(nn.Module):
77
- """A compact four-level U-Net for binary Kvasir-SEG polyp segmentation."""
78
-
79
- def __init__(
80
- self,
81
- in_channels: int = 3,
82
- out_channels: int = 1,
83
- features: tuple[int, int, int, int] = (64, 128, 256, 512),
84
- ) -> None:
85
  super().__init__()
86
- f1, f2, f3, f4 = features
87
-
88
- self.encoder1 = DoubleConv(in_channels, f1)
89
- self.encoder2 = DownBlock(f1, f2)
90
- self.encoder3 = DownBlock(f2, f3)
91
- self.encoder4 = DownBlock(f3, f4)
92
-
93
- self.bottleneck = DownBlock(f4, f4 * 2)
94
-
95
- self.decoder4 = UpBlock(f4 * 2, f4, f4)
96
- self.decoder3 = UpBlock(f4, f3, f3)
97
- self.decoder2 = UpBlock(f3, f2, f2)
98
- self.decoder1 = UpBlock(f2, f1, f1)
99
-
100
- self.output_conv = nn.Conv2d(f1, out_channels, kernel_size=1)
101
-
102
- def forward(
103
- self,
104
- pixel_values: torch.Tensor,
105
- labels: torch.Tensor | None = None,
106
- ) -> torch.Tensor:
107
- enc1 = self.encoder1(pixel_values)
108
- enc2 = self.encoder2(enc1)
109
- enc3 = self.encoder3(enc2)
110
- enc4 = self.encoder4(enc3)
111
-
112
- bottleneck = self.bottleneck(enc4)
113
-
114
- dec4 = self.decoder4(bottleneck, enc4)
115
- dec3 = self.decoder3(dec4, enc3)
116
- dec2 = self.decoder2(dec3, enc2)
117
- dec1 = self.decoder1(dec2, enc1)
118
-
119
- return self.output_conv(dec1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import torch
2
+ import torch.nn as nn
 
 
3
 
4
  class DoubleConv(nn.Module):
5
+ def __init__(self, in_channels, out_channels):
 
 
6
  super().__init__()
7
+ self.double_conv = nn.Sequential(
8
  nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
9
  nn.BatchNorm2d(out_channels),
10
  nn.ReLU(inplace=True),
11
  nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False),
12
  nn.BatchNorm2d(out_channels),
13
+ nn.ReLU(inplace=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  )
15
+ def forward(self, x): return self.double_conv(x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  class UNet(nn.Module):
18
+ def __init__(self, in_channels: int = 3, out_channels: int = 1):
 
 
 
 
 
 
 
19
  super().__init__()
20
+ self.inc = DoubleConv(in_channels, 64)
21
+ self.down1 = nn.Sequential(nn.MaxPool2d(2), DoubleConv(64, 128))
22
+ self.down2 = nn.Sequential(nn.MaxPool2d(2), DoubleConv(128, 256))
23
+ self.down3 = nn.Sequential(nn.MaxPool2d(2), DoubleConv(256, 512))
24
+ self.down4 = nn.MaxPool2d(2)
25
+ self.bottleneck = DoubleConv(512, 1024)
26
+
27
+ self.up1 = nn.ConvTranspose2d(1024, 512, kernel_size=2, stride=2)
28
+ self.conv1 = DoubleConv(1024, 512)
29
+ self.up2 = nn.ConvTranspose2d(512, 256, kernel_size=2, stride=2)
30
+ self.conv2 = DoubleConv(512, 256)
31
+ self.up3 = nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2)
32
+ self.conv3 = DoubleConv(256, 128)
33
+ self.up4 = nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2)
34
+ self.conv4 = DoubleConv(128, 64)
35
+ self.outc = nn.Conv2d(64, out_channels, kernel_size=1)
36
+
37
+ def forward(self, x):
38
+ x1 = self.inc(x)
39
+ x2 = self.down1(x1)
40
+ x3 = self.down2(x2)
41
+ x4 = self.down3(x3)
42
+ b = self.down4(x4)
43
+ b = self.bottleneck(b)
44
+
45
+ x = self.up1(b)
46
+ x = torch.cat([x, x4], dim=1)
47
+ x = self.conv1(x)
48
+
49
+ x = self.up2(x)
50
+ x = torch.cat([x, x3], dim=1)
51
+ x = self.conv2(x)
52
+
53
+ x = self.up3(x)
54
+ x = torch.cat([x, x2], dim=1)
55
+ x = self.conv3(x)
56
+
57
+ x = self.up4(x)
58
+ x = torch.cat([x, x1], dim=1)
59
+ x = self.conv4(x)
60
+ return self.outc(x)