Spaces:
Build error
Build error
| # ---------------------------- | |
| # Step 3.1: Define core building blocks | |
| # ---------------------------- | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| # A simple helper: 2×(Conv -> BN -> ReLU) | |
| class DoubleConv(nn.Module): | |
| def __init__(self, in_channels, out_channels): | |
| super(DoubleConv, self).__init__() | |
| self.double_conv = 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): | |
| return self.double_conv(x) | |
| # ---------------------------- | |
| # Step 3.2: Define the full U-Net architecture | |
| # ---------------------------- | |
| class UNet(nn.Module): | |
| def __init__(self, in_channels=3, out_channels=1, features=[64, 128, 256, 512]): | |
| super(UNet, self).__init__() | |
| self.downs = nn.ModuleList() | |
| self.ups = nn.ModuleList() | |
| self.pool = nn.MaxPool2d(kernel_size=2, stride=2) | |
| # Encoder path | |
| for feature in features: | |
| self.downs.append(DoubleConv(in_channels, feature)) | |
| in_channels = feature | |
| # Bottleneck | |
| self.bottleneck = DoubleConv(features[-1], features[-1]*2) | |
| # Decoder path | |
| for feature in reversed(features): | |
| self.ups.append( | |
| nn.ConvTranspose2d(feature*2, feature, kernel_size=2, stride=2) | |
| ) | |
| self.ups.append(DoubleConv(feature*2, feature)) | |
| # Output layer | |
| self.final_conv = nn.Conv2d(features[0], out_channels, kernel_size=1) | |
| def forward(self, x): | |
| skip_connections = [] | |
| # Encoder | |
| for down in self.downs: | |
| x = down(x) | |
| skip_connections.append(x) | |
| x = self.pool(x) | |
| # Bottleneck | |
| x = self.bottleneck(x) | |
| # Decoder | |
| skip_connections = skip_connections[::-1] | |
| for idx in range(0, len(self.ups), 2): | |
| x = self.ups[idx](x) # upsample | |
| skip_connection = skip_connections[idx//2] | |
| # Handle potential size mismatch due to pooling | |
| if x.shape != skip_connection.shape: | |
| x = nn.functional.interpolate(x, size=skip_connection.shape[2:]) | |
| concat_skip = torch.cat((skip_connection, x), dim=1) | |
| x = self.ups[idx+1](concat_skip) | |
| return self.final_conv(x) | |