-
Notifications
You must be signed in to change notification settings - Fork 0
/
drGAT.py
310 lines (248 loc) · 9.1 KB
/
drGAT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""
This is the official implementation of "drGAT: Attention-Guided Gene Assessment
for Drug Response in Drug-Cell-Gene Heterogeneous Network."
Written by inoue0426
If you have any quesionts, feel free to make an issue to https://github.com/inoue0426/drGAT
"""
import random
import subprocess
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch_geometric
from sklearn.metrics import (accuracy_score, confusion_matrix, f1_score,
precision_score, recall_score)
from torch.nn import BatchNorm1d, Dropout, Linear, Module, MSELoss
from torch.nn.functional import relu, sigmoid
from torch_geometric.data import Data
from torch_geometric.nn import GATv2Conv, GraphNorm
from tqdm import tqdm
def get_attention_mat(attention):
"""A function to make attention coefficient tensor to matrix.
attention: attention tensor from Graph Attention layer.
"""
edge_index, attention_weights = [i.detach().cpu() for i in attention]
num_nodes = torch.max(edge_index) + 1
attention_matrix = torch.zeros(
(num_nodes, num_nodes), dtype=attention_weights.dtype
)
attention_matrix[edge_index[0], edge_index[1]] = attention_weights.squeeze().mean()
return attention_matrix
class GAT(Module):
"""A class to generate a drGAT model.
params: contains params for the model
- dropout1: dropout rate for dropout 1
- dropout2: dropout rate for dropout 2
- hidden1: shape for the hidden1
- hidden2: shape for the hidden2
- hidden3: shape for the hidden3
- heads: The number of heads for graph attention
"""
def __init__(self, params):
super(GAT, self).__init__()
self.linear_drug = Linear(params["n_drug"], params["hidden1"])
self.linear_cell = Linear(params["n_cell"], params["hidden1"])
self.linear_gene = Linear(params["n_gene"], params["hidden1"])
self.gat1 = GATv2Conv(
params["hidden1"], params["hidden2"], heads=params["heads"]
)
self.gat2 = GATv2Conv(
params["hidden2"] * params["heads"],
params["hidden3"],
heads=params["heads"],
)
self.dropout1 = Dropout(params["dropout1"])
self.dropout2 = Dropout(params["dropout2"])
self.graph_norm1 = GraphNorm(params["hidden2"] * params["heads"])
self.graph_norm2 = GraphNorm(params["hidden3"] * params["heads"])
self.linear1 = Linear(
params["hidden3"] * params["heads"] + params["hidden3"] * params["heads"], 1
)
def forward(self, drug, cell, gene, edges, idx_drug, idx_cell):
x = torch.concat(
[self.linear_drug(drug), self.linear_cell(cell), self.linear_gene(gene)]
)
x, attention = self.gat1(x, edges, return_attention_weights=True)
all_attention = get_attention_mat(attention)
del attention
x = self.dropout1(relu(self.graph_norm1(x)))
x, attention = self.gat2(x, edges, return_attention_weights=True)
all_attention += get_attention_mat(attention)
del attention
x = self.dropout2(relu(self.graph_norm2(x)))
x = torch.concat(
[
x[idx_drug],
x[idx_cell],
],
1,
)
x = self.linear1(x)
return torch.sigmoid(x), all_attention
def get_model(params, device):
"""
A function to get a model.
params: contains params for the model
device: device to use
"""
model = GAT(params).to(device)
criterion = nn.BCELoss().to(device)
optimizer = getattr(torch.optim, "Adam")(
model.parameters(),
lr=params["lr"],
)
return model, criterion, optimizer
def train(data, params=None, is_sample=False, device=None, is_save=False):
"""
A function to train a model.
data: contains data for training
- x: feature matrix
- adj: adjacency matrix
- train_drug: indices of drug nodes for training
- train_cell: indices of cell nodes for training
- train_labels: labels for training
- val_drug: indices of drug nodes for validation
- val_cell: indices of cell nodes for validation
- val_labels: labels for validation
params: contains params for the model
is_sample: whether to use small epochs for training
device: device to use
is_save: whether to save the best model
"""
if device is None:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using: ", device)
(
drug,
cell,
gene,
edge_index,
train_drug,
train_cell,
val_drug,
val_cell,
train_labels,
val_labels,
) = [x.to(device) if torch.is_tensor(x) else x for x in data]
if not params:
params = {
"dropout1": 0.1,
"dropout2": 0.1,
"n_drug": drug.shape[0],
"n_cell": cell.shape[0],
"n_gene": gene.shape[0],
"hidden1": 256,
"hidden2": 32,
"hidden3": 128,
"epochs": 1500,
"lr": 0.001,
"heads": 5,
}
if is_sample:
params["epochs"] = 5
train_losses = []
train_accs = []
val_losses = []
val_accs = []
model, criterion, optimizer = get_model(params, device)
best_val_acc = 0.0
best_model = None
early_stopping_counter = 0
max_early_stopping = 10
tmp = -1
for epoch in tqdm(range(params["epochs"])):
model.train()
optimizer.zero_grad()
outputs, attention = model(drug, cell, gene, edge_index, train_drug, train_cell)
loss = criterion(outputs.squeeze(), train_labels)
train_losses.append(loss.item())
predict = torch.round(outputs).squeeze()
train_acc = (predict == train_labels).sum().item() / len(predict)
train_accs.append(train_acc)
loss.backward()
optimizer.step()
model.eval()
valid_loss = 0.0
with torch.no_grad():
outputs, _ = model(drug, cell, gene, edge_index, val_drug, val_cell)
loss = criterion(outputs.squeeze(), val_labels)
val_losses.append(loss.item())
predict = torch.round(outputs).squeeze()
val_acc = (predict == val_labels).sum().item() / len(predict)
val_accs.append(val_acc)
if val_acc > best_val_acc:
best_val_acc = val_acc
if is_save:
torch.save(model, "model_{}.pt".format(epoch))
if tmp >= 0:
subprocess.run(["rm", "-rf", f"model_{tmp}.pt"], check=True)
tmp = epoch
early_stopping_counter = 0
else:
early_stopping_counter += 1
if early_stopping_counter >= max_early_stopping:
print(
f"Early stopping at epoch {epoch + 1} because validation accuracy did not improve for {max_early_stopping} epochs."
)
break
if (epoch + 1) % 10 == 0:
print("Epoch: ", epoch + 1)
print("Train Loss: ", train_losses[-1])
print("Val Loss: ", val_losses[-1])
print("Train Accuracy: ", train_accs[-1])
print("Val Accuracy: ", val_accs[-1], "\n")
return model, attention
def print_binary_classification_metrics(y_true, y_pred):
"""
A function to print binary classification metrics.
y_true: true labels
y_pred: predicted labels
"""
if len(y_true) == 1:
return None
accuracy = accuracy_score(y_true, y_pred)
precision = precision_score(y_true, y_pred)
recall = recall_score(y_true, y_pred)
f1 = f1_score(y_true, y_pred)
tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
metrics_data = {
"Accuracy": [accuracy],
"Precision": [precision],
"Recall": [recall],
"F1 Score": [f1],
"True Positive": [tp],
"True Negative": [tn],
"False Positive": [fp],
"False Negative": [fn],
}
metrics_df = pd.DataFrame(metrics_data)
return metrics_df
def eval(model, data, device=None):
"""
A function to evaluate a model.
model: model to evaluate
data: contains data for evaluation
- x: feature matrix
- adj: adjacency matrix
- test_drug: indices of drug nodes for testing
- test_cell: indices of cell nodes for testing
- test_labels: labels for testing
device: device to use
"""
if not device:
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
drug, cell, gene, edge_index, test_drug, test_cell, test_labels = [
x.to(device) if torch.is_tensor(x) else x for x in data
]
model.eval()
testid_loss = 0.0
with torch.no_grad():
outputs, _ = model(drug, cell, gene, edge_index, test_drug, test_cell)
probability = outputs.squeeze()
predict = torch.round(outputs).squeeze()
res = print_binary_classification_metrics(
test_labels.cpu().detach().numpy(), predict.cpu().detach().numpy()
)
return probability, res