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.

model.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # model.py
  2. import numpy as np
  3. import torch
  4. import torch.nn as nn
  5. import torch.nn.functional as F
  6. from torch.nn import MultiheadAttention, TransformerEncoder, TransformerEncoderLayer
  7. from typing import Tuple, List
  8. from sklearn.metrics import roc_auc_score, average_precision_score
  9. from utils import torch_corr_x_y, cross_entropy_loss, prototypical_loss
  10. class ConstructAdjMatrix(nn.Module):
  11. """
  12. Constructs normalized adjacency matrices for graph-based operations.
  13. """
  14. def __init__(self, original_adj_mat: torch.Tensor | np.ndarray, device: str = "cpu"):
  15. """
  16. Initialize the adjacency matrix construction module.
  17. Args:
  18. original_adj_mat (torch.Tensor | np.ndarray): Input adjacency matrix.
  19. device (str): Device to run computations on (e.g., 'cuda:0' or 'cpu').
  20. """
  21. super().__init__()
  22. self.device = device
  23. # Convert to tensor if input is NumPy array
  24. if isinstance(original_adj_mat, np.ndarray):
  25. original_adj_mat = torch.from_numpy(original_adj_mat).float()
  26. self.adj = original_adj_mat.to(device)
  27. def forward(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
  28. """
  29. Compute normalized adjacency matrices for cells and drugs.
  30. Returns:
  31. Tuple of aggregated and self-loop adjacency matrices for cells and drugs.
  32. """
  33. with torch.no_grad():
  34. # Degree normalization for cells and drugs
  35. d_x = torch.diag(torch.pow(torch.sum(self.adj, dim=1) + 1, -0.5))
  36. d_y = torch.diag(torch.pow(torch.sum(self.adj, dim=0) + 1, -0.5))
  37. # Aggregated Laplacian matrices
  38. agg_cell_lp = torch.mm(torch.mm(d_x, self.adj), d_y)
  39. agg_drug_lp = torch.mm(torch.mm(d_y, self.adj.T), d_x)
  40. # Self-loop matrices
  41. self_cell_lp = torch.diag(torch.add(torch.pow(torch.sum(self.adj, dim=1) + 1, -1), 1))
  42. self_drug_lp = torch.diag(torch.add(torch.pow(torch.sum(self.adj, dim=0) + 1, -1), 1))
  43. return (
  44. agg_cell_lp.to(self.device),
  45. agg_drug_lp.to(self.device),
  46. self_cell_lp.to(self.device),
  47. self_drug_lp.to(self.device)
  48. )
  49. class LoadFeature(nn.Module):
  50. """
  51. Loads and processes cell expression and drug fingerprint features.
  52. """
  53. def __init__(self, cell_exprs: np.ndarray, drug_fingerprints: List[np.ndarray], device: str = "cpu"):
  54. """
  55. Initialize the feature loading module.
  56. Args:
  57. cell_exprs (np.ndarray): Cell expression data.
  58. drug_fingerprints (List[np.ndarray]): List of drug fingerprint matrices.
  59. device (str): Device to run computations on (e.g., 'cuda:0' or 'cpu').
  60. """
  61. super().__init__()
  62. self.device = device
  63. # Convert inputs to tensors
  64. self.cell_exprs = torch.from_numpy(cell_exprs).float().to(device)
  65. self.drug_fingerprints = [torch.from_numpy(fp).float().to(device) for fp in drug_fingerprints]
  66. # Drug projection layers
  67. self.drug_proj = nn.ModuleList([
  68. nn.Sequential(
  69. nn.Linear(fp.shape[1], 512),
  70. nn.BatchNorm1d(512),
  71. nn.GELU(),
  72. nn.Dropout(0.5)
  73. ).to(device) for fp in drug_fingerprints
  74. ])
  75. # Transformer encoder for drug features
  76. self.transformer = TransformerEncoder(
  77. TransformerEncoderLayer(
  78. d_model=512,
  79. nhead=8,
  80. dim_feedforward=2048,
  81. batch_first=True
  82. ),
  83. num_layers=1
  84. ).to(device)
  85. # Normalization layers
  86. self.cell_norm = nn.LayerNorm(cell_exprs.shape[1]).to(device)
  87. self.drug_norm = nn.LayerNorm(512).to(device)
  88. # Cell encoder
  89. self.cell_encoder = nn.Sequential(
  90. nn.Linear(cell_exprs.shape[1], 1024),
  91. nn.BatchNorm1d(1024),
  92. nn.GELU(),
  93. nn.Dropout(0.5),
  94. nn.Linear(1024, 512)
  95. ).to(device)
  96. def forward(self) -> Tuple[torch.Tensor, torch.Tensor]:
  97. """
  98. Process cell and drug features.
  99. Returns:
  100. Tuple of encoded cell features and drug features.
  101. """
  102. # Process cell features
  103. cell_feat = self.cell_norm(self.cell_exprs) # [num_cells x num_features]
  104. cell_encoded = self.cell_encoder(cell_feat) # [num_cells x 512]
  105. # Process drug features
  106. projected = [proj(fp) for proj, fp in zip(self.drug_proj, self.drug_fingerprints)] # List of [num_samples x 512]
  107. stacked = torch.stack(projected, dim=1) # [num_samples x num_drugs x 512]
  108. drug_feat = self.transformer(stacked) # [num_samples x num_drugs x 512]
  109. drug_feat = self.drug_norm(drug_feat.mean(dim=1)) # [num_samples x 512]
  110. return cell_encoded, drug_feat
  111. class GEncoder(nn.Module):
  112. """
  113. Graph encoder for combining cell and drug features with graph structure.
  114. """
  115. def __init__(
  116. self,
  117. agg_c_lp: torch.Tensor,
  118. agg_d_lp: torch.Tensor,
  119. self_c_lp: torch.Tensor,
  120. self_d_lp: torch.Tensor,
  121. device: str = "cpu"
  122. ):
  123. """
  124. Initialize the graph encoder.
  125. Args:
  126. agg_c_lp (torch.Tensor): Aggregated cell Laplacian matrix.
  127. agg_d_lp (torch.Tensor): Aggregated drug Laplacian matrix.
  128. self_c_lp (torch.Tensor): Self-loop cell Laplacian matrix.
  129. self_d_lp (torch.Tensor): Self-loop drug Laplacian matrix.
  130. device (str): Device to run computations on (e.g., 'cuda:0' or 'cpu').
  131. """
  132. super().__init__()
  133. self.agg_c_lp = agg_c_lp
  134. self.agg_d_lp = agg_d_lp
  135. self.self_c_lp = self_c_lp
  136. self.self_d_lp = self_d_lp
  137. self.device = device
  138. # Cell and drug encoders
  139. self.cell_encoder = nn.Sequential(
  140. nn.Linear(512, 1024),
  141. nn.BatchNorm1d(1024),
  142. nn.GELU(),
  143. nn.Dropout(0.5),
  144. nn.Linear(1024, 512)
  145. ).to(device)
  146. self.drug_encoder = nn.Sequential(
  147. nn.Linear(512, 1024),
  148. nn.BatchNorm1d(1024),
  149. nn.GELU(),
  150. nn.Dropout(0.5),
  151. nn.Linear(1024, 512)
  152. ).to(device)
  153. # Attention mechanism
  154. self.attention = MultiheadAttention(embed_dim=512, num_heads=8, batch_first=True).to(device)
  155. self.residual = nn.Linear(512, 512).to(device)
  156. # Final fully connected layer
  157. self.fc = nn.Sequential(
  158. nn.Linear(1024, 512),
  159. nn.BatchNorm1d(512),
  160. nn.GELU(),
  161. nn.Dropout(0.5)
  162. ).to(device)
  163. def forward(self, cell_f: torch.Tensor, drug_f: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
  164. """
  165. Encode cell and drug features using graph structure and attention.
  166. Args:
  167. cell_f (torch.Tensor): Cell features.
  168. drug_f (torch.Tensor): Drug features.
  169. Returns:
  170. Tuple of encoded cell and drug embeddings.
  171. """
  172. # Aggregate features using Laplacian matrices
  173. cell_agg = torch.mm(self.agg_c_lp, drug_f) + torch.mm(self.self_c_lp, cell_f) # [num_cells x 512]
  174. drug_agg = torch.mm(self.agg_d_lp, cell_f) + torch.mm(self.self_d_lp, drug_f) # [num_drugs x 512]
  175. # Encode aggregated features
  176. cell_fc = self.cell_encoder(cell_agg) # [num_cells x 512]
  177. drug_fc = self.drug_encoder(drug_agg) # [num_drugs x 512]
  178. # Apply attention mechanism
  179. attn_output, _ = self.attention(
  180. query=cell_fc.unsqueeze(0), # [1 x num_cells x 512]
  181. key=drug_fc.unsqueeze(0), # [1 x num_drugs x 512]
  182. value=drug_fc.unsqueeze(0) # [1 x num_drugs x 512]
  183. )
  184. attn_output = attn_output.squeeze(0) # [num_cells x 512]
  185. cell_emb = cell_fc + self.residual(attn_output) # [num_cells x 512]
  186. # Apply final activation
  187. cell_emb = F.gelu(cell_emb) # [num_cells x 512]
  188. drug_emb = F.gelu(drug_fc) # [num_drugs x 512]
  189. return cell_emb, drug_emb
  190. class GDecoder(nn.Module):
  191. """
  192. Decoder to predict interaction scores between cells and drugs.
  193. """
  194. def __init__(self, emb_dim: int, gamma: float):
  195. """
  196. Initialize the decoder.
  197. Args:
  198. emb_dim (int): Embedding dimension (default: 512).
  199. gamma (float): Scaling factor for output scores.
  200. """
  201. super().__init__()
  202. self.gamma = gamma
  203. self.decoder = nn.Sequential(
  204. nn.Linear(2 * emb_dim, 1024),
  205. nn.BatchNorm1d(1024),
  206. nn.GELU(),
  207. nn.Dropout(0.2),
  208. nn.Linear(1024, 1)
  209. )
  210. self.corr_weight = nn.Parameter(torch.tensor(0.5))
  211. def forward(self, cell_emb: torch.Tensor, drug_emb: torch.Tensor) -> torch.Tensor:
  212. """
  213. Predict interaction scores between cells and drugs.
  214. Args:
  215. cell_emb (torch.Tensor): Cell embeddings.
  216. drug_emb (torch.Tensor): Drug embeddings.
  217. Returns:
  218. torch.Tensor: Predicted interaction scores.
  219. """
  220. # Expand dimensions for pairwise combination
  221. cell_exp = cell_emb.unsqueeze(1).repeat(1, drug_emb.size(0), 1) # [num_cells x num_drugs x 512]
  222. drug_exp = drug_emb.unsqueeze(0).repeat(cell_emb.size(0), 1, 1) # [num_cells x num_drugs x 512]
  223. combined = torch.cat([cell_exp, drug_exp], dim=-1) # [num_cells x num_drugs x 1024]
  224. # Decode combined features
  225. scores = self.decoder(combined.view(-1, 2 * cell_emb.size(1))).view(cell_emb.size(0), drug_emb.size(0)) # [num_cells x num_drugs]
  226. corr = torch_corr_x_y(cell_emb, drug_emb) # [num_cells x num_drugs]
  227. # Combine scores and correlation with learned weighting
  228. return torch.sigmoid(self.gamma * (self.corr_weight * scores + (1 - self.corr_weight) * corr))
  229. class DeepTraCDR(nn.Module):
  230. """
  231. DeepTraCDR model for predicting cell-drug interactions.
  232. """
  233. def __init__(
  234. self,
  235. adj_mat: torch.Tensor | np.ndarray,
  236. cell_exprs: np.ndarray,
  237. drug_finger: List[np.ndarray],
  238. layer_size: List[int],
  239. gamma: float,
  240. device: str = "cpu"
  241. ):
  242. """
  243. Initialize the DeepTraCDR model.
  244. Args:
  245. adj_mat (torch.Tensor | np.ndarray): Adjacency matrix.
  246. cell_exprs (np.ndarray): Cell expression data.
  247. drug_finger (List[np.ndarray]): List of drug fingerprint matrices.
  248. layer_size (List[int]): Sizes of hidden layers.
  249. gamma (float): Scaling factor for decoder.
  250. device (str): Device to run computations on (e.g., 'cuda:0' or 'cpu').
  251. """
  252. super().__init__()
  253. self.device = device
  254. if isinstance(adj_mat, np.ndarray):
  255. adj_mat = torch.from_numpy(adj_mat).float()
  256. self.adj_mat = adj_mat.to(device)
  257. # Initialize submodules
  258. self.construct_adj = ConstructAdjMatrix(self.adj_mat, device=device)
  259. self.load_feat = LoadFeature(cell_exprs, drug_finger, device=device)
  260. # Compute fixed adjacency matrices
  261. agg_c, agg_d, self_c, self_d = self.construct_adj()
  262. # Initialize encoder and decoder
  263. self.encoder = GEncoder(agg_c, agg_d, self_c, self_d, device=device).to(device)
  264. self.decoder = GDecoder(emb_dim=512, gamma=gamma).to(device)
  265. def forward(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
  266. """
  267. Forward pass of the DeepTraCDR model.
  268. Returns:
  269. Tuple of predicted scores, cell embeddings, and drug embeddings.
  270. """
  271. cell_f, drug_f = self.load_feat()
  272. cell_emb, drug_emb = self.encoder(cell_f, drug_f)
  273. scores = self.decoder(cell_emb, drug_emb)
  274. return scores, cell_emb, drug_emb
  275. class Optimizer:
  276. """
  277. Optimizer for training the DeepTraCDR model with early stopping and evaluation.
  278. """
  279. def __init__(
  280. self,
  281. model: DeepTraCDR,
  282. train_data: torch.Tensor,
  283. test_data: torch.Tensor,
  284. test_mask: torch.Tensor,
  285. train_mask: torch.Tensor,
  286. adj_matrix: torch.Tensor | np.ndarray,
  287. evaluate_fun,
  288. lr: float = 0.001,
  289. wd: float = 1e-05,
  290. epochs: int = 200,
  291. test_freq: int = 20,
  292. patience: int = 200,
  293. device: str = "cpu"
  294. ):
  295. """
  296. Initialize the optimizer.
  297. Args:
  298. model (DeepTraCDR): The DeepTraCDR model to train.
  299. train_data (torch.Tensor): Training data.
  300. test_data (torch.Tensor): Test data.
  301. test_mask (torch.Tensor): Mask for test data.
  302. train_mask (torch.Tensor): Mask for training data.
  303. adj_matrix (torch.Tensor | np.ndarray): Adjacency matrix.
  304. evaluate_fun: Function to evaluate model performance.
  305. lr (float): Learning rate.
  306. wd (float): Weight decay.
  307. epochs (int): Number of training epochs.
  308. test_freq (int): Frequency of evaluation.
  309. patience (int): Patience for early stopping.
  310. device (str): Device to run computations on (e.g., 'cuda:0' or 'cpu').
  311. """
  312. self.model = model.to(device)
  313. self.train_data = train_data.float().to(device)
  314. self.test_data = test_data.float().to(device)
  315. self.train_mask = train_mask.to(device)
  316. self.test_mask_bool = test_mask.to(device).bool()
  317. self.device = device
  318. # Convert adjacency matrix to tensor
  319. if isinstance(adj_matrix, np.ndarray):
  320. adj_matrix = torch.from_numpy(adj_matrix).float()
  321. self.adj_matrix = adj_matrix.to(device)
  322. self.evaluate_fun = evaluate_fun
  323. self.optimizer = torch.optim.Adam(self.model.parameters(), lr=lr, weight_decay=wd)
  324. self.epochs = epochs
  325. self.test_freq = test_freq
  326. self.patience = patience
  327. self.best_auc = 0.0
  328. self.best_auprc = 0.0
  329. self.best_weights = None
  330. self.counter = 0
  331. def train(self) -> Tuple[np.ndarray, np.ndarray, float, float]:
  332. """
  333. Train the DeepTraCDR model and evaluate performance.
  334. Returns:
  335. Tuple of true labels, predicted scores, best AUC, and best AUPRC.
  336. """
  337. true_data = torch.masked_select(self.test_data, self.test_mask_bool).cpu().numpy()
  338. for epoch in range(self.epochs):
  339. self.model.train()
  340. # Forward pass and compute loss
  341. pred_train, cell_emb, drug_emb = self.model()
  342. ce_loss = cross_entropy_loss(self.train_data, pred_train, self.train_mask)
  343. proto_loss = prototypical_loss(cell_emb, drug_emb, self.adj_matrix)
  344. total_loss = 0.7 * ce_loss + 0.3 * proto_loss
  345. # Backward pass
  346. self.optimizer.zero_grad()
  347. total_loss.backward()
  348. self.optimizer.step()
  349. # Evaluate model
  350. self.model.eval()
  351. with torch.no_grad():
  352. # Training metrics
  353. train_pred, _, _ = self.model()
  354. train_pred_masked = torch.masked_select(train_pred, self.train_mask).cpu().numpy()
  355. train_true_data = torch.masked_select(self.train_data, self.train_mask).cpu().numpy()
  356. try:
  357. train_auc = roc_auc_score(train_true_data, train_pred_masked)
  358. train_auprc = average_precision_score(train_true_data, train_pred_masked)
  359. except ValueError:
  360. train_auc, train_auprc = 0.0, 0.0
  361. # Test metrics
  362. pred_eval, _, _ = self.model()
  363. pred_masked = torch.masked_select(pred_eval, self.test_mask_bool).cpu().numpy()
  364. try:
  365. auc = roc_auc_score(true_data, pred_masked)
  366. auprc = average_precision_score(true_data, pred_masked)
  367. except ValueError:
  368. auc, auprc = 0.0, 0.0
  369. # Update best metrics and weights
  370. if auc > self.best_auc:
  371. self.best_auc = auc
  372. self.best_auprc = auprc
  373. self.best_weights = self.model.state_dict().copy()
  374. self.counter = 0
  375. else:
  376. self.counter += 1
  377. # Log progress
  378. if epoch % self.test_freq == 0 or epoch == self.epochs - 1:
  379. print(f"Epoch {epoch}: Loss={total_loss.item():.4f}, "
  380. f"Train AUC={train_auc:.4f}, Train AUPRC={train_auprc:.4f}, "
  381. f"Test AUC={auc:.4f}, Test AUPRC={auprc:.4f}")
  382. # Early stopping
  383. if self.counter >= self.patience:
  384. print(f"\nEarly stopping at epoch {epoch}: No AUC improvement for {self.patience} epochs.")
  385. break
  386. # Load best weights
  387. if self.best_weights is not None:
  388. self.model.load_state_dict(self.best_weights)
  389. # Final evaluation
  390. self.model.eval()
  391. with torch.no_grad():
  392. final_pred, _, _ = self.model()
  393. final_pred_masked = torch.masked_select(final_pred, self.test_mask_bool).cpu().numpy()
  394. best_auc = roc_auc_score(true_data, final_pred_masked)
  395. best_auprc = average_precision_score(true_data, final_pred_masked)
  396. print("\nBest Metrics (Test Data):")
  397. print(f"AUC: {best_auc:.4f}")
  398. print(f"AUPRC: {best_auprc:.4f}")
  399. return true_data, final_pred_masked, best_auc, best_auprc