Datasets:
File size: 11,816 Bytes
7a37175 | 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 | """
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() |