Datasets:
model and lightning module
Browse files- lightning_module.py +0 -165
- model_and_lightning_module.py +152 -0
lightning_module.py
DELETED
|
@@ -1,165 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
PyTorch Lightning modules for roof segmentation.
|
| 3 |
-
"""
|
| 4 |
-
import torch
|
| 5 |
-
import torch.nn as nn
|
| 6 |
-
import pytorch_lightning as pl
|
| 7 |
-
from torch.utils.data import DataLoader
|
| 8 |
-
from typing import Dict, Any, Optional
|
| 9 |
-
|
| 10 |
-
from utils.dataset import create_dataloaders
|
| 11 |
-
from utils.losses import DiceBCELoss
|
| 12 |
-
from utils.metrics import get_segmentation_metrics
|
| 13 |
-
from utils.models import get_unet_model
|
| 14 |
-
from config import (
|
| 15 |
-
TRAIN_IMAGES_DIR, TRAIN_MASKS_DIR,
|
| 16 |
-
VALID_IMAGES_DIR, VALID_MASKS_DIR,
|
| 17 |
-
TRAINING_CONFIG
|
| 18 |
-
)
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
class SegmentationLightningModule(pl.LightningModule):
|
| 22 |
-
"""Lightning module for segmentation training."""
|
| 23 |
-
|
| 24 |
-
def __init__(self, config: Dict[str, Any]):
|
| 25 |
-
super().__init__()
|
| 26 |
-
self.save_hyperparameters(config)
|
| 27 |
-
self.config = config
|
| 28 |
-
|
| 29 |
-
# Model
|
| 30 |
-
self.model = get_unet_model(
|
| 31 |
-
n_channels=config["in_channels"],
|
| 32 |
-
n_classes=config["classes"],
|
| 33 |
-
base_channels=config.get("base_channels", 32),
|
| 34 |
-
bilinear=config.get("bilinear", True)
|
| 35 |
-
)
|
| 36 |
-
|
| 37 |
-
# Loss function
|
| 38 |
-
self.criterion = DiceBCELoss(
|
| 39 |
-
dice_weight=config["dice_weight"],
|
| 40 |
-
bce_weight=config["bce_weight"]
|
| 41 |
-
)
|
| 42 |
-
|
| 43 |
-
# Metrics
|
| 44 |
-
self.train_metrics = get_segmentation_metrics()
|
| 45 |
-
self.val_metrics = get_segmentation_metrics()
|
| 46 |
-
|
| 47 |
-
def forward(self, x):
|
| 48 |
-
return self.model(x)
|
| 49 |
-
|
| 50 |
-
def training_step(self, batch, batch_idx):
|
| 51 |
-
images = batch['image']
|
| 52 |
-
masks = batch['mask']
|
| 53 |
-
|
| 54 |
-
# Ensure masks have the right dimensions [B, 1, H, W]
|
| 55 |
-
if masks.dim() == 3:
|
| 56 |
-
masks = masks.unsqueeze(1) # Add channel dimension
|
| 57 |
-
|
| 58 |
-
outputs = self(images)
|
| 59 |
-
loss = self.criterion(outputs, masks)
|
| 60 |
-
|
| 61 |
-
# Calculate metrics
|
| 62 |
-
preds_sigmoid = torch.sigmoid(outputs)
|
| 63 |
-
|
| 64 |
-
# For torchmetrics, we need to squeeze the channel dimension and convert to binary
|
| 65 |
-
masks_squeezed = masks.squeeze(1) # [B, H, W]
|
| 66 |
-
preds_squeezed = preds_sigmoid.squeeze(1) # [B, H, W]
|
| 67 |
-
|
| 68 |
-
# Update metrics
|
| 69 |
-
self.train_metrics.update(preds_squeezed, masks_squeezed.int())
|
| 70 |
-
|
| 71 |
-
# Log metrics
|
| 72 |
-
self.log('train_loss', loss, on_step=True, on_epoch=True, prog_bar=True)
|
| 73 |
-
|
| 74 |
-
return loss
|
| 75 |
-
|
| 76 |
-
def on_train_epoch_end(self):
|
| 77 |
-
# Log training metrics
|
| 78 |
-
computed_metrics = self.train_metrics.compute()
|
| 79 |
-
for name, value in computed_metrics.items():
|
| 80 |
-
self.log(f'train_{name}', value, on_epoch=True, prog_bar=True)
|
| 81 |
-
self.train_metrics.reset()
|
| 82 |
-
|
| 83 |
-
def validation_step(self, batch, batch_idx):
|
| 84 |
-
images = batch['image']
|
| 85 |
-
masks = batch['mask']
|
| 86 |
-
|
| 87 |
-
# Ensure masks have the right dimensions [B, 1, H, W]
|
| 88 |
-
if masks.dim() == 3:
|
| 89 |
-
masks = masks.unsqueeze(1) # Add channel dimension
|
| 90 |
-
|
| 91 |
-
outputs = self(images)
|
| 92 |
-
loss = self.criterion(outputs, masks)
|
| 93 |
-
|
| 94 |
-
# Calculate metrics
|
| 95 |
-
preds_sigmoid = torch.sigmoid(outputs)
|
| 96 |
-
|
| 97 |
-
# For torchmetrics, we need to squeeze the channel dimension and convert to binary
|
| 98 |
-
masks_squeezed = masks.squeeze(1) # [B, H, W]
|
| 99 |
-
preds_squeezed = preds_sigmoid.squeeze(1) # [B, H, W]
|
| 100 |
-
|
| 101 |
-
# Update metrics
|
| 102 |
-
self.val_metrics.update(preds_squeezed, masks_squeezed.int())
|
| 103 |
-
|
| 104 |
-
# Log metrics
|
| 105 |
-
self.log('val_loss', loss, on_step=False, on_epoch=True, prog_bar=True)
|
| 106 |
-
|
| 107 |
-
return loss
|
| 108 |
-
|
| 109 |
-
def on_validation_epoch_end(self):
|
| 110 |
-
# Log validation metrics
|
| 111 |
-
computed_metrics = self.val_metrics.compute()
|
| 112 |
-
for name, value in computed_metrics.items():
|
| 113 |
-
self.log(f'val_{name}', value, on_epoch=True, prog_bar=True)
|
| 114 |
-
self.val_metrics.reset()
|
| 115 |
-
|
| 116 |
-
def configure_optimizers(self):
|
| 117 |
-
optimizer = torch.optim.AdamW(
|
| 118 |
-
self.parameters(),
|
| 119 |
-
lr=self.config["learning_rate"],
|
| 120 |
-
weight_decay=self.config["weight_decay"]
|
| 121 |
-
)
|
| 122 |
-
|
| 123 |
-
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
|
| 124 |
-
optimizer,
|
| 125 |
-
mode='min',
|
| 126 |
-
patience=self.config["reduce_lr_patience"],
|
| 127 |
-
factor=self.config["reduce_lr_factor"],
|
| 128 |
-
)
|
| 129 |
-
|
| 130 |
-
return {
|
| 131 |
-
"optimizer": optimizer,
|
| 132 |
-
"lr_scheduler": {
|
| 133 |
-
"scheduler": scheduler,
|
| 134 |
-
"monitor": "val_loss",
|
| 135 |
-
"frequency": 1
|
| 136 |
-
}
|
| 137 |
-
}
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
class SegmentationDataModule(pl.LightningDataModule):
|
| 141 |
-
"""Lightning data module for segmentation."""
|
| 142 |
-
|
| 143 |
-
def __init__(self, config: Dict[str, Any]):
|
| 144 |
-
super().__init__()
|
| 145 |
-
self.config = config
|
| 146 |
-
self.train_loader = None
|
| 147 |
-
self.val_loader = None
|
| 148 |
-
|
| 149 |
-
def setup(self, stage: Optional[str] = None):
|
| 150 |
-
if stage == "fit" or stage is None:
|
| 151 |
-
self.train_loader, self.val_loader = create_dataloaders(
|
| 152 |
-
train_images_dir=TRAIN_IMAGES_DIR,
|
| 153 |
-
train_masks_dir=TRAIN_MASKS_DIR,
|
| 154 |
-
val_images_dir=VALID_IMAGES_DIR,
|
| 155 |
-
val_masks_dir=VALID_MASKS_DIR,
|
| 156 |
-
batch_size=self.config["batch_size"],
|
| 157 |
-
num_workers=self.config["num_workers"],
|
| 158 |
-
image_size=self.config["image_size"]
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
def train_dataloader(self):
|
| 162 |
-
return self.train_loader
|
| 163 |
-
|
| 164 |
-
def val_dataloader(self):
|
| 165 |
-
return self.val_loader
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PyTorch Lightning modules for roof segmentation.
|
| 3 |
+
"""
|
| 4 |
+
from typing import Any, Dict
|
| 5 |
+
|
| 6 |
+
import pytorch_lightning as pl
|
| 7 |
+
import torch
|
| 8 |
+
import torch.nn as nn
|
| 9 |
+
import torch.nn.functional as F
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class DoubleConv(nn.Module):
|
| 13 |
+
"""Double convolution block: (conv => BN => ReLU) * 2"""
|
| 14 |
+
|
| 15 |
+
def __init__(self, in_channels, out_channels):
|
| 16 |
+
super().__init__()
|
| 17 |
+
self.double_conv = nn.Sequential(
|
| 18 |
+
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
|
| 19 |
+
nn.BatchNorm2d(out_channels),
|
| 20 |
+
nn.ReLU(inplace=True),
|
| 21 |
+
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
|
| 22 |
+
nn.BatchNorm2d(out_channels),
|
| 23 |
+
nn.ReLU(inplace=True)
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
def forward(self, x):
|
| 27 |
+
return self.double_conv(x)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Down(nn.Module):
|
| 31 |
+
"""Downscaling with maxpool then double conv"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, in_channels, out_channels):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.maxpool_conv = nn.Sequential(
|
| 36 |
+
nn.MaxPool2d(2),
|
| 37 |
+
DoubleConv(in_channels, out_channels)
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
def forward(self, x):
|
| 41 |
+
return self.maxpool_conv(x)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Up(nn.Module):
|
| 45 |
+
"""Upscaling then double conv"""
|
| 46 |
+
|
| 47 |
+
def __init__(self, in_channels, out_channels, bilinear=True):
|
| 48 |
+
super().__init__()
|
| 49 |
+
|
| 50 |
+
# Use bilinear upsampling or transpose convolution
|
| 51 |
+
if bilinear:
|
| 52 |
+
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
|
| 53 |
+
self.conv = DoubleConv(in_channels, out_channels)
|
| 54 |
+
else:
|
| 55 |
+
self.up = nn.ConvTranspose2d(in_channels, in_channels // 2, kernel_size=2, stride=2)
|
| 56 |
+
self.conv = DoubleConv(in_channels, out_channels)
|
| 57 |
+
|
| 58 |
+
def forward(self, x1, x2):
|
| 59 |
+
x1 = self.up(x1)
|
| 60 |
+
|
| 61 |
+
# Input is CHW
|
| 62 |
+
diffY = x2.size()[2] - x1.size()[2]
|
| 63 |
+
diffX = x2.size()[3] - x1.size()[3]
|
| 64 |
+
|
| 65 |
+
x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
|
| 66 |
+
diffY // 2, diffY - diffY // 2])
|
| 67 |
+
|
| 68 |
+
# Concatenate along channel dimension
|
| 69 |
+
x = torch.cat([x2, x1], dim=1)
|
| 70 |
+
return self.conv(x)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class OutConv(nn.Module):
|
| 74 |
+
"""Output convolution"""
|
| 75 |
+
|
| 76 |
+
def __init__(self, in_channels, out_channels):
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
|
| 79 |
+
|
| 80 |
+
def forward(self, x):
|
| 81 |
+
return self.conv(x)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class UNet(nn.Module):
|
| 85 |
+
"""Simple U-Net implementation with configurable base channels"""
|
| 86 |
+
|
| 87 |
+
def __init__(self, n_channels=3, n_classes=1, base_channels=32, bilinear=True):
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.n_channels = n_channels
|
| 90 |
+
self.n_classes = n_classes
|
| 91 |
+
self.bilinear = bilinear
|
| 92 |
+
|
| 93 |
+
# Use configurable base channels (default 32 instead of 64)
|
| 94 |
+
c = base_channels
|
| 95 |
+
|
| 96 |
+
# Encoder (downsampling path)
|
| 97 |
+
self.inc = DoubleConv(n_channels, c)
|
| 98 |
+
self.down1 = Down(c, c*2)
|
| 99 |
+
self.down2 = Down(c*2, c*4)
|
| 100 |
+
self.down3 = Down(c*4, c*8)
|
| 101 |
+
factor = 2 if bilinear else 1
|
| 102 |
+
self.down4 = Down(c*8, c*16 // factor)
|
| 103 |
+
|
| 104 |
+
# Decoder (upsampling path)
|
| 105 |
+
self.up1 = Up(c*16, c*8 // factor, bilinear)
|
| 106 |
+
self.up2 = Up(c*8, c*4 // factor, bilinear)
|
| 107 |
+
self.up3 = Up(c*4, c*2 // factor, bilinear)
|
| 108 |
+
self.up4 = Up(c*2, c, bilinear)
|
| 109 |
+
self.outc = OutConv(c, n_classes)
|
| 110 |
+
|
| 111 |
+
def forward(self, x):
|
| 112 |
+
# Encoder
|
| 113 |
+
x1 = self.inc(x)
|
| 114 |
+
x2 = self.down1(x1)
|
| 115 |
+
x3 = self.down2(x2)
|
| 116 |
+
x4 = self.down3(x3)
|
| 117 |
+
x5 = self.down4(x4)
|
| 118 |
+
|
| 119 |
+
# Decoder with skip connections
|
| 120 |
+
x = self.up1(x5, x4)
|
| 121 |
+
x = self.up2(x, x3)
|
| 122 |
+
x = self.up3(x, x2)
|
| 123 |
+
x = self.up4(x, x1)
|
| 124 |
+
logits = self.outc(x)
|
| 125 |
+
return logits
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def get_unet_model(n_channels=3, n_classes=1, base_channels=32, bilinear=True):
|
| 129 |
+
"""
|
| 130 |
+
Create a U-Net model.
|
| 131 |
+
|
| 132 |
+
Args:
|
| 133 |
+
n_channels: Number of input channels
|
| 134 |
+
n_classes: Number of output classes
|
| 135 |
+
base_channels: Base number of channels (32 = lighter, 64 = standard)
|
| 136 |
+
bilinear: Use bilinear upsampling
|
| 137 |
+
"""
|
| 138 |
+
return UNet(n_channels=n_channels, n_classes=n_classes, base_channels=base_channels, bilinear=bilinear)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class SegmentationLightningModule(pl.LightningModule):
|
| 142 |
+
def __init__(self, config: Dict[str, Any]):
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.model = get_unet_model(
|
| 145 |
+
n_channels=config["in_channels"],
|
| 146 |
+
n_classes=config["classes"],
|
| 147 |
+
base_channels=config.get("base_channels", 32),
|
| 148 |
+
bilinear=config.get("bilinear", True)
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
def forward(self, x):
|
| 152 |
+
return self.model(x)
|