-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
329 lines (254 loc) · 9.56 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
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
"""
utility functions
"""
import os
import scipy
import scipy.sparse as sp
from scipy.stats import sem
import numpy as np
from torch_scatter import scatter_add
from torch_geometric.utils import add_remaining_self_loops
from torch_geometric.utils.num_nodes import maybe_num_nodes
from torch_geometric.utils.convert import to_scipy_sparse_matrix
from sklearn.preprocessing import normalize
from torch_geometric.nn.conv.gcn_conv import gcn_norm
from torch_sparse import SparseTensor
import numpy as np
import networkx as nx
import os
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
class MaxNFEException(Exception): pass
def sparse_to_tuple(sparse_mx):
"""
Convert sparse matrix to tuple representation.
"""
def to_tuple(mx):
if not sp.isspmatrix_coo(mx):
mx = mx.tocoo()
coords = np.vstack((mx.row, mx.col)).transpose()
values = mx.data
shape = mx.shape
return coords, values, shape
if isinstance(sparse_mx, list):
for i in range(len(sparse_mx)):
sparse_mx[i] = to_tuple(sparse_mx[i])
else:
sparse_mx = to_tuple(sparse_mx)
return sparse_mx
def generate_sparse_adj(scipy_sparse_graph):
"""
Convert sparse matrix to SparseTensor representation.
"""
supports = sparse_to_tuple(scipy_sparse_graph)
i = torch.from_numpy(supports[0]).long()
v = torch.from_numpy(supports[1])
support = torch.sparse.FloatTensor(i.t(), v, supports[2]).float()
adj = SparseTensor.from_torch_sparse_coo_tensor(support)
return adj
def make_2d_graph(m, n, periodic=False, return_pos=False):
network = nx.grid_2d_graph(m, n, periodic=False, create_using=None)
matrix = nx.linalg.graphmatrix.adjacency_matrix(network).todense()
matrix = np.array(matrix).astype(float)
return matrix
def get_graph_props(A, normalize_L='none', shift_to_zero_diag=False):
ran = range(A.shape[0])
D = np.zeros_like(A)
D[ran, ran] = np.abs(np.sum(A, axis=1) - A[ran, ran])
L = D - A
if (normalize_L is None) or (normalize_L=='none') or (normalize_L == False):
pass
elif (normalize_L == 'inv'):
Dinv = np.linalg.inv(D)
L = np.matmul(Dinv, L) # Normalized laplacian
elif (normalize_L == 'sym'):
Dinv = np.sqrt(np.linalg.inv(D))
L = np.matmul(np.matmul(Dinv, L), Dinv)
elif (normalize_L == 'abs'):
L = np.abs(L)
else:
raise ValueError('unsupported normalization option')
eigval, eigvec = np.linalg.eigh(L)
eigval = np.real(eigval)
# eigidx = np.argsort(eigval)[::-1]
eigidx = np.argsort(eigval)
eigval = eigval[eigidx]
eigvec = eigvec[:, eigidx]
L_inv = np.linalg.pinv(L)
if shift_to_zero_diag:
L_inv_diag = L_inv[np.eye(L.shape[0])>0]
L_inv = (L_inv - L_inv_diag[:, np.newaxis])
return D, L, L_inv, eigval, eigvec
def rms_norm(tensor):
return tensor.pow(2).mean().sqrt()
def make_norm(state):
if isinstance(state, tuple):
state = state[0]
state_size = state.numel()
def norm(aug_state):
y = aug_state[1:1 + state_size]
adj_y = aug_state[1 + state_size:1 + 2 * state_size]
return max(rms_norm(y), rms_norm(adj_y))
return norm
def print_model_params(model):
total_num_params = 0
print(model)
for name, param in model.named_parameters():
if param.requires_grad:
print(name)
print(param.data.shape)
total_num_params += param.numel()
print("Model has a total of {} params".format(total_num_params))
def adjust_learning_rate(optimizer, lr, epoch, burnin=50):
if epoch <= burnin:
for param_group in optimizer.param_groups:
param_group["lr"] = lr * epoch / burnin
def gcn_norm_fill_val(edge_index, edge_weight=None, fill_value=0., num_nodes=None, dtype=None):
num_nodes = maybe_num_nodes(edge_index, num_nodes)
if edge_weight is None:
edge_weight = torch.ones((edge_index.size(1),), dtype=dtype,
device=edge_index.device)
if not int(fill_value) == 0:
edge_index, tmp_edge_weight = add_remaining_self_loops(
edge_index, edge_weight, fill_value, num_nodes)
assert tmp_edge_weight is not None
edge_weight = tmp_edge_weight
row, col = edge_index[0], edge_index[1]
deg = scatter_add(edge_weight, col, dim=0, dim_size=num_nodes)
deg_inv_sqrt = deg.pow_(-0.5)
deg_inv_sqrt.masked_fill_(deg_inv_sqrt == float('inf'), 0)
return edge_index, deg_inv_sqrt[row] * edge_weight * deg_inv_sqrt[col]
def coo2tensor(coo, device=None):
indices = np.vstack((coo.row, coo.col))
i = torch.LongTensor(indices)
values = coo.data
v = torch.FloatTensor(values)
shape = coo.shape
print('adjacency matrix generated with shape {}'.format(shape))
# test
return torch.sparse.FloatTensor(i, v, torch.Size(shape)).to(device)
def get_sym_adj(data, opt, improved=False):
edge_index, edge_weight = gcn_norm( # yapf: disable
data.edge_index, data.edge_attr, data.num_nodes,
improved, opt['self_loop_weight'] > 0, dtype=data.x.dtype)
coo = to_scipy_sparse_matrix(edge_index, edge_weight)
return coo2tensor(coo)
def get_rw_adj_old(data, opt):
if opt['self_loop_weight'] > 0:
edge_index, edge_weight = add_remaining_self_loops(data.edge_index, data.edge_attr,
fill_value=opt['self_loop_weight'])
else:
edge_index, edge_weight = data.edge_index, data.edge_attr
coo = to_scipy_sparse_matrix(edge_index, edge_weight)
normed_csc = normalize(coo, norm='l1', axis=0)
return coo2tensor(normed_csc.tocoo())
def get_rw_adj(edge_index, edge_weight=None, norm_dim=1, fill_value=0., num_nodes=None, dtype=None):
num_nodes = maybe_num_nodes(edge_index, num_nodes)
if edge_weight is None:
edge_weight = torch.ones((edge_index.size(1),), dtype=dtype,
device=edge_index.device)
if not fill_value == 0:
edge_index, tmp_edge_weight = add_remaining_self_loops(
edge_index, edge_weight, fill_value, num_nodes)
assert tmp_edge_weight is not None
edge_weight = tmp_edge_weight
row, col = edge_index[0], edge_index[1]
indices = row if norm_dim == 0 else col
deg = scatter_add(edge_weight, indices, dim=0, dim_size=num_nodes)
deg_inv_sqrt = deg.pow_(-1)
edge_weight = deg_inv_sqrt[indices] * edge_weight if norm_dim == 0 else edge_weight * deg_inv_sqrt[indices]
return edge_index, edge_weight
def mean_confidence_interval(data, confidence=0.95):
"""
As number of samples will be < 10 use t-test for the mean confidence intervals
:param data: NDarray of metric means
:param confidence: The desired confidence interval
:return: Float confidence interval
"""
if len(data) < 2:
return 0
a = 1.0 * np.array(data)
n = len(a)
_, se = np.mean(a), scipy.stats.sem(a)
h = se * scipy.stats.t.ppf((1 + confidence) / 2., n - 1)
return h
def sparse_dense_mul(s, d):
i = s._indices()
v = s._values()
return torch.sparse.FloatTensor(i, v * d, s.size())
def get_sem(vec):
"""
wrapper around the scipy standard error metric
:param vec: List of metric means
:return:
"""
if len(vec) > 1:
retval = sem(vec)
else:
retval = 0.
return retval
def get_full_adjacency(num_nodes):
# what is the format of the edge index?
edge_index = torch.zeros((2, num_nodes ** 2),dtype=torch.long)
for idx in range(num_nodes):
edge_index[0][idx * num_nodes: (idx + 1) * num_nodes] = idx
edge_index[1][idx * num_nodes: (idx + 1) * num_nodes] = torch.arange(0, num_nodes,dtype=torch.long)
return edge_index
from typing import Optional
import torch
from torch import Tensor
from torch_scatter import scatter, segment_csr, gather_csr
# https://twitter.com/jon_barron/status/1387167648669048833?s=12
# @torch.jit.script
def squareplus(src: Tensor, index: Optional[Tensor], ptr: Optional[Tensor] = None,
num_nodes: Optional[int] = None) -> Tensor:
r"""Computes a sparsely evaluated softmax.
Given a value tensor :attr:`src`, this function first groups the values
along the first dimension based on the indices specified in :attr:`index`,
and then proceeds to compute the softmax individually for each group.
Args:
src (Tensor): The source tensor.
index (LongTensor): The indices of elements for applying the softmax.
ptr (LongTensor, optional): If given, computes the softmax based on
sorted inputs in CSR representation. (default: :obj:`None`)
num_nodes (int, optional): The number of nodes, *i.e.*
:obj:`max_val + 1` of :attr:`index`. (default: :obj:`None`)
:rtype: :class:`Tensor`
"""
out = src - src.max()
# out = out.exp()
out = (out + torch.sqrt(out ** 2 + 4)) / 2
if ptr is not None:
out_sum = gather_csr(segment_csr(out, ptr, reduce='sum'), ptr)
elif index is not None:
N = maybe_num_nodes(index, num_nodes)
out_sum = scatter(out, index, dim=0, dim_size=N, reduce='sum')[index]
else:
raise NotImplementedError
return out / (out_sum + 1e-16)
# Counter of forward and backward passes.
class Meter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = None
self.sum = 0
self.cnt = 0
def update(self, val):
self.val = val
self.sum += val
self.cnt += 1
def get_average(self):
if self.cnt == 0:
return 0
return self.sum / self.cnt
def get_value(self):
return self.val
class DummyDataset(object):
def __init__(self, data, num_classes):
self.data = data
self.num_classes = num_classes
class DummyData(object):
def __init__(self, edge_index=None, edge_Attr=None, num_nodes=None):
self.edge_index = edge_index
self.edge_attr = edge_Attr
self.num_nodes = num_nodes