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.

DeepTraCDR_model.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import numpy as np
  2. import torch
  3. import torch.nn as nn
  4. import torch.nn.functional as F
  5. from torch.nn import MultiheadAttention, TransformerEncoder, TransformerEncoderLayer
  6. from scipy.stats import pearsonr, spearmanr
  7. from utils import mse_loss, torch_corr_x_y
  8. class ConstructAdjMatrix(nn.Module):
  9. """Constructs adjacency matrices for graph-based operations."""
  10. def __init__(self, original_adj_mat, device="cpu"):
  11. super().__init__()
  12. # Convert numpy array to torch tensor if needed
  13. self.adj = torch.from_numpy(original_adj_mat).float() if isinstance(original_adj_mat, np.ndarray) else original_adj_mat
  14. self.adj = self.adj.to(device)
  15. self.device = device
  16. def forward(self):
  17. """Computes Laplacian matrices for cells and drugs."""
  18. with torch.no_grad():
  19. # Compute degree matrices for normalization
  20. d_x = torch.diag(torch.pow(torch.sum(self.adj, dim=1) + 1, -0.5))
  21. d_y = torch.diag(torch.pow(torch.sum(self.adj, dim=0) + 1, -0.5))
  22. # Compute aggregated Laplacian matrices
  23. agg_cell_lp = torch.mm(torch.mm(d_x, self.adj), d_y)
  24. agg_drug_lp = torch.mm(torch.mm(d_y, self.adj.T), d_x)
  25. # Compute self-loop Laplacian matrices
  26. self_cell_lp = torch.diag(torch.add(torch.pow(torch.sum(self.adj, dim=1) + 1, -1), 1))
  27. self_drug_lp = torch.diag(torch.add(torch.pow(torch.sum(self.adj, dim=0) + 1, -1), 1))
  28. return agg_cell_lp.to(self.device), agg_drug_lp.to(self.device), self_cell_lp.to(self.device), self_drug_lp.to(self.device)
  29. class LoadFeature(nn.Module):
  30. """Loads and processes cell and drug features."""
  31. def __init__(self, cell_exprs, drug_fingerprints, device="cpu"):
  32. super().__init__()
  33. self.device = device
  34. # Convert input data to torch tensors
  35. self.cell_exprs = torch.from_numpy(cell_exprs).float().to(device)
  36. self.drug_fingerprints = [torch.from_numpy(fp).float().to(device) for fp in drug_fingerprints]
  37. # Define projection layers for drug fingerprints
  38. self.drug_proj = nn.ModuleList([
  39. nn.Sequential(
  40. nn.Linear(fp.shape[1], 512),
  41. nn.BatchNorm1d(512),
  42. nn.GELU(),
  43. nn.Dropout(0.3)
  44. ).to(device) for fp in drug_fingerprints
  45. ])
  46. # Initialize transformer encoder for drug features
  47. self.transformer = TransformerEncoder(
  48. TransformerEncoderLayer(d_model=512, nhead=8, dim_feedforward=2048, batch_first=True),
  49. num_layers=3
  50. ).to(device)
  51. # Normalization layers
  52. self.cell_norm = nn.LayerNorm(cell_exprs.shape[1]).to(device)
  53. self.drug_norm = nn.LayerNorm(512).to(device)
  54. # Cell feature encoder
  55. self.cell_encoder = nn.Sequential(
  56. nn.Linear(cell_exprs.shape[1], 1024),
  57. nn.BatchNorm1d(1024),
  58. nn.GELU(),
  59. nn.Dropout(0.3),
  60. nn.Linear(1024, 512)
  61. ).to(device)
  62. def forward(self):
  63. """Processes cell and drug features to generate encoded representations."""
  64. # Normalize and encode cell features
  65. cell_feat = self.cell_norm(self.cell_exprs)
  66. cell_encoded = self.cell_encoder(cell_feat)
  67. # Project and process drug fingerprints
  68. projected = [proj(fp) for proj, fp in zip(self.drug_proj, self.drug_fingerprints)]
  69. stacked = torch.stack(projected, dim=1)
  70. drug_feat = self.transformer(stacked)
  71. drug_feat = self.drug_norm(drug_feat.mean(dim=1))
  72. return cell_encoded, drug_feat
  73. class GEncoder(nn.Module):
  74. """Encodes cell and drug features using graph-based operations."""
  75. def __init__(self, agg_c_lp, agg_d_lp, self_c_lp, self_d_lp, device="cpu"):
  76. super().__init__()
  77. self.agg_c_lp = agg_c_lp
  78. self.agg_d_lp = agg_d_lp
  79. self.self_c_lp = self_c_lp
  80. self.self_d_lp = self_d_lp
  81. self.device = device
  82. # Cell feature encoder
  83. self.cell_encoder = nn.Sequential(
  84. nn.Linear(512, 1024),
  85. nn.BatchNorm1d(1024),
  86. nn.GELU(),
  87. nn.Dropout(0.3),
  88. nn.Linear(1024, 512)
  89. ).to(device)
  90. # Drug feature encoder
  91. self.drug_encoder = nn.Sequential(
  92. nn.Linear(512, 1024),
  93. nn.BatchNorm1d(1024),
  94. nn.GELU(),
  95. nn.Dropout(0.3),
  96. nn.Linear(1024, 512)
  97. ).to(device)
  98. # Attention mechanism and residual connection
  99. self.attention = MultiheadAttention(embed_dim=512, num_heads=8, batch_first=True).to(device)
  100. self.residual = nn.Linear(512, 512).to(device)
  101. self.fc = nn.Sequential(
  102. nn.Linear(1024, 512),
  103. nn.BatchNorm1d(512),
  104. nn.GELU(),
  105. nn.Dropout(0.2)
  106. ).to(device)
  107. def forward(self, cell_f, drug_f):
  108. """Encodes cell and drug features with graph-based attention."""
  109. # Aggregate features using Laplacian matrices
  110. cell_agg = torch.mm(self.agg_c_lp, drug_f) + torch.mm(self.self_c_lp, cell_f)
  111. drug_agg = torch.mm(self.agg_d_lp, cell_f) + torch.mm(self.self_d_lp, drug_f)
  112. # Encode aggregated features
  113. cell_fc = self.cell_encoder(cell_agg)
  114. drug_fc = self.drug_encoder(drug_agg)
  115. # Apply attention mechanism
  116. attn_output, _ = self.attention(
  117. query=cell_fc.unsqueeze(0),
  118. key=drug_fc.unsqueeze(0),
  119. value=drug_fc.unsqueeze(0)
  120. )
  121. attn_output = attn_output.squeeze(0)
  122. cell_emb = cell_fc + self.residual(attn_output)
  123. # Apply final activation
  124. cell_emb = F.gelu(cell_emb)
  125. drug_emb = F.gelu(drug_fc)
  126. return cell_emb, drug_emb
  127. class GDecoder(nn.Module):
  128. """Decodes combined cell and drug embeddings to predict scores."""
  129. def __init__(self, emb_dim, gamma):
  130. super().__init__()
  131. self.gamma = gamma
  132. # Decoder network
  133. self.decoder = nn.Sequential(
  134. nn.Linear(2 * emb_dim, 1024),
  135. nn.BatchNorm1d(1024),
  136. nn.GELU(),
  137. nn.Dropout(0.2),
  138. nn.Linear(1024, 1)
  139. )
  140. # Learnable correlation weight
  141. self.corr_weight = nn.Parameter(torch.tensor(0.5))
  142. def forward(self, cell_emb, drug_emb):
  143. """Generates prediction scores from cell and drug embeddings."""
  144. # Combine cell and drug embeddings
  145. cell_exp = cell_emb.unsqueeze(1).repeat(1, drug_emb.size(0), 1)
  146. drug_exp = drug_emb.unsqueeze(0).repeat(cell_emb.size(0), 1, 1)
  147. combined = torch.cat([cell_exp, drug_exp], dim=-1)
  148. # Decode combined features
  149. scores = self.decoder(combined.view(-1, 2 * cell_emb.size(1))).view(cell_emb.size(0), drug_emb.size(0))
  150. corr = torch_corr_x_y(cell_emb, drug_emb)
  151. # Combine scores and correlation
  152. return self.gamma * (self.corr_weight * scores + (1 - self.corr_weight) * corr)
  153. class DeepTraCDR(nn.Module):
  154. """Graph Convolutional Network for cell-drug interaction prediction."""
  155. def __init__(self, adj_mat, cell_exprs, drug_finger, layer_size, gamma, device="cpu"):
  156. super().__init__()
  157. self.device = device
  158. # Convert adjacency matrix to tensor if needed
  159. self.adj_mat = torch.from_numpy(adj_mat).float().to(device) if isinstance(adj_mat, np.ndarray) else adj_mat.to(device)
  160. # Initialize components
  161. self.construct_adj = ConstructAdjMatrix(self.adj_mat, device=device)
  162. self.load_feat = LoadFeature(cell_exprs, drug_finger, device=device)
  163. # Precompute adjacency matrices
  164. agg_c, agg_d, self_c, self_d = self.construct_adj()
  165. # Initialize encoder and decoder
  166. self.encoder = GEncoder(agg_c, agg_d, self_c, self_d, device=device).to(device)
  167. self.decoder = GDecoder(layer_size[-1], gamma).to(device)
  168. def forward(self):
  169. """Generates predictions and embeddings for cell-drug interactions."""
  170. cell_f, drug_f = self.load_feat()
  171. cell_emb, drug_emb = self.encoder(cell_f, drug_f)
  172. return self.decoder(cell_emb, drug_emb), cell_emb, drug_emb
  173. class Optimizer:
  174. """Handles training and evaluation of the DeepTraCDR model."""
  175. def __init__(self, model, train_data, test_data, test_mask, train_mask, adj_matrix,
  176. lr=0.001, wd=1e-05, epochs=200, test_freq=20, device="cpu", patience=50):
  177. self.model = model.to(device)
  178. self.train_data = train_data.float().to(device)
  179. self.test_data = test_data.float().to(device)
  180. self.train_mask = train_mask.to(device)
  181. self.test_mask = test_mask.to(device).bool()
  182. self.adj_matrix = adj_matrix.to(device)
  183. self.optimizer = torch.optim.Adam(self.model.parameters(), lr=lr, weight_decay=wd)
  184. self.epochs = epochs
  185. self.test_freq = test_freq
  186. self.patience = patience
  187. self.best_rmse = float('inf')
  188. self.epochs_no_improve = 0
  189. self.true_masked_np = torch.masked_select(self.test_data, self.test_mask).cpu().numpy()
  190. def evaluate_metrics(self, pred_tensor):
  191. """Computes RMSE, PCC, and SCC for model evaluation."""
  192. pred_masked_np = torch.masked_select(pred_tensor, self.test_mask).cpu().numpy()
  193. rmse = np.sqrt(np.mean((self.true_masked_np - pred_masked_np)**2))
  194. pcc, _ = pearsonr(self.true_masked_np, pred_masked_np)
  195. scc, _ = spearmanr(self.true_masked_np, pred_masked_np)
  196. return rmse, pcc, scc, pred_masked_np
  197. def train(self):
  198. """Trains the model with early stopping based on RMSE."""
  199. best_rmse = float('inf')
  200. best_pcc = 0.0
  201. best_scc = 0.0
  202. best_pred_np = None
  203. for epoch in range(self.epochs):
  204. self.model.train()
  205. pred, cell_emb, drug_emb = self.model()
  206. # Compute and optimize loss
  207. mse_loss_val = mse_loss(self.train_data, pred, self.train_mask)
  208. total_loss = mse_loss_val
  209. self.optimizer.zero_grad()
  210. total_loss.backward()
  211. self.optimizer.step()
  212. if epoch % self.test_freq == 0:
  213. self.model.eval()
  214. with torch.no_grad():
  215. pred_eval, _, _ = self.model()
  216. rmse, pcc, scc, pred_masked = self.evaluate_metrics(pred_eval)
  217. # Update early stopping criteria
  218. if rmse < self.best_rmse:
  219. self.best_rmse = rmse
  220. self.epochs_no_improve = 0
  221. else:
  222. self.epochs_no_improve += 1
  223. # Track best results
  224. if rmse < best_rmse:
  225. best_rmse = rmse
  226. best_pcc = pcc
  227. best_scc = scc
  228. best_pred_np = pred_masked.copy()
  229. print(f"Epoch {epoch}: Loss = {total_loss.item():.4f}, RMSE = {rmse:.4f}, PCC = {pcc:.4f}, SCC = {scc:.4f}")
  230. # Early stopping
  231. if self.epochs_no_improve >= self.patience:
  232. print(f"Early stopping at epoch {epoch} (no improvement for {self.patience} epochs).")
  233. break
  234. print("\nBest Results:")
  235. print(f"RMSE: {best_rmse:.4f}")
  236. print(f"PCC: {best_pcc:.4f}")
  237. print(f"SCC: {best_scc:.4f}")
  238. return self.true_masked_np, best_pred_np, best_rmse, best_pcc, best_scc