-
Notifications
You must be signed in to change notification settings - Fork 2
/
deepgozero.py
452 lines (383 loc) · 16.3 KB
/
deepgozero.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
import click as ck
import pandas as pd
from utils import Ontology
import torch as th
import numpy as np
from torch import nn
from torch.nn import functional as F
from torch import optim
from torch.optim.lr_scheduler import MultiStepLR
from sklearn.metrics import roc_curve, auc, matthews_corrcoef
import copy
from torch.utils.data import DataLoader, IterableDataset, TensorDataset
from itertools import cycle
import math
from aminoacids import to_onehot, MAXLEN
from multiprocessing import Pool, get_context
from torch_utils import FastTensorDataLoader
from evaluate import test
from tqdm import tqdm
from functools import partial
import wandb
@ck.command()
@ck.option(
'--data-root', '-dr', default='data-sim',
help='Data folder')
@ck.option(
'--ont', '-ont', default='mf',
help='Prediction model')
@ck.option(
'--batch-size', '-bs', default=37,
help='Batch size for training')
@ck.option(
'--epochs', '-ep', default=30,
help='Training epochs')
@ck.option(
'--load', '-ld', is_flag=True, help='Load Model?')
@ck.option(
'--device', '-d', default='cuda:0',
help='Device')
def main(data_root, ont, batch_size, epochs, load, device):
combine = False
run = 0
wandb_logger = wandb.init(project="final-dgpu-similarity-based", name = ont, group="dgzero")
model_name = f"deepgozero_{ont}"
go_file = f'{data_root}/go-plus.norm'
model_file = f'{data_root}/{ont}/deepgozero.th'
terms_file = f'{data_root}/{ont}/terms.pkl'
out_file = f'{data_root}/{ont}/predictions_deepgozero_{ont}_{run}.pkl'
go = Ontology(f'{data_root}/go-basic.obo', with_rels=True)
loss_func = nn.BCELoss()
iprs_dict, terms_dict, train_data, valid_data, test_data, test_df = load_data(data_root, ont, terms_file)
n_terms = len(terms_dict)
n_iprs = len(iprs_dict)
nf1, nf2, nf3, nf4, relations, zero_classes = load_normal_forms(
go_file, terms_dict)
n_rels = len(relations)
n_zeros = len(zero_classes)
normal_forms = nf1, nf2, nf3, nf4
nf1 = th.LongTensor(nf1).to(device)
nf2 = th.LongTensor(nf2).to(device)
nf3 = th.LongTensor(nf3).to(device)
nf4 = th.LongTensor(nf4).to(device)
normal_forms = nf1, nf2, nf3, nf4
net = DGELModel(n_iprs, n_terms, n_zeros, n_rels, device).to(device)
print(net)
train_features, train_labels = train_data
valid_features, valid_labels = valid_data
test_features, test_labels = test_data
train_loader = FastTensorDataLoader(
*train_data, batch_size=batch_size, shuffle=True)
valid_loader = FastTensorDataLoader(
*valid_data, batch_size=batch_size, shuffle=False)
test_loader = FastTensorDataLoader(
*test_data, batch_size=batch_size, shuffle=False)
valid_labels = valid_labels.detach().cpu().numpy()
test_labels = test_labels.detach().cpu().numpy()
optimizer = th.optim.Adam(net.parameters(), lr=5e-4)
scheduler = MultiStepLR(optimizer, milestones=[5, 20], gamma=0.1)
best_loss = 10000.0
if not load:
print('Training the model')
for epoch in range(epochs):
net.train()
train_loss = 0
train_elloss = 0
lmbda = 0.1
train_steps = int(math.ceil(len(train_labels) / batch_size))
with ck.progressbar(length=train_steps, show_pos=True) as bar:
for batch_features, batch_labels in train_loader:
bar.update(1)
batch_features = batch_features.to(device)
batch_labels = batch_labels.to(device)
logits = net(batch_features)
loss = F.binary_cross_entropy(logits, batch_labels)
el_loss = net.el_loss(normal_forms)
total_loss = loss + el_loss
train_loss += loss.detach().item()
train_elloss = el_loss.detach().item()
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
train_loss /= train_steps
print('Validation')
net.eval()
with th.no_grad():
valid_steps = int(math.ceil(len(valid_labels) / batch_size))
valid_loss = 0
preds = []
with ck.progressbar(length=valid_steps, show_pos=True) as bar:
for batch_features, batch_labels in valid_loader:
bar.update(1)
batch_features = batch_features.to(device)
batch_labels = batch_labels.to(device)
logits = net(batch_features)
batch_loss = F.binary_cross_entropy(logits, batch_labels)
valid_loss += batch_loss.detach().item()
preds = np.append(preds, logits.detach().cpu().numpy())
valid_loss /= valid_steps
roc_auc = compute_roc(valid_labels, preds)
print(f'Epoch {epoch}: Loss - {train_loss}, EL Loss: {train_elloss}, Valid loss - {valid_loss}, AUC - {roc_auc}')
print('EL Loss', train_elloss)
if valid_loss < best_loss:
best_loss = valid_loss
print('Saving model')
th.save(net.state_dict(), model_file)
scheduler.step()
# Loading best model
print('Loading the best model')
net.load_state_dict(th.load(model_file))
net.eval()
with th.no_grad():
test_steps = int(math.ceil(len(test_labels) / batch_size))
test_loss = 0
preds = []
with ck.progressbar(length=test_steps, show_pos=True) as bar:
for batch_features, batch_labels in test_loader:
bar.update(1)
batch_features = batch_features.to(device)
batch_labels = batch_labels.to(device)
logits = net(batch_features)
batch_loss = F.binary_cross_entropy(logits, batch_labels)
test_loss += batch_loss.detach().cpu().item()
preds = np.append(preds, logits.detach().cpu().numpy())
test_loss /= test_steps
preds = preds.reshape(-1, n_terms)
roc_auc = compute_roc(test_labels, preds)
print(f'Test Loss - {test_loss}, AUC - {roc_auc}')
preds = list(preds)
indexed_preds = [(i, preds[i]) for i in range(len(preds))]
with get_context("spawn").Pool(30) as p:
results = []
with tqdm(total=len(preds)) as pbar:
for output in p.imap_unordered(partial(propagate_annots, go=go, terms_dict=terms_dict), indexed_preds, chunksize=200):
results.append(output)
pbar.update()
unordered_preds = [pred for pred in results]
ordered_preds = sorted(unordered_preds, key=lambda x: x[0])
preds = [pred[1] for pred in ordered_preds]
test_df['preds'] = preds
test_df.to_pickle(out_file)
test(data_root, ont, model_name, run, combine, 0.5, False, wandb_logger)
def propagate_annots(preds, go, terms_dict):
idx, preds = preds
prop_annots = {}
for go_id, j in terms_dict.items():
score = preds[j]
for sup_go in go.get_ancestors(go_id):
if sup_go in prop_annots:
prop_annots[sup_go] = max(prop_annots[sup_go], score)
else:
prop_annots[sup_go] = score
for go_id, score in prop_annots.items():
if go_id in terms_dict:
preds[terms_dict[go_id]] = score
return idx, preds
def compute_roc(labels, preds):
# Compute ROC curve and ROC area for each class
fpr, tpr, _ = roc_curve(labels.flatten(), preds.flatten())
roc_auc = auc(fpr, tpr)
return roc_auc
def load_normal_forms(go_file, terms_dict):
nf1 = []
nf2 = []
nf3 = []
nf4 = []
relations = {}
zclasses = {}
def get_index(go_id):
if go_id in terms_dict:
index = terms_dict[go_id]
elif go_id in zclasses:
index = zclasses[go_id]
else:
zclasses[go_id] = len(terms_dict) + len(zclasses)
index = zclasses[go_id]
return index
def get_rel_index(rel_id):
if rel_id not in relations:
relations[rel_id] = len(relations)
return relations[rel_id]
with open(go_file) as f:
for line in f:
line = line.strip().replace('_', ':')
if line.find('SubClassOf') == -1:
continue
left, right = line.split(' SubClassOf ')
# C SubClassOf D
if len(left) == 10 and len(right) == 10:
go1, go2 = left, right
nf1.append((get_index(go1), get_index(go2)))
elif left.find('and') != -1: # C and D SubClassOf E
go1, go2 = left.split(' and ')
go3 = right
nf2.append((get_index(go1), get_index(go2), get_index(go3)))
elif left.find('some') != -1: # R some C SubClassOf D
rel, go1 = left.split(' some ')
go2 = right
nf3.append((get_rel_index(rel), get_index(go1), get_index(go2)))
elif right.find('some') != -1: # C SubClassOf R some D
go1 = left
rel, go2 = right.split(' some ')
nf4.append((get_index(go1), get_rel_index(rel), get_index(go2)))
return nf1, nf2, nf3, nf4, relations, zclasses
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x):
return x + self.fn(x)
class MLPBlock(nn.Module):
def __init__(self, in_features, out_features, bias=True, layer_norm=True, dropout=0.1, activation=nn.ReLU):
super().__init__()
self.linear = nn.Linear(in_features, out_features, bias)
self.activation = activation()
self.layer_norm = nn.BatchNorm1d(out_features) if layer_norm else None
self.dropout = nn.Dropout(dropout) if dropout else None
def forward(self, x):
x = self.activation(self.linear(x))
if self.layer_norm:
x = self.layer_norm(x)
if self.dropout:
x = self.dropout(x)
return x
class DGELModel(nn.Module):
def __init__(self, nb_iprs, nb_gos, nb_zero_gos, nb_rels, device, hidden_dim=1024, embed_dim=1024, margin=0.1):
super().__init__()
self.nb_gos = nb_gos
self.nb_zero_gos = nb_zero_gos
input_length = nb_iprs
net = []
net.append(MLPBlock(input_length, hidden_dim))
net.append(Residual(MLPBlock(hidden_dim, hidden_dim)))
self.net = nn.Sequential(*net)
# ELEmbeddings
self.embed_dim = embed_dim
self.hasFuncIndex = th.LongTensor([nb_rels]).to(device)
self.go_embed = nn.Embedding(nb_gos + nb_zero_gos, embed_dim)
self.go_norm = nn.BatchNorm1d(embed_dim)
k = math.sqrt(1 / embed_dim)
nn.init.uniform_(self.go_embed.weight, -k, k)
self.go_rad = nn.Embedding(nb_gos + nb_zero_gos, 1)
nn.init.uniform_(self.go_rad.weight, -k, k)
# self.go_embed.weight.requires_grad = False
# self.go_rad.weight.requires_grad = False
self.rel_embed = nn.Embedding(nb_rels + 1, embed_dim)
nn.init.uniform_(self.rel_embed.weight, -k, k)
self.all_gos = th.arange(self.nb_gos).to(device)
self.margin = margin
def forward(self, features):
x = self.net(features)
go_embed = self.go_embed(self.all_gos)
hasFunc = self.rel_embed(self.hasFuncIndex)
hasFuncGO = go_embed + hasFunc
go_rad = th.abs(self.go_rad(self.all_gos).view(1, -1))
x = th.matmul(x, hasFuncGO.T) + go_rad
logits = th.sigmoid(x)
return logits
def predict_zero(self, features, data):
x = self.net(features)
go_embed = self.go_embed(data)
hasFunc = self.rel_embed(self.hasFuncIndex)
hasFuncGO = go_embed + hasFunc
go_rad = th.abs(self.go_rad(data).view(1, -1))
x = th.matmul(x, hasFuncGO.T) + go_rad
logits = th.sigmoid(x)
return logits
def el_loss(self, go_normal_forms):
nf1, nf2, nf3, nf4 = go_normal_forms
nf1_loss = self.nf1_loss(nf1)
nf2_loss = self.nf2_loss(nf2)
nf3_loss = self.nf3_loss(nf3)
nf4_loss = self.nf4_loss(nf4)
# print()
# print(nf1_loss.detach().item(),
# nf2_loss.detach().item(),
# nf3_loss.detach().item(),
# nf4_loss.detach().item())
return nf1_loss + nf3_loss + nf4_loss + nf2_loss
def class_dist(self, data):
c = self.go_norm(self.go_embed(data[:, 0]))
d = self.go_norm(self.go_embed(data[:, 1]))
rc = th.abs(self.go_rad(data[:, 0]))
rd = th.abs(self.go_rad(data[:, 1]))
dist = th.linalg.norm(c - d, dim=1, keepdim=True) + rc - rd
return dist
def nf1_loss(self, data):
pos_dist = self.class_dist(data)
loss = th.mean(th.relu(pos_dist - self.margin))
return loss
def nf2_loss(self, data):
c = self.go_norm(self.go_embed(data[:, 0]))
d = self.go_norm(self.go_embed(data[:, 1]))
e = self.go_norm(self.go_embed(data[:, 2]))
rc = th.abs(self.go_rad(data[:, 0]))
rd = th.abs(self.go_rad(data[:, 1]))
re = th.abs(self.go_rad(data[:, 2]))
sr = rc + rd
dst = th.linalg.norm(c - d, dim=1, keepdim=True)
dst2 = th.linalg.norm(e - c, dim=1, keepdim=True)
dst3 = th.linalg.norm(e - d, dim=1, keepdim=True)
loss = th.mean(th.relu(dst - sr - self.margin)
+ th.relu(dst2 - rc - self.margin)
+ th.relu(dst3 - rd - self.margin))
return loss
def nf3_loss(self, data):
# R some C subClassOf D
n = data.shape[0]
# rS = self.rel_space(data[:, 0])
# rS = rS.reshape(-1, self.embed_dim, self.embed_dim)
rE = self.rel_embed(data[:, 0])
c = self.go_norm(self.go_embed(data[:, 1]))
d = self.go_norm(self.go_embed(data[:, 2]))
# c = th.matmul(c, rS).reshape(n, -1)
# d = th.matmul(d, rS).reshape(n, -1)
rc = th.abs(self.go_rad(data[:, 1]))
rd = th.abs(self.go_rad(data[:, 2]))
rSomeC = c + rE
euc = th.linalg.norm(rSomeC - d, dim=1, keepdim=True)
loss = th.mean(th.relu(euc + rc - rd - self.margin))
return loss
def nf4_loss(self, data):
# C subClassOf R some D
n = data.shape[0]
c = self.go_norm(self.go_embed(data[:, 0]))
rE = self.rel_embed(data[:, 1])
d = self.go_norm(self.go_embed(data[:, 2]))
rc = th.abs(self.go_rad(data[:, 1]))
rd = th.abs(self.go_rad(data[:, 2]))
sr = rc + rd
# c should intersect with d + r
rSomeD = d + rE
dst = th.linalg.norm(c - rSomeD, dim=1, keepdim=True)
loss = th.mean(th.relu(dst - sr - self.margin))
return loss
def load_data(data_root, ont, terms_file):
terms_df = pd.read_pickle(terms_file)
terms = terms_df['gos'].values.flatten()
terms_dict = {v: i for i, v in enumerate(terms)}
print('Terms', len(terms))
ipr_df = pd.read_pickle(f'{data_root}/{ont}/interpros.pkl')
iprs = ipr_df['interpros'].values
iprs_dict = {v:k for k, v in enumerate(iprs)}
train_df = pd.read_pickle(f'{data_root}/{ont}/train_data.pkl')
valid_df = pd.read_pickle(f'{data_root}/{ont}/valid_data.pkl')
test_df = pd.read_pickle(f'{data_root}/{ont}/test_data.pkl')
train_data = get_data(train_df, iprs_dict, terms_dict)
valid_data = get_data(valid_df, iprs_dict, terms_dict)
test_data = get_data(test_df, iprs_dict, terms_dict)
return iprs_dict, terms_dict, train_data, valid_data, test_data, test_df
def get_data(df, iprs_dict, terms_dict):
data = th.zeros((len(df), len(iprs_dict)), dtype=th.float32)
labels = th.zeros((len(df), len(terms_dict)), dtype=th.float32)
for i, row in enumerate(df.itertuples()):
for ipr in row.interpros:
if ipr in iprs_dict:
data[i, iprs_dict[ipr]] = 1
for go_id in row.prop_annotations: # prop_annotations for full model
if go_id in terms_dict:
g_id = terms_dict[go_id]
labels[i, g_id] = 1
return data, labels
if __name__ == '__main__':
main()