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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unified training script for deterministic segmentation baselines.
|
| 3 |
+
Uses official libraries: smp (U-Net, U-Net++), MONAI (Attention U-Net), smp MAnet (TransUNet-style).
|
| 4 |
+
"""
|
| 5 |
+
import argparse
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import time
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn as nn
|
| 12 |
+
import torch.optim as optim
|
| 13 |
+
from torch.utils.data import DataLoader, random_split
|
| 14 |
+
|
| 15 |
+
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 16 |
+
from dataset import LIDCFlatDataset
|
| 17 |
+
from models import get_model
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DiceBCELoss(nn.Module):
|
| 21 |
+
"""Combined Dice + BCE loss for binary segmentation."""
|
| 22 |
+
def __init__(self, dice_weight=0.5, bce_weight=0.5):
|
| 23 |
+
super().__init__()
|
| 24 |
+
self.dice_weight = dice_weight
|
| 25 |
+
self.bce_weight = bce_weight
|
| 26 |
+
self.bce = nn.BCEWithLogitsLoss()
|
| 27 |
+
|
| 28 |
+
def forward(self, logits, targets):
|
| 29 |
+
# BCE loss
|
| 30 |
+
bce_loss = self.bce(logits, targets)
|
| 31 |
+
|
| 32 |
+
# Dice loss
|
| 33 |
+
probs = torch.sigmoid(logits)
|
| 34 |
+
smooth = 1e-5
|
| 35 |
+
intersection = (probs * targets).sum(dim=(2, 3))
|
| 36 |
+
dice = (2. * intersection + smooth) / (probs.sum(dim=(2, 3)) + targets.sum(dim=(2, 3)) + smooth)
|
| 37 |
+
dice_loss = 1 - dice.mean()
|
| 38 |
+
|
| 39 |
+
return self.dice_weight * dice_loss + self.bce_weight * bce_loss
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def compute_dice(pred, target):
|
| 43 |
+
"""Compute Dice coefficient for evaluation."""
|
| 44 |
+
smooth = 1e-5
|
| 45 |
+
pred = (torch.sigmoid(pred) > 0.5).float()
|
| 46 |
+
intersection = (pred * target).sum()
|
| 47 |
+
return (2. * intersection + smooth) / (pred.sum() + target.sum() + smooth)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def train_one_epoch(model, loader, optimizer, criterion, device):
|
| 51 |
+
model.train()
|
| 52 |
+
total_loss = 0
|
| 53 |
+
total_dice = 0
|
| 54 |
+
|
| 55 |
+
for images, masks, _ in loader:
|
| 56 |
+
images = images.to(device)
|
| 57 |
+
masks = masks.to(device)
|
| 58 |
+
|
| 59 |
+
optimizer.zero_grad()
|
| 60 |
+
outputs = model(images)
|
| 61 |
+
loss = criterion(outputs, masks)
|
| 62 |
+
loss.backward()
|
| 63 |
+
optimizer.step()
|
| 64 |
+
|
| 65 |
+
total_loss += loss.item()
|
| 66 |
+
total_dice += compute_dice(outputs, masks).item()
|
| 67 |
+
|
| 68 |
+
return total_loss / len(loader), total_dice / len(loader)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@torch.no_grad()
|
| 72 |
+
def validate(model, loader, criterion, device):
|
| 73 |
+
model.eval()
|
| 74 |
+
total_loss = 0
|
| 75 |
+
total_dice = 0
|
| 76 |
+
|
| 77 |
+
for images, masks, _ in loader:
|
| 78 |
+
images = images.to(device)
|
| 79 |
+
masks = masks.to(device)
|
| 80 |
+
|
| 81 |
+
outputs = model(images)
|
| 82 |
+
loss = criterion(outputs, masks)
|
| 83 |
+
|
| 84 |
+
total_loss += loss.item()
|
| 85 |
+
total_dice += compute_dice(outputs, masks).item()
|
| 86 |
+
|
| 87 |
+
return total_loss / len(loader), total_dice / len(loader)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def main():
|
| 91 |
+
parser = argparse.ArgumentParser(description="Train deterministic segmentation baseline")
|
| 92 |
+
parser.add_argument("--model", type=str, required=True,
|
| 93 |
+
choices=["unet", "attention_unet", "unetpp", "transunet", "nnunet"],
|
| 94 |
+
help="Model architecture")
|
| 95 |
+
parser.add_argument("--data_dir", type=str, default="data/flat_train",
|
| 96 |
+
help="Path to flat training data")
|
| 97 |
+
parser.add_argument("--epochs", type=int, default=100, help="Number of epochs")
|
| 98 |
+
parser.add_argument("--batch_size", type=int, default=32, help="Batch size")
|
| 99 |
+
parser.add_argument("--lr", type=float, default=1e-3, help="Learning rate")
|
| 100 |
+
parser.add_argument("--val_split", type=float, default=0.1, help="Validation split ratio")
|
| 101 |
+
parser.add_argument("--checkpoint_dir", type=str, default="checkpoints", help="Checkpoint directory")
|
| 102 |
+
parser.add_argument("--num_workers", type=int, default=4, help="DataLoader workers")
|
| 103 |
+
parser.add_argument("--patience", type=int, default=20, help="Early stopping patience")
|
| 104 |
+
args = parser.parse_args()
|
| 105 |
+
|
| 106 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 107 |
+
print(f"Using device: {device}")
|
| 108 |
+
|
| 109 |
+
os.makedirs(args.checkpoint_dir, exist_ok=True)
|
| 110 |
+
|
| 111 |
+
# Create dataset
|
| 112 |
+
full_dataset = LIDCFlatDataset(args.data_dir, augment=True)
|
| 113 |
+
|
| 114 |
+
# Split into train/val
|
| 115 |
+
val_size = int(len(full_dataset) * args.val_split)
|
| 116 |
+
train_size = len(full_dataset) - val_size
|
| 117 |
+
|
| 118 |
+
generator = torch.Generator().manual_seed(42)
|
| 119 |
+
train_dataset, val_dataset = random_split(full_dataset, [train_size, val_size], generator=generator)
|
| 120 |
+
|
| 121 |
+
# Disable augmentation for validation
|
| 122 |
+
val_dataset_no_aug = LIDCFlatDataset(args.data_dir, augment=False)
|
| 123 |
+
val_indices = val_dataset.indices
|
| 124 |
+
val_dataset_final = torch.utils.data.Subset(val_dataset_no_aug, val_indices)
|
| 125 |
+
|
| 126 |
+
train_loader = DataLoader(train_dataset, batch_size=args.batch_size,
|
| 127 |
+
shuffle=True, num_workers=args.num_workers, pin_memory=True)
|
| 128 |
+
val_loader = DataLoader(val_dataset_final, batch_size=args.batch_size,
|
| 129 |
+
shuffle=False, num_workers=args.num_workers, pin_memory=True)
|
| 130 |
+
|
| 131 |
+
print(f"Train: {train_size}, Val: {val_size}")
|
| 132 |
+
|
| 133 |
+
# Create model
|
| 134 |
+
model = get_model(args.model, in_channels=1, num_classes=1)
|
| 135 |
+
model = model.to(device)
|
| 136 |
+
|
| 137 |
+
# Count parameters
|
| 138 |
+
n_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 139 |
+
print(f"Model: {args.model}, Parameters: {n_params:,}")
|
| 140 |
+
|
| 141 |
+
# Loss, optimizer, scheduler
|
| 142 |
+
criterion = DiceBCELoss()
|
| 143 |
+
optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=1e-4)
|
| 144 |
+
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs)
|
| 145 |
+
|
| 146 |
+
# Training loop
|
| 147 |
+
best_val_dice = 0
|
| 148 |
+
patience_counter = 0
|
| 149 |
+
|
| 150 |
+
checkpoint_path = os.path.join(args.checkpoint_dir, f"{args.model}_best.pth")
|
| 151 |
+
|
| 152 |
+
print(f"\nTraining {args.model} for {args.epochs} epochs...")
|
| 153 |
+
print("-" * 70)
|
| 154 |
+
|
| 155 |
+
start_time = time.time()
|
| 156 |
+
|
| 157 |
+
for epoch in range(1, args.epochs + 1):
|
| 158 |
+
train_loss, train_dice = train_one_epoch(model, train_loader, optimizer, criterion, device)
|
| 159 |
+
val_loss, val_dice = validate(model, val_loader, criterion, device)
|
| 160 |
+
scheduler.step()
|
| 161 |
+
|
| 162 |
+
# Save best model
|
| 163 |
+
if val_dice > best_val_dice:
|
| 164 |
+
best_val_dice = val_dice
|
| 165 |
+
patience_counter = 0
|
| 166 |
+
torch.save({
|
| 167 |
+
"epoch": epoch,
|
| 168 |
+
"model_state_dict": model.state_dict(),
|
| 169 |
+
"optimizer_state_dict": optimizer.state_dict(),
|
| 170 |
+
"val_dice": val_dice,
|
| 171 |
+
"model_name": args.model,
|
| 172 |
+
}, checkpoint_path)
|
| 173 |
+
else:
|
| 174 |
+
patience_counter += 1
|
| 175 |
+
|
| 176 |
+
# Print progress every 5 epochs or at start/end
|
| 177 |
+
if epoch % 5 == 0 or epoch == 1 or epoch == args.epochs:
|
| 178 |
+
elapsed = time.time() - start_time
|
| 179 |
+
lr = optimizer.param_groups[0]['lr']
|
| 180 |
+
print(f"Epoch {epoch:3d}/{args.epochs} | "
|
| 181 |
+
f"Train Loss: {train_loss:.4f} Dice: {train_dice:.4f} | "
|
| 182 |
+
f"Val Loss: {val_loss:.4f} Dice: {val_dice:.4f} | "
|
| 183 |
+
f"Best: {best_val_dice:.4f} | "
|
| 184 |
+
f"LR: {lr:.2e} | "
|
| 185 |
+
f"Time: {elapsed:.0f}s")
|
| 186 |
+
|
| 187 |
+
# Early stopping
|
| 188 |
+
if patience_counter >= args.patience:
|
| 189 |
+
print(f"\nEarly stopping at epoch {epoch} (patience={args.patience})")
|
| 190 |
+
break
|
| 191 |
+
|
| 192 |
+
total_time = time.time() - start_time
|
| 193 |
+
print("-" * 70)
|
| 194 |
+
print(f"Training complete! Best val Dice: {best_val_dice:.4f}")
|
| 195 |
+
print(f"Total time: {total_time:.0f}s ({total_time/60:.1f}min)")
|
| 196 |
+
print(f"Checkpoint saved: {checkpoint_path}")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
if __name__ == "__main__":
|
| 200 |
+
main()
|