-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
executable file
·364 lines (305 loc) · 12 KB
/
main.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
from __future__ import division
from __future__ import print_function
from operator import itemgetter
from itertools import combinations
import time
import os
from collections import ChainMap
import tensorflow as tf
import numpy as np
import networkx as nx
import scipy.sparse as sp
from sklearn import metrics
from collections import defaultdict
from decagon.deep.optimizer import DecagonOptimizer
from decagon.deep.model import DecagonModel
from decagon.deep.minibatch import EdgeMinibatchIterator
from decagon.utility import rank_metrics, preprocessing
import dgl
# Train on CPU (hide GPU) due to memory constraints
# os.environ['CUDA_VISIBLE_DEVICES'] = "0"
# Train on GPU
os.environ["CUDA_DEVICE_ORDER"] = 'PCI_BUS_ID'
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
np.random.seed(0)
###########################################################
#
# Functions
#
###########################################################
def get_accuracy_scores(edges_pos, edges_neg, edge_type):
feed_dict.update({placeholders['dropout']: 0})
feed_dict.update({placeholders['batch_edge_type_idx']: minibatch.edge_type2idx[edge_type]})
feed_dict.update({placeholders['batch_row_edge_type']: edge_type[0]})
feed_dict.update({placeholders['batch_col_edge_type']: edge_type[1]})
rec = sess.run(opt.predictions, feed_dict=feed_dict)
def sigmoid(x):
return 1. / (1 + np.exp(-x))
# Predict on test set of edges
preds = []
actual = []
predicted = []
edge_ind = 0
for u, v in edges_pos[edge_type[:2]][edge_type[2]]:
score = sigmoid(rec[u, v])
preds.append(score)
assert adj_mats_orig[edge_type[:2]][edge_type[2]][u,v] == 1, 'Problem 1'
actual.append(edge_ind)
predicted.append((score, edge_ind))
edge_ind += 1
preds_neg = []
for u, v in edges_neg[edge_type[:2]][edge_type[2]]:
score = sigmoid(rec[u, v])
preds_neg.append(score)
assert adj_mats_orig[edge_type[:2]][edge_type[2]][u,v] == 0, 'Problem 0'
predicted.append((score, edge_ind))
edge_ind += 1
preds_all = np.hstack([preds, preds_neg])
preds_all = np.nan_to_num(preds_all)
labels_all = np.hstack([np.ones(len(preds)), np.zeros(len(preds_neg))])
predicted = list(zip(*sorted(predicted, reverse=True, key=itemgetter(0))))[1]
roc_sc = metrics.roc_auc_score(labels_all, preds_all)
aupr_sc = metrics.average_precision_score(labels_all, preds_all)
apk_sc = rank_metrics.apk(actual, predicted, k=50)
return roc_sc, aupr_sc, apk_sc
def construct_placeholders(edge_types):
placeholders = {
'batch': tf.placeholder(tf.int32, name='batch'),
'batch_edge_type_idx': tf.placeholder(tf.int32, shape=(), name='batch_edge_type_idx'),
'batch_row_edge_type': tf.placeholder(tf.int32, shape=(), name='batch_row_edge_type'),
'batch_col_edge_type': tf.placeholder(tf.int32, shape=(), name='batch_col_edge_type'),
'degrees': tf.placeholder(tf.int32),
'dropout': tf.placeholder_with_default(0., shape=()),
}
placeholders.update({
'adj_mats_%d,%d,%d' % (i, j, k): tf.sparse_placeholder(tf.float32)
for i, j in edge_types for k in range(edge_types[i,j])})
placeholders.update({
'feat_%d' % i: tf.sparse_placeholder(tf.float32)
for i, _ in edge_types})
return placeholders
###########################################################
#
# Load and preprocess data (This is a dummy toy example!)
#
###########################################################
####
# The following code uses artificially generated and very small networks.
# Expect less than excellent performance as these random networks do not have any interesting structure.
# The purpose of main.py is to show how to use the code!
#
# All preprocessed datasets used in the drug combination study are at: http://snap.stanford.edu/decagon:
# (1) Download datasets from http://snap.stanford.edu/decagon to your local machine.
# (2) Replace dummy toy datasets used here with the actual datasets you just downloaded.
# (3) Train & test the model.
####
def load_ppi(fname='./polypharmacy/bio-decagon-ppi.csv'):
fin = open(fname)
print ('Reading: %s' % fname)
fin.readline()
edges= []
for line in fin:
gene_id1, gene_id2= line.strip().split(',')
edges +=[[gene_id1,gene_id2]]
nodes = set([u for e in edges for u in e])
print ('Edges: %d' % len(edges))
print ('Nodes: %d' % len(nodes))
net = nx.Graph()
net.add_edges_from(edges)
net.remove_nodes_from(nx.isolates(net))
net.remove_edges_from(net.selfloop_edges())
# node2idx = {node: i for i, node in enumerate(net.nodes())}
return net, len(edges),len(nodes)
def load_combo_se(fname='./polypharmacy/bio-decagon-combo.csv'):
combo2stitch = {}
combo2se = defaultdict(set)
se2name = {}
drug={}
fin = open(fname)
print ('Reading: %s' % fname)
fin.readline()
for line in fin:
stitch_id1, stitch_id2, se, se_name = line.strip().split(',')
combo = stitch_id1 + '_' + stitch_id2
combo2stitch[combo] = [stitch_id1, stitch_id2]
combo2se[combo].add(se)
se2name[se] = se_name
drug[stitch_id1,se_name ,stitch_id2]= [(0,0)]
fin.close()
g = dgl.heterograph(drug)
n_interactions = sum([len(v) for v in combo2se.values()])
print ('Drug combinations: %d Side effects: %d' % (len(combo2stitch), len(se2name)))
print ('Drug-drug interactions: %d' % (n_interactions))
return g,se2name
# Returns dictionary from Stitch ID to list of drug targets
def load_targets(fname='./polypharmacy/bio-decagon-targets.csv'):
stitch2proteins = defaultdict(set)
fin = open(fname)
fin.readline()
for line in fin:
stitch_id, gene = line.strip().split(',')
stitch2proteins[stitch_id].add(gene)
return stitch2proteins
net, gene_edges,n_genes = load_ppi()
drug2gene = load_targets()
drug,sename= load_combo_se()
val_test_size = 0.05
n_drugs = 645
n_drugdrug_rel_types = 1317
gene_net = net
gene_adj = nx.adjacency_matrix(gene_net)
gene_degrees = np.array(gene_adj.sum(axis=0)).squeeze()
# gene_drug_adj = sp.csr_matrix((10 * np.random.randn(n_genes, n_drugs) > 15).astype(int))
# drug_gene_adj = gene_drug_adj.transpose(copy=True)
gene_drug_adj = drug2gene.adjacency_matrix()
drug_gene_adj = gene_drug_adj.transpose(copy=True)
drug_drug_adj_list = []
# tmp = np.dot(drug_gene_adj, gene_drug_adj)
for key, value in sename.items():
mat = drug.adjacency_matrix(etype=value)
if sum(sum(mat[i]) for i in range(len(mat))) > 500:
drug_drug_adj_list.append(sp.csr_matrix(mat))
drug_degrees_list = [np.array(drug_adj.sum(axis=0)).squeeze() for drug_adj in drug_drug_adj_list]
# data representation
adj_mats_orig = {
(0, 0): [gene_adj, gene_adj.transpose(copy=True)],
(0, 1): [gene_drug_adj],
(1, 0): [drug_gene_adj],
(1, 1): drug_drug_adj_list + [x.transpose(copy=True) for x in drug_drug_adj_list],
}
degrees = {
0: [gene_degrees, gene_degrees],
1: drug_degrees_list + drug_degrees_list,
}
# featureless (genes)
gene_feat = sp.identity(n_genes)
gene_nonzero_feat, gene_num_feat = gene_feat.shape
gene_feat = preprocessing.sparse_to_tuple(gene_feat.tocoo())
# features (drugs)
drug_feat = sp.identity(n_drugs)
drug_nonzero_feat, drug_num_feat = drug_feat.shape
drug_feat = preprocessing.sparse_to_tuple(drug_feat.tocoo())
# data representation
num_feat = {
0: gene_num_feat,
1: drug_num_feat,
}
nonzero_feat = {
0: gene_nonzero_feat,
1: drug_nonzero_feat,
}
feat = {
0: gene_feat,
1: drug_feat,
}
edge_type2dim = {k: [adj.shape for adj in adjs] for k, adjs in adj_mats_orig.items()}
edge_type2decoder = {
(0, 0): 'bilinear',
(0, 1): 'bilinear',
(1, 0): 'bilinear',
(1, 1): 'dedicom',
}
edge_types = {k: len(v) for k, v in adj_mats_orig.items()}
num_edge_types = sum(edge_types.values())
print("Edge types:", "%d" % num_edge_types)
###########################################################
#
# Settings and placeholders
#
###########################################################
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_integer('neg_sample_size', 1, 'Negative sample size.')
flags.DEFINE_float('learning_rate', 0.001, 'Initial learning rate.')
flags.DEFINE_integer('epochs', 50, 'Number of epochs to train.')
flags.DEFINE_integer('hidden1', 64, 'Number of units in hidden layer 1.')
flags.DEFINE_integer('hidden2', 32, 'Number of units in hidden layer 2.')
flags.DEFINE_float('weight_decay', 0, 'Weight for L2 loss on embedding matrix.')
flags.DEFINE_float('dropout', 0.1, 'Dropout rate (1 - keep probability).')
flags.DEFINE_float('max_margin', 0.1, 'Max margin parameter in hinge loss')
flags.DEFINE_integer('batch_size', 512, 'minibatch size.')
flags.DEFINE_boolean('bias', True, 'Bias term.')
# Important -- Do not evaluate/print validation performance every iteration as it can take
# substantial amount of time
PRINT_PROGRESS_EVERY = 150
print("Defining placeholders")
placeholders = construct_placeholders(edge_types)
###########################################################
#
# Create minibatch iterator, model and optimizer
#
###########################################################
print("Create minibatch iterator")
minibatch = EdgeMinibatchIterator(
adj_mats=adj_mats_orig,
feat=feat,
edge_types=edge_types,
batch_size=FLAGS.batch_size,
val_test_size=val_test_size
)
print("Create model")
model = DecagonModel(
placeholders=placeholders,
num_feat=num_feat,
nonzero_feat=nonzero_feat,
edge_types=edge_types,
decoders=edge_type2decoder,
)
print("Create optimizer")
with tf.name_scope('optimizer'):
opt = DecagonOptimizer(
embeddings=model.embeddings,
latent_inters=model.latent_inters,
latent_varies=model.latent_varies,
degrees=degrees,
edge_types=edge_types,
edge_type2dim=edge_type2dim,
placeholders=placeholders,
batch_size=FLAGS.batch_size,
margin=FLAGS.max_margin
)
print("Initialize session")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
feed_dict = {}
###########################################################
#
# Train model
#
###########################################################
print("Train model")
for epoch in range(FLAGS.epochs):
minibatch.shuffle()
itr = 0
while not minibatch.end():
# Construct feed dictionary
feed_dict = minibatch.next_minibatch_feed_dict(placeholders=placeholders)
feed_dict = minibatch.update_feed_dict(
feed_dict=feed_dict,
dropout=FLAGS.dropout,
placeholders=placeholders)
t = time.time()
# Training step: run single weight update
outs = sess.run([opt.opt_op, opt.cost, opt.batch_edge_type_idx], feed_dict=feed_dict)
train_cost = outs[1]
batch_edge_type = outs[2]
if itr % PRINT_PROGRESS_EVERY == 0:
val_auc, val_auprc, val_apk = get_accuracy_scores(
minibatch.val_edges, minibatch.val_edges_false,
minibatch.idx2edge_type[minibatch.current_edge_type_idx])
print("Epoch:", "%04d" % (epoch + 1), "Iter:", "%04d" % (itr + 1), "Edge:", "%04d" % batch_edge_type,
"train_loss=", "{:.5f}".format(train_cost),
"val_roc=", "{:.5f}".format(val_auc), "val_auprc=", "{:.5f}".format(val_auprc),
"val_apk=", "{:.5f}".format(val_apk), "time=", "{:.5f}".format(time.time() - t))
itr += 1
print("Optimization finished!")
for et in range(num_edge_types):
roc_score, auprc_score, apk_score = get_accuracy_scores(
minibatch.test_edges, minibatch.test_edges_false, minibatch.idx2edge_type[et])
print("Edge type=", "[%02d, %02d, %02d]" % minibatch.idx2edge_type[et])
print("Edge type:", "%04d" % et, "Test AUROC score", "{:.5f}".format(roc_score))
print("Edge type:", "%04d" % et, "Test AUPRC score", "{:.5f}".format(auprc_score))
print("Edge type:", "%04d" % et, "Test AP@k score", "{:.5f}".format(apk_score))
print()