Spaces:
Sleeping
Sleeping
File size: 8,124 Bytes
4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be 4b0207f 47ac0be | 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | """
model.py
--------
Two segmentation architectures for binary skin lesion segmentation:
1. UNet β Classic U-Net with encoderβdecoder and skip connections.
2. BaselineCNN β Identical encoder/bottleneck/decoder but WITHOUT skip
connections, used to isolate the contribution of skip
connections to segmentation performance.
Channel progression (encoder β bottleneck β decoder):
3 β 64 β 128 β 256 β 512 β 1024 β 512 β 256 β 128 β 64 β 1
"""
import torch
import torch.nn as nn
from typing import List
# ---------------------------------------------------------------------------
# Shared building block
# ---------------------------------------------------------------------------
class DoubleConv(nn.Module):
"""
Two consecutive Conv2d β BatchNorm2d β ReLU blocks.
This is the fundamental repeated unit in both the U-Net encoder/decoder
and the Baseline CNN.
Args:
in_channels (int): Number of input feature maps.
out_channels (int): Number of output feature maps.
"""
def __init__(self, in_channels: int, out_channels: int) -> None:
"""Build the sequential double-conv block."""
super().__init__()
self.block = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Apply double-conv block to input tensor."""
return self.block(x)
# ---------------------------------------------------------------------------
# U-Net
# ---------------------------------------------------------------------------
class UNet(nn.Module):
"""
U-Net for binary segmentation.
Architecture:
Encoder : 4 DoubleConv blocks (64β128β256β512), each followed by
MaxPool2d(2, 2) for spatial downsampling.
Bottleneck : DoubleConv block (512β1024).
Decoder : 4 blocks, each using ConvTranspose2d for upsampling, then
concatenating the corresponding encoder skip connection,
then a DoubleConv block.
Output : 1Γ1 Conv2d followed by Sigmoid activation.
Args:
in_channels (int): Number of input image channels (default 3 for RGB).
out_channels (int): Number of output segmentation channels (default 1).
features (List[int]): Channel sizes for encoder blocks.
"""
def __init__(
self,
in_channels: int = 3,
out_channels: int = 1,
features: List[int] = [64, 128, 256, 512],
) -> None:
"""Initialise U-Net encoder, bottleneck, decoder, and output head with skip connections."""
super().__init__()
# ---- Encoder ----
self.encoders = nn.ModuleList()
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
ch = in_channels
for feat in features:
self.encoders.append(DoubleConv(ch, feat))
ch = feat
# ---- Bottleneck ----
self.bottleneck = DoubleConv(features[-1], features[-1] * 2)
ch = features[-1] * 2 # 1024
# ---- Decoder ----
self.up_convs = nn.ModuleList()
self.decoders = nn.ModuleList()
for feat in reversed(features):
# Upsample: 2Γ spatial, halve channels
self.up_convs.append(
nn.ConvTranspose2d(ch, feat, kernel_size=2, stride=2)
)
# After skip-connection concat: feat (upsampled) + feat (skip) β feat
self.decoders.append(DoubleConv(feat * 2, feat))
ch = feat
# ---- Output head ----
self.output_conv = nn.Conv2d(features[0], out_channels, kernel_size=1)
self.sigmoid = nn.Sigmoid()
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass through U-Net.
Args:
x (Tensor): Input image batch, shape (N, 3, H, W).
Returns:
Tensor: Sigmoid-activated segmentation map, shape (N, 1, H, W).
"""
skip_connections: List[torch.Tensor] = []
# Encoder path
for encoder in self.encoders:
x = encoder(x)
skip_connections.append(x)
x = self.pool(x)
# Bottleneck
x = self.bottleneck(x)
# Decoder path (skip connections in reverse order)
skip_connections = skip_connections[::-1]
for up_conv, decoder, skip in zip(
self.up_convs, self.decoders, skip_connections
):
x = up_conv(x)
# Handle potential size mismatch due to odd spatial dimensions
if x.shape != skip.shape:
x = nn.functional.interpolate(
x, size=skip.shape[2:], mode="bilinear", align_corners=False
)
x = torch.cat([skip, x], dim=1)
x = decoder(x)
return self.sigmoid(self.output_conv(x))
# ---------------------------------------------------------------------------
# Baseline CNN (no skip connections)
# ---------------------------------------------------------------------------
class BaselineCNN(nn.Module):
"""
Baseline segmentation CNN β identical to U-Net in structure but WITHOUT
skip connections between encoder and decoder.
This model serves as an ablation baseline to quantify the benefit of skip
connections. The decoder receives only the upsampled feature maps from
the previous decoder stage (or the bottleneck), with no concatenated
encoder features.
Args:
in_channels (int): Number of input image channels (default 3).
out_channels (int): Number of output segmentation channels (default 1).
features (List[int]): Channel sizes for encoder blocks.
"""
def __init__(
self,
in_channels: int = 3,
out_channels: int = 1,
features: List[int] = [64, 128, 256, 512],
) -> None:
"""Initialise Baseline CNN encoder, bottleneck, decoder, and output head (no skip connections)."""
super().__init__()
# ---- Encoder ----
self.encoders = nn.ModuleList()
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
ch = in_channels
for feat in features:
self.encoders.append(DoubleConv(ch, feat))
ch = feat
# ---- Bottleneck ----
self.bottleneck = DoubleConv(features[-1], features[-1] * 2)
ch = features[-1] * 2 # 1024
# ---- Decoder (NO skip connections β input channels halved) ----
self.up_convs = nn.ModuleList()
self.decoders = nn.ModuleList()
for feat in reversed(features):
self.up_convs.append(
nn.ConvTranspose2d(ch, feat, kernel_size=2, stride=2)
)
# No concatenation β input to DoubleConv is just `feat`
self.decoders.append(DoubleConv(feat, feat))
ch = feat
# ---- Output head ----
self.output_conv = nn.Conv2d(features[0], out_channels, kernel_size=1)
self.sigmoid = nn.Sigmoid()
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass through Baseline CNN (no skip connections).
Args:
x (Tensor): Input image batch, shape (N, 3, H, W).
Returns:
Tensor: Sigmoid-activated segmentation map, shape (N, 1, H, W).
"""
# Encoder path β no skip connections saved
for encoder in self.encoders:
x = encoder(x)
x = self.pool(x)
# Bottleneck
x = self.bottleneck(x)
# Decoder path β only upsampled features, no concat
for up_conv, decoder in zip(self.up_convs, self.decoders):
x = up_conv(x)
x = decoder(x)
return self.sigmoid(self.output_conv(x))
|