File size: 4,026 Bytes
232c308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
survivalstandalone/train.py

Run this file directly:
    cd CMTLNet/CMTLNet/survivalstandalone
    python train.py

Step 1 (sanity check): overfits ~10 samples, C-index should climb near 1.0.
Step 2 (real run): proper train/val split, reports val C-index per epoch.
"""

import torch
from torch.utils.data import DataLoader, random_split

from dataset import build_records, SurvivalDataset
from model import SurvivalNet3D
from losses import cox_ph_loss, concordance_index

# ---- EDIT THESE FOR YOUR MACHINE ----
CSV_PATH = "clinicaldata.csv"

USE_PREPROCESSED = True  # False = raw HF download (fast path, step 2)
                           # True  = output of preprocess_ucsf.py (paper-matched, step 6)

RAW_DATA_ROOT = r"D:\jainam\UCSF-PDGM-v5"
PREPROCESSED_DATA_ROOT = r"D:\jainam\UCSF-PDGM-v5-preprocessed"
# ------------------------------------------------


def sanity_check_overfit(model, loader, device, steps=200, lr=1e-3):
    model.train()
    opt = torch.optim.Adam(model.parameters(), lr=lr)
    batch = next(iter(loader))
    x, t, e = batch["image"].to(device), batch["time"].to(device), batch["event"].to(device)

    for step in range(steps):
        opt.zero_grad()
        risk = model(x)
        loss = cox_ph_loss(risk, t, e)
        loss.backward()
        opt.step()
        if step % 20 == 0 or step == steps - 1:
            with torch.no_grad():
                c_idx = concordance_index(risk, t, e)
            print(f"[sanity check] step {step:3d}  loss={loss.item():.4f}  C-index={c_idx:.3f}")


def train_real(model, train_loader, val_loader, device, epochs=30, lr=1e-4):
    opt = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=1e-5)
    scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, mode="max", patience=5, factor=0.5)

    for epoch in range(epochs):
        model.train()
        total_loss = 0.0
        for batch in train_loader:
            x, t, e = batch["image"].to(device), batch["time"].to(device), batch["event"].to(device)
            opt.zero_grad()
            risk = model(x)
            loss = cox_ph_loss(risk, t, e)
            loss.backward()
            opt.step()
            total_loss += loss.item() * x.size(0)

        model.eval()
        risks, times, events = [], [], []
        with torch.no_grad():
            for batch in val_loader:
                x = batch["image"].to(device)
                risks.append(model(x).cpu())
                times.append(batch["time"])
                events.append(batch["event"])
        risks, times, events = torch.cat(risks), torch.cat(times), torch.cat(events)
        val_c = concordance_index(risks, times, events)
        scheduler.step(val_c)
        print(f"epoch {epoch+1:3d}  train_loss={total_loss/len(train_loader.dataset):.4f}  val_C-index={val_c:.3f}")


if __name__ == "__main__":
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    print("device:", device)

    records = build_records(
        CSV_PATH,
        PREPROCESSED_DATA_ROOT if USE_PREPROCESSED else RAW_DATA_ROOT,
        modality="T1c",
        preprocessed=USE_PREPROCESSED,
    )
    if len(records) < 10:
        print("Too few usable records — check DATA_ROOT path / file naming and rerun.")
        raise SystemExit

    dataset = SurvivalDataset(records)

    # ---- Step 1: overfit sanity check ----
    model = SurvivalNet3D(in_channels=1).to(device)
    tiny_loader = DataLoader(dataset, batch_size=min(10, len(dataset)), shuffle=True)
    sanity_check_overfit(model, tiny_loader, device)

    # ---- Step 2: real train/val ----
    n_val = max(1, int(0.2 * len(dataset)))
    n_train = len(dataset) - n_val
    train_set, val_set = random_split(dataset, [n_train, n_val])

    train_loader = DataLoader(train_set, batch_size=8, shuffle=True, num_workers=4)
    val_loader = DataLoader(val_set, batch_size=8, shuffle=False, num_workers=4)

    model = SurvivalNet3D(in_channels=1).to(device)  # fresh weights for the real run
    train_real(model, train_loader, val_loader, device)