DeepTraCDR: Prediction Cancer Drug Response using multimodal deep learning with Transformers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.py 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # main.py
  2. import argparse
  3. import numpy as np
  4. import torch
  5. from sklearn.metrics import roc_auc_score, average_precision_score
  6. from typing import Dict, List, Tuple
  7. from model import DeepTraCDR, Optimizer
  8. from utils import evaluate_auc
  9. from data_sampler import ExterSampler
  10. from data_loader import load_data
  11. from torch.optim.lr_scheduler import OneCycleLR
  12. def parse_arguments() -> argparse.Namespace:
  13. """
  14. Parse command-line arguments for the DeepTraCDR model training pipeline.
  15. Returns:
  16. argparse.Namespace: Parsed arguments.
  17. """
  18. parser = argparse.ArgumentParser(description="DeepTraCDR Advanced: Graph-based Neural Network for Drug Response Prediction")
  19. parser.add_argument('--device', type=str, default="cuda:0" if torch.cuda.is_available() else "cpu",
  20. help="Device to run the model on (cuda:0 or cpu)")
  21. parser.add_argument('--data', type=str, default='tcga', help="Dataset to use (e.g., tcga)")
  22. parser.add_argument('--wd', type=float, default=1e-7, help="Weight decay for optimizer")
  23. parser.add_argument('--layer_size', nargs='+', type=int, default=[512],
  24. help="List of layer sizes for the GCN model")
  25. parser.add_argument('--gamma', type=float, default=20.0, help="Gamma parameter for model")
  26. parser.add_argument('--epochs', type=int, default=1000, help="Number of training epochs")
  27. parser.add_argument('--test_freq', type=int, default=50, help="Frequency of evaluation during training")
  28. parser.add_argument('--lr', type=float, default=0.0005, help="Learning rate for optimizer")
  29. return parser.parse_args()
  30. def initialize_data(args: argparse.Namespace) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, int, argparse.Namespace]:
  31. """
  32. Load and preprocess the dataset for training.
  33. Args:
  34. args (argparse.Namespace): Command-line arguments.
  35. Returns:
  36. Tuple containing adjacency matrix, drug fingerprints, expression data, null mask, positive sample count, and args.
  37. """
  38. try:
  39. full_adj, drug_fingerprints, exprs, null_mask, pos_num, args = load_data(args)
  40. print(f"Data loaded successfully:")
  41. print(f" - Adjacency matrix shape: {full_adj.shape}")
  42. print(f" - Expression data shape: {exprs.shape}")
  43. print(f" - Null mask shape: {null_mask.shape}")
  44. print(f" - Drug fingerprints shape: {drug_fingerprints.shape}")
  45. return full_adj, drug_fingerprints, exprs, null_mask, pos_num, args
  46. except Exception as e:
  47. raise RuntimeError(f"Failed to load data: {str(e)}")
  48. def convert_to_tensor(data: np.ndarray, device: str) -> torch.Tensor:
  49. """
  50. Convert a NumPy array to a PyTorch tensor and move it to the specified device.
  51. Args:
  52. data (np.ndarray): Input NumPy array.
  53. device (str): Target device (e.g., 'cuda:0' or 'cpu').
  54. Returns:
  55. torch.Tensor: Tensor on the specified device.
  56. """
  57. if isinstance(data, np.ndarray):
  58. return torch.from_numpy(data).float().to(device)
  59. return data.float().to(device)
  60. def train_single_fold(
  61. fold_idx: int,
  62. full_adj: torch.Tensor,
  63. exprs: torch.Tensor,
  64. drug_fingerprints: torch.Tensor,
  65. null_mask: torch.Tensor,
  66. pos_num: int,
  67. args: argparse.Namespace
  68. ) -> Tuple[float, float]:
  69. """
  70. Train the DeepTraCDR model for a single fold and return evaluation metrics.
  71. Args:
  72. fold_idx (int): Current fold index.
  73. full_adj (torch.Tensor): Adjacency matrix.
  74. exprs (torch.Tensor): Gene expression data.
  75. drug_fingerprints (torch.Tensor): Drug fingerprint data.
  76. null_mask (torch.Tensor): Null mask for sampling.
  77. pos_num (int): Number of positive samples.
  78. args (argparse.Namespace): Command-line arguments.
  79. Returns:
  80. Tuple[float, float]: Best AUC and AUPRC for the fold.
  81. """
  82. # Define train/test split
  83. train_index = np.arange(pos_num)
  84. test_index = np.arange(full_adj.shape[0] - pos_num) + pos_num
  85. # Initialize sampler
  86. sampler = ExterSampler(full_adj, null_mask, train_index, test_index)
  87. # Initialize model
  88. model = DeepTraCDR(
  89. adj_mat=full_adj,
  90. cell_exprs=exprs,
  91. drug_finger=drug_fingerprints,
  92. layer_size=args.layer_size,
  93. gamma=args.gamma,
  94. device=args.device
  95. )
  96. # Initialize optimizer
  97. optimizer = Optimizer(
  98. model=model,
  99. train_data=sampler.train_data,
  100. test_data=sampler.test_data,
  101. test_mask=sampler.test_mask,
  102. train_mask=sampler.train_mask,
  103. adj_matrix=full_adj,
  104. evaluate_fun=evaluate_auc,
  105. lr=args.lr,
  106. wd=args.wd,
  107. epochs=args.epochs,
  108. test_freq=args.test_freq,
  109. device=args.device
  110. )
  111. # Train model and collect metrics
  112. _, _, best_auc, best_auprc = optimizer.train()
  113. print(f"Fold {fold_idx + 1}: AUC={best_auc:.4f}, AUPRC={best_auprc:.4f}")
  114. return best_auc, best_auprc
  115. def summarize_metrics(metrics: Dict[str, List[float]]) -> None:
  116. """
  117. Summarize metrics across all folds by computing mean and standard deviation.
  118. Args:
  119. metrics (Dict[str, List[float]]): Dictionary of metrics (e.g., {'auc': [...], 'auprc': [...]})
  120. """
  121. print("\nFinal Average Metrics:")
  122. for metric, values in metrics.items():
  123. mean_val = np.mean(values)
  124. std_val = np.std(values)
  125. print(f"{metric.upper()}: {mean_val:.4f} ± {std_val:.4f}")
  126. def main():
  127. """
  128. Main function to orchestrate the DeepTraCDR training and evaluation pipeline.
  129. """
  130. # Set precision for matrix multiplications
  131. torch.set_float32_matmul_precision('high')
  132. # Parse arguments
  133. args = parse_arguments()
  134. # Load and preprocess data
  135. full_adj, drug_fingerprints, exprs, null_mask, pos_num, args = initialize_data(args)
  136. # Convert adjacency matrix to tensor
  137. full_adj = convert_to_tensor(full_adj, args.device)
  138. # Initialize metrics storage
  139. metrics = {'auc': [], 'auprc': []}
  140. n_folds = 25
  141. # Perform k-fold cross-validation
  142. for fold_idx in range(n_folds):
  143. best_auc, best_auprc = train_single_fold(
  144. fold_idx, full_adj, exprs, drug_fingerprints, null_mask, pos_num, args
  145. )
  146. metrics['auc'].append(best_auc)
  147. metrics['auprc'].append(best_auprc)
  148. # Summarize results
  149. summarize_metrics(metrics)
  150. if __name__ == "__main__":
  151. try:
  152. main()
  153. except Exception as e:
  154. print(f"Error occurred: {str(e)}")
  155. raise