S-OH / scripts /baseline_resnet18.py
ivanpodd's picture
soh (#4)
8ed1de7
Raw
History Blame
11.8 kB
"""
Example ML/AI Use Case: ResNet18 Classifier for Disease Detection
Demonstrates:
- Data loading and preprocessing
- Temporal split application
- Model definition (ResNet18 fine-tuned)
- Training loop with early stopping
- Evaluation (ROC AUC)
"""
import os
import json
import numpy as np
import pandas as pd
from pathlib import Path
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import PolynomialFeatures
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, models
# ============================================
# CONFIGURATION
# ============================================
METADATA_PATH = Path("../metadata.csv")
DATA_DIR = Path("../data")
MANIFEST_PATH = DATA_DIR / "manifest.json"
TARGET_DISEASE = 'Z00' # Healthy controls
TEST_WEEKS = {9, 10, 11} # Weeks 9-11 for testing
EPOCHS = 20
BATCH_SIZE = 16
LEARNING_RATE = 1e-4 # Lower learning rate for fine-tuning
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# ============================================
# MODEL DEFINITION
# ============================================
class ResNet18Classifier(nn.Module):
"""
ResNet18 fine-tuned for binary classification on polynomial image representations.
Input is resized to 224x224 to match ImageNet pretraining dimensions.
"""
def __init__(self, num_classes=2):
super().__init__()
# Load pretrained ResNet18
self.resnet = models.resnet18(weights=models.ResNet18_Weights.IMAGENET1K_V1)
# Replace the final fully connected layer
in_features = self.resnet.fc.in_features
self.resnet.fc = nn.Linear(in_features, num_classes)
def forward(self, x):
# x is (B, 1, H, W) where H=374, W=337
# ResNet18 expects 3-channel input (RGB). Repeat the single channel 3 times.
x = x.repeat(1, 3, 1, 1) # (B, 3, H, W)
# Resize to 224x224 (ResNet18 input size)
x = F.interpolate(x, size=(224, 224), mode='bilinear', align_corners=False)
return self.resnet(x)
# ============================================
# DATASET CLASS
# ============================================
class CustomDataset(Dataset):
def __init__(self, data, labels, transform=None):
self.data = data
self.labels = labels
self.transform = transform
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
sample = self.data[idx]
label = int(self.labels[idx])
if self.transform:
sample = self.transform(sample)
return sample, label
# ============================================
# DATA LOADING FUNCTIONS
# ============================================
def load_patient_data(patient_id):
"""Load a single patient's JSON file."""
with open(MANIFEST_PATH, 'r') as f:
manifest = json.load(f)
entry = next((e for e in manifest['files'] if e['patient_id'] == patient_id), None)
if entry is None:
return None
file_path = DATA_DIR / entry['file']
with open(file_path, 'r') as f:
return json.load(f)
def preprocess_signal(signal):
"""
Preprocess a single signal:
1. Wavelet smoothing (db4, level 4)
2. Min-max scaling
"""
import pywt
from sklearn.preprocessing import minmax_scale
coeffs = pywt.wavedec(signal, 'db4', level=4)
coeffs[1:] = [np.zeros_like(c) for c in coeffs[1:]]
smoothed = pywt.waverec(coeffs, 'db4')
return minmax_scale(smoothed, axis=0)
def load_and_preprocess_data():
"""Load full dataset and preprocess eNose signals."""
metadata = pd.read_csv(METADATA_PATH)
X = []
y = []
patient_ids = []
# Stable channels (based on manufacturer recommendation)
channels = ['R2', 'R3', 'R5', 'R8', 'R11', 'R12', 'R13', 'R14', 'R15', 'R16', 'R17']
poly = PolynomialFeatures(degree=3, include_bias=False, interaction_only=False)
with open(MANIFEST_PATH, 'r') as f:
manifest = json.load(f)
# Fit polynomial features on dummy data to get feature dimensions
dummy = np.random.random((11, 337))
poly.fit(dummy.T)
for entry in manifest['files']:
patient_id = entry['patient_id']
row = metadata[metadata['Patient_id'] == patient_id].iloc[0]
# Binary label: 1 if target disease, else 0
label = 1 if row['Diagnosis'] == TARGET_DISEASE else 0
patient_data = load_patient_data(patient_id)
if patient_data is None:
continue
# Extract raw signals
raw_signals = []
for sensor in patient_data['sensors']:
if sensor['id'] == 'enose':
for channel in sensor['channels']:
if channel['id'] in channels:
raw_signals.append(np.array(channel['samples']))
break
if len(raw_signals) == 0:
continue
# Preprocess each channel
processed_signals = []
for sig in raw_signals:
# Clip to active measurement period (20-450 samples)
clipped = sig[20:450]
processed = preprocess_signal(clipped)
processed_signals.append(processed)
# Stack signals: shape (channels, time_steps)
processed_signals = np.array(processed_signals)[:11, :337]
if processed_signals.shape[0] * processed_signals.shape[1] == 11 * 337:
poly_features = poly.transform(processed_signals.T).T
extended_features = np.vstack([processed_signals, poly_features])
X.append(extended_features)
y.append(label)
patient_ids.append(patient_id)
y = np.array(y)
patient_ids = np.array(patient_ids)
X = np.array(X, dtype=np.float32)
print(f" Data shape: {X.shape}")
print(f" Labels: {np.bincount(y)}")
return X, y, patient_ids
def get_temporal_split(metadata, patient_ids):
"""Get train/test split based on weeks."""
train_mask = np.zeros(len(patient_ids), dtype=bool)
test_mask = np.zeros(len(patient_ids), dtype=bool)
for i, pid in enumerate(patient_ids):
row = metadata[metadata['Patient_id'] == pid].iloc[0]
week = row['Week']
if week in TEST_WEEKS:
test_mask[i] = True
else:
train_mask[i] = True
return train_mask, test_mask
# ============================================
# TRAINING FUNCTIONS
# ============================================
def roc_auc_score_torch(outputs, labels):
"""Compute ROC AUC from model outputs and labels."""
probs = F.softmax(outputs, dim=1)[:, 1]
return roc_auc_score(labels.cpu().numpy(), probs.detach().cpu().numpy())
def train_epoch(model, loader, optimizer, criterion, device):
"""Train for one epoch."""
model.train()
total_loss = 0.0
total_count = 0
all_outputs = []
all_targets = []
for data, target in loader:
data, target = data.to(device), target.to(device, dtype=torch.long)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
bs = data.size(0)
total_loss += loss.item() * bs
total_count += bs
all_outputs.append(output)
all_targets.append(target)
all_outputs = torch.cat(all_outputs)
all_targets = torch.cat(all_targets)
avg_loss = total_loss / total_count
avg_auc = roc_auc_score_torch(all_outputs, all_targets)
return avg_loss, avg_auc
def validate(model, loader, criterion, device):
"""Validate the model."""
model.eval()
total_loss = 0.0
total_count = 0
all_outputs = []
all_targets = []
with torch.no_grad():
for data, target in loader:
data, target = data.to(device), target.to(device, dtype=torch.long)
output = model(data)
loss = criterion(output, target)
bs = data.size(0)
total_loss += loss.item() * bs
total_count += bs
all_outputs.append(output)
all_targets.append(target)
all_outputs = torch.cat(all_outputs)
all_targets = torch.cat(all_targets)
avg_loss = total_loss / total_count
avg_auc = roc_auc_score_torch(all_outputs, all_targets)
return avg_loss, avg_auc
# ============================================
# MAIN
# ============================================
def main():
print("=" * 60)
print("DISEASE DETECTION WITH RESNET18")
print(f"Target: {TARGET_DISEASE}")
print(f"Test weeks: {TEST_WEEKS}")
print(f"Device: {DEVICE}")
print("=" * 60)
# 1. Load and preprocess data
print("\n1. Loading and preprocessing data...")
X, y, patient_ids = load_and_preprocess_data()
metadata = pd.read_csv(METADATA_PATH)
print(f" Total samples: {len(X)}")
print(f" Positive ({TARGET_DISEASE}): {sum(y)}")
print(f" Negative: {len(y) - sum(y)}")
# 2. Temporal split
print("\n2. Applying temporal split...")
train_mask, test_mask = get_temporal_split(metadata, patient_ids)
print(f" Train samples: {train_mask.sum()}")
print(f" Test samples: {test_mask.sum()}")
X_train = X[train_mask]
y_train = y[train_mask]
X_test = X[test_mask]
y_test = y[test_mask]
# 3. Create datasets and dataloaders
print("\n3. Creating datasets...")
transform = transforms.Compose([
transforms.ToTensor(), # (H,W) -> (1,H,W)
])
train_dataset = CustomDataset(X_train, y_train, transform=transform)
test_dataset = CustomDataset(X_test, y_test, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False)
# 4. Initialize model
print("\n4. Initializing ResNet18...")
model = ResNet18Classifier(num_classes=2).to(DEVICE)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS)
print(f" Model parameters: {sum(p.numel() for p in model.parameters()):,}")
# 5. Training loop
print("\n5. Training...")
best_val_auc = 0.0
for epoch in range(EPOCHS):
train_loss, train_auc = train_epoch(model, train_loader, optimizer, criterion, DEVICE)
val_loss, val_auc = validate(model, test_loader, criterion, DEVICE)
scheduler.step()
if val_auc > best_val_auc:
best_val_auc = val_auc
torch.save(model.state_dict(), 'resnet18_best.pth')
if (epoch + 1) % 5 == 0:
print(f" Epoch {epoch+1:02d}/{EPOCHS}: "
f"Train Loss: {train_loss:.4f}, Train AUC: {train_auc:.4f}, "
f"Val Loss: {val_loss:.4f}, Val AUC: {val_auc:.4f}")
print(f"\n Best validation AUC: {best_val_auc:.4f}")
# 6. Load best model and evaluate
print("\n6. Evaluating best model on test set...")
model.load_state_dict(torch.load('resnet18_best.pth'))
# Full evaluation on test set
model.eval()
all_probs = []
all_targets = []
with torch.no_grad():
for data, target in test_loader:
data = data.to(DEVICE)
output = model(data)
probs = F.softmax(output, dim=1)[:, 1]
all_probs.extend(probs.cpu().numpy())
all_targets.extend(target.numpy())
all_probs = np.array(all_probs)
all_targets = np.array(all_targets)
auc = roc_auc_score(all_targets, all_probs)
print(f"\n ROC AUC: {auc:.4f}")
print("\n✅ Done!")
if __name__ == "__main__":
main()