| """ |
| Example ML/AI Use Case: CNN Classifier for Disease Detection |
| Demonstrates: |
| - Data loading and preprocessing |
| - Temporal split application |
| - Model definition (HeightWiseCNN) |
| - Training loop with early stopping |
| - Evaluation (ROC AUC, confusion matrix) |
| """ |
|
|
| import os |
| import json |
| import numpy as np |
| import pandas as pd |
| from pathlib import Path |
| from sklearn.metrics import roc_auc_score, confusion_matrix, classification_report |
| from sklearn.preprocessing import PolynomialFeatures |
| import matplotlib.pyplot as plt |
| import seaborn as sns |
|
|
| 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 |
|
|
| |
| |
| |
|
|
| METADATA_PATH = Path("../metadata.csv") |
| DATA_DIR = Path("../data") |
| MANIFEST_PATH = DATA_DIR / "manifest.json" |
|
|
| TARGET_DISEASE = 'Z00' |
| TEST_WEEKS = {9, 10, 11} |
| EPOCHS = 20 |
| BATCH_SIZE = 16 |
| LEARNING_RATE = 1e-3 |
| DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
|
|
| |
| |
| |
|
|
| class HeightWiseCNN(nn.Module): |
| """ |
| Height-wise CNN for multivariate time series classification. |
| Treats each channel as a separate "height" dimension and applies 2D convolutions |
| across the temporal dimension. |
| """ |
| def __init__(self, num_classes=2, input_height=374, input_width=337): |
| super().__init__() |
| self.conv1 = nn.Conv2d(1, 32, kernel_size=(input_height, 15), padding=(0, 2)) |
| self.pool = nn.MaxPool2d(kernel_size=(1, 2)) |
| self.conv2 = nn.Conv2d(32, 64, kernel_size=(1, 10), padding='same') |
| self.conv3 = nn.Conv2d(64, 128, kernel_size=(1, 20), padding='same') |
| self.head_pool = nn.AdaptiveMaxPool2d((1, 1)) |
| self.dropout = nn.Dropout(0.1) |
| self.fc1 = nn.Linear(128, 256) |
| self.fc2 = nn.Linear(256, num_classes) |
|
|
| def forward(self, x): |
| x = F.relu(self.conv1(x)) |
| x = self.pool(x) |
| x = F.relu(self.conv2(x)) |
| x = self.pool(x) |
| x = F.relu(self.conv3(x)) |
| x = self.head_pool(x) |
| x = x.flatten(1) |
| x = self.dropout(x) |
| x = F.relu(self.fc1(x)) |
| x = self.dropout(x) |
| return self.fc2(x) |
|
|
|
|
| |
| |
| |
|
|
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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 extract_enose_signals(patient_data, channels=None): |
| """Extract eNose signals from patient data.""" |
| if channels is None: |
| channels = [f'R{i}' for i in range(1, 18)] |
|
|
| for sensor in patient_data['sensors']: |
| if sensor['id'] == 'enose': |
| signals = [] |
| for channel in sensor['channels']: |
| if channel['id'] in channels: |
| signals.append(np.array(channel['samples'])) |
| return np.array(signals).T |
|
|
| return None |
|
|
|
|
| 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 = [] |
|
|
| |
| 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) |
|
|
| poly = PolynomialFeatures(degree=3, include_bias=False, interaction_only=False) |
| dummy = np.random.random((11,337)) |
| poly.fit_transform(dummy.T).T |
|
|
| for entry in manifest['files']: |
| patient_id = entry['patient_id'] |
| row = metadata[metadata['Patient_id'] == patient_id].iloc[0] |
|
|
| |
| label = 1 if row['Diagnosis'] == TARGET_DISEASE else 0 |
|
|
| patient_data = load_patient_data(patient_id) |
| if patient_data is None: |
| continue |
|
|
| |
| 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 |
|
|
| |
| processed_signals = [] |
| for sig in raw_signals: |
| |
| clipped = sig[20:450] |
| processed = preprocess_signal(clipped) |
| processed_signals.append(processed) |
|
|
| |
| 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) |
|
|
| 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 |
|
|
|
|
| |
| |
| |
|
|
| 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 |
|
|
|
|
| def main(): |
| print("=" * 60) |
| print("HELTH DETECTION WITH HEIGHT-WISE CNN") |
| print(f"Target: {TARGET_DISEASE}") |
| print(f"Test weeks: {TEST_WEEKS}") |
| print(f"Device: {DEVICE}") |
| print("=" * 60) |
|
|
| |
| 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)}") |
|
|
| |
| 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] |
|
|
| |
| print("\n3. Creating datasets...") |
| transform = transforms.Compose([ |
| transforms.ToTensor(), |
| ]) |
|
|
| 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) |
|
|
| |
| print("\n4. Initializing model...") |
| model = HeightWiseCNN(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()):,}") |
|
|
| |
| 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(), 'cnn_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}") |
|
|
| |
| print("\n6. Evaluating best model on test set...") |
| model.load_state_dict(torch.load('cnn_best.pth')) |
| |
| |
| 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() |