-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
216 lines (155 loc) · 6.24 KB
/
utils.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
from __future__ import print_function
import scipy.sparse as sp
import numpy as np
def csr_zero_rows(csr, rows_to_zero):
"""Set rows given by rows_to_zero in a sparse csr matrix to zero.
NOTE: Inplace operation! Does not return a copy of sparse matrix."""
rows, cols = csr.shape
mask = np.ones((rows,), dtype=np.bool)
mask[rows_to_zero] = False
nnz_per_row = np.diff(csr.indptr)
mask = np.repeat(mask, nnz_per_row)
nnz_per_row[rows_to_zero] = 0
csr.data = csr.data[mask]
csr.indices = csr.indices[mask]
csr.indptr[1:] = np.cumsum(nnz_per_row)
csr.eliminate_zeros()
return csr
def csc_zero_cols(csc, cols_to_zero):
"""Set rows given by cols_to_zero in a sparse csc matrix to zero.
NOTE: Inplace operation! Does not return a copy of sparse matrix."""
rows, cols = csc.shape
mask = np.ones((cols,), dtype=np.bool)
mask[cols_to_zero] = False
nnz_per_row = np.diff(csc.indptr)
mask = np.repeat(mask, nnz_per_row)
nnz_per_row[cols_to_zero] = 0
csc.data = csc.data[mask]
csc.indices = csc.indices[mask]
csc.indptr[1:] = np.cumsum(nnz_per_row)
csc.eliminate_zeros()
return csc
def sp_vec_from_idx_list(idx_list, dim):
"""Create sparse vector of dimensionality dim from a list of indices."""
shape = (dim, 1)
data = np.ones(len(idx_list))
row_ind = list(idx_list)
col_ind = np.zeros(len(idx_list))
return sp.csr_matrix((data, (row_ind, col_ind)), shape=shape)
def sp_row_vec_from_idx_list(idx_list, dim):
"""Create sparse vector of dimensionality dim from a list of indices."""
shape = (1, dim)
data = np.ones(len(idx_list))
row_ind = np.zeros(len(idx_list))
col_ind = list(idx_list)
return sp.csr_matrix((data, (row_ind, col_ind)), shape=shape)
def get_neighbors(adj, nodes):
"""Takes a set of nodes and a graph adjacency matrix and returns a set of neighbors."""
sp_nodes = sp_row_vec_from_idx_list(list(nodes), adj.shape[1])
sp_neighbors = sp_nodes.dot(adj)
neighbors = set(sp.find(sp_neighbors)[1]) # convert to set of indices
return neighbors
def bfs(adj, roots):
"""
Perform BFS on a graph given by an adjaceny matrix adj.
Can take a set of multiple root nodes.
Root nodes have level 0, first-order neighors have level 1, and so on.]
"""
visited = set()
current_lvl = set(roots)
while current_lvl:
for v in current_lvl:
visited.add(v)
next_lvl = get_neighbors(adj, current_lvl)
next_lvl -= visited # set difference
yield next_lvl
current_lvl = next_lvl
def bfs_relational(adj_list, roots):
"""
BFS for graphs with multiple edge types. Returns list of level sets.
Each entry in list corresponds to relation specified by adj_list.
"""
visited = set()
current_lvl = set(roots)
next_lvl = list()
for rel in range(len(adj_list)):
next_lvl.append(set())
while current_lvl:
for v in current_lvl:
visited.add(v)
for rel in range(len(adj_list)):
next_lvl[rel] = get_neighbors(adj_list[rel], current_lvl)
next_lvl[rel] -= visited # set difference
yield next_lvl
current_lvl = set.union(*next_lvl)
def bfs_sample(adj, roots, max_lvl_size):
"""
BFS with node dropout. Only keeps random subset of nodes per level up to max_lvl_size.
'roots' should be a mini-batch of nodes (set of node indices).
NOTE: In this implementation, not every node in the mini-batch is guaranteed to have
the same number of neighbors, as we're sampling for the whole batch at the same time.
"""
visited = set(roots)
current_lvl = set(roots)
while current_lvl:
next_lvl = get_neighbors(adj, current_lvl)
next_lvl -= visited # set difference
for v in next_lvl:
visited.add(v)
yield next_lvl
current_lvl = next_lvl
def get_splits(y, train_idx, test_idx, validation=True):
# Make dataset splits
# np.random.shuffle(train_idx)
if validation:
idx_train = train_idx[len(train_idx) / 5:]
idx_val = train_idx[:len(train_idx) / 5]
idx_test = idx_val # report final score on validation set for hyperparameter optimization
else:
idx_train = train_idx
idx_val = train_idx # no validation
idx_test = test_idx
y_train = np.zeros(y.shape)
y_val = np.zeros(y.shape)
y_test = np.zeros(y.shape)
y_train[idx_train] = np.array(y[idx_train].todense())
y_val[idx_val] = np.array(y[idx_val].todense())
y_test[idx_test] = np.array(y[idx_test].todense())
return y_train, y_val, y_test, idx_train, idx_val, idx_test
def normalize_adj(adj, symmetric=True):
if symmetric:
d = sp.diags(np.power(np.array(adj.sum(1)), -0.5).flatten())
a_norm = adj.dot(d).transpose().dot(d).tocsr()
else:
d = sp.diags(np.power(np.array(adj.sum(1)), -1).flatten())
a_norm = d.dot(adj).tocsr()
return a_norm
def preprocess_adj(adj, symmetric=True):
adj = normalize_adj(adj, symmetric)
return adj
def sample_mask(idx, l):
mask = np.zeros(l)
mask[idx] = 1
return np.array(mask, dtype=np.bool)
def categorical_crossentropy(preds, labels):
return np.mean(-np.log(np.extract(labels, preds)))
def binary_crossentropy(preds, labels):
return np.mean(-labels*np.log(preds) - (1-labels)*np.log(1-preds))
def two_class_accuracy(preds, labels, threshold=0.5):
return np.mean(np.equal(labels, preds > 0.5))
def accuracy(preds, labels):
return np.mean(np.equal(np.argmax(labels, 1), np.argmax(preds, 1)))
def evaluate_preds(preds, labels, indices):
split_loss = list()
split_acc = list()
for y_split, idx_split in zip(labels, indices):
split_loss.append(categorical_crossentropy(preds[idx_split], y_split[idx_split]))
split_acc.append(accuracy(preds[idx_split], y_split[idx_split]))
return split_loss, split_acc
def evaluate_preds_sigmoid(preds, labels, indices):
split_loss = list()
split_acc = list()
for y_split, idx_split in zip(labels, indices):
split_loss.append(binary_crossentropy(preds[idx_split], y_split[idx_split]))
split_acc.append(two_class_accuracy(preds[idx_split], y_split[idx_split]))
return split_loss, split_acc