training.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. from model import ModelCT # Import your custom model architecture
  2. import os # For file and directory operations
  3. import numpy as np # For numerical operations and data shuffling
  4. import torch # For PyTorch operations
  5. from torch.utils.data import DataLoader # To load data in batches
  6. from datareader import DataReader # Custom data reader for loading processed data
  7. from sklearn.metrics import roc_auc_score # To compute ROC AUC metric
  8. import time # For time tracking during training
  9. ############################################################################
  10. # DATA PREPARATION #
  11. ############################################################################
  12. # Define the main folder containing all processed data
  13. main_path_to_data = "/data/PSUF_naloge/5-naloga/processed/" # Change this path as needed
  14. # Get file lists from the subdirectories 'mild' and 'severe'
  15. files_mild = os.listdir(os.path.join(main_path_to_data, "mild"))
  16. files_severe = os.listdir(os.path.join(main_path_to_data, "severe"))
  17. # Extract unique patient IDs from filenames (assumes format: <patientID>_slice_<number>.npy)
  18. patients_mild = {file.split("_slice_")[0] for file in files_mild}
  19. patients_severe = {file.split("_slice_")[0] for file in files_severe}
  20. # Build a list of tuples (file_path, label) for central slice (assumed slice_4)
  21. # Label 0 for 'mild' and 1 for 'severe'
  22. all_central_slices = (
  23. [("mild/" + patient_ID + "_slice_4.npy", 0) for patient_ID in patients_mild] +
  24. [("severe/" + patient_ID + "_slice_4.npy", 1) for patient_ID in patients_severe]
  25. )
  26. # Set a fixed random seed for reproducibility and shuffle the list of samples
  27. np.random.seed(42)
  28. np.random.shuffle(all_central_slices)
  29. # Split data into train (60%), validation (20%), and test (20%) sets
  30. total_samples = len(all_central_slices)
  31. train_info = all_central_slices[: int(0.6 * total_samples)]
  32. valid_info = all_central_slices[int(0.6 * total_samples) : int(0.8 * total_samples)]
  33. test_info = all_central_slices[int(0.8 * total_samples) :]
  34. ############################################################################
  35. # MODEL & HYPERPARAMETERS #
  36. ############################################################################
  37. # Instantiate the model
  38. model = ModelCT()
  39. # Set the device for training (GPU if available, otherwise CPU)
  40. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  41. # Extract hyperparameters for convenience
  42. learning_rate = 0.2e-3 # Base learning rate for the optimizer
  43. weight_decay = 0.0001 # Regularization parameter
  44. total_epoch = 10 # Total number of training epochs
  45. ############################################################################
  46. # DATA LOADER CREATION #
  47. ############################################################################
  48. # Create dataset objects for training and validation using the DataReader
  49. train_dataset = DataReader(main_path_to_data, train_info)
  50. valid_dataset = DataReader(main_path_to_data, valid_info)
  51. # Create DataLoader objects for training and validation
  52. train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True,)
  53. valid_loader = DataLoader(valid_dataset, batch_size=10, shuffle=False)
  54. ############################################################################
  55. # MODEL PREPARATION #
  56. ############################################################################
  57. # Move the model to the selected device (GPU/CPU)
  58. model.to(device)
  59. # Define the loss function (BCEWithLogitsLoss combines sigmoid activation with binary cross-entropy loss)
  60. criterion = torch.nn.BCEWithLogitsLoss()
  61. # Define the optimizer (Adam) with the specified learning rate and weight decay
  62. optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)
  63. ############################################################################
  64. # TRAINING LOOP #
  65. ############################################################################
  66. if __name__ == '__main__': # use this to avoid Broken Pipe Error in torch 1.9
  67. # Initialize the variable to track the best validation AUC
  68. best_auc = -np.inf
  69. # Loop over epochs
  70. for epoch in range(total_epoch):
  71. start_time = time.time() # Start time for the current epoch
  72. print(f"Epoch: {epoch + 1}/{total_epoch}")
  73. running_loss = 0.0 # Initialize the running loss for this epoch
  74. # Set the model to training mode
  75. model.train()
  76. # Iterate over the training data batches
  77. for x, y in train_loader:
  78. # Move data to the correct device
  79. x, y = x.to(device), y.to(device)
  80. # Zero the gradients from the previous iteration
  81. optimizer.zero_grad()
  82. # Forward pass: Compute predictions using the model
  83. y_hat = model(x) # Using model(x) calls the __call__ method
  84. loss = criterion(y_hat, y) # Compute the loss
  85. # Backward pass: Compute gradient of the loss with respect to model parameters
  86. loss.backward()
  87. # Update model weights
  88. optimizer.step()
  89. # Accumulate loss for tracking
  90. running_loss += loss.item()
  91. # Compute average loss for the epoch
  92. avg_loss = running_loss / len(train_loader)
  93. ############################################################################
  94. # VALIDATION LOOP #
  95. ############################################################################
  96. # Prepare to store predictions and ground truth labels
  97. predictions = []
  98. trues = []
  99. # Set the model to evaluation mode (disables dropout, batch norm, etc.)
  100. model.eval()
  101. with torch.no_grad():
  102. # Iterate over the validation data batches
  103. for x, y in valid_loader:
  104. # Move data to the appropriate device
  105. x, y = x.to(device), y.to(device)
  106. # Forward pass to compute predictions
  107. y_hat = model(x)
  108. # Apply sigmoid to convert logits to probabilities
  109. probs = torch.sigmoid(y_hat)
  110. # Flatten and collect predictions and true labels
  111. predictions.extend(probs.cpu().numpy().flatten().tolist())
  112. trues.extend(y.cpu().numpy().flatten().tolist())
  113. # Compute ROC AUC for validation set and handle potential errors
  114. auc = roc_auc_score(trues, predictions)
  115. # Print training metrics for the epoch
  116. elapsed_time = time.time() - start_time
  117. print(f"AUC: {auc:.4f}, Avg Loss: {avg_loss:.4f}, Time: {elapsed_time:.2f} sec")
  118. # Save the best model based on validation AUC
  119. if auc > best_auc:
  120. best_model_path = os.path.join("trained_models/", 'trained_model_weights.pth')
  121. torch.save(model.state_dict(), best_model_path)
  122. best_auc = auc