-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
68 lines (63 loc) · 1.87 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
#%%
import torch
import numpy as np
def tensor2onehot(labels):
"""Convert label tensor to label onehot tensor.
Parameters
----------
labels : torch.LongTensor
node labels
Returns
-------
torch.LongTensor
onehot labels tensor
"""
labels = labels.long()
eye = torch.eye(labels.max() + 1)
onehot_mx = eye[labels]
return onehot_mx.to(labels.device)
def accuracy(output, labels):
"""Return accuracy of output compared to labels.
Parameters
----------
output : torch.Tensor
output from model
labels : torch.Tensor or numpy.array
node labels
Returns
-------
float
accuracy
"""
if not hasattr(labels, '__len__'):
labels = [labels]
if type(labels) is not torch.Tensor:
labels = torch.LongTensor(labels)
preds = output.max(1)[1].type_as(labels)
correct = preds.eq(labels).double()
correct = correct.sum()
return correct / len(labels)
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
"""Convert a scipy sparse matrix to a torch sparse tensor."""
sparse_mx = sparse_mx.tocoo().astype(np.float32)
indices = torch.from_numpy(
np.vstack((sparse_mx.row, sparse_mx.col)).astype(np.int64))
values = torch.from_numpy(sparse_mx.data)
shape = torch.Size(sparse_mx.shape)
return torch.sparse.FloatTensor(indices, values, shape)
def idx_to_mask(indices, n):
mask = torch.zeros(n, dtype=torch.bool)
mask[indices] = True
return mask
import scipy.sparse as sp
def sys_normalized_adjacency(adj):
adj = sp.coo_matrix(adj)
adj = adj + sp.eye(adj.shape[0])
row_sum = np.array(adj.sum(1))
row_sum=(row_sum==0)*1+row_sum
d_inv_sqrt = np.power(row_sum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return d_mat_inv_sqrt.dot(adj).dot(d_mat_inv_sqrt).tocoo()
# %%
# %%