-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
148 lines (119 loc) · 4.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
import torch
import random
import numpy as np
import networkx as nx
from scipy import sparse
import scipy.sparse as sp
from scipy.linalg import fractional_matrix_power, inv
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
def select_DatasSet(labels):
label_set = {}
for i, label in enumerate(labels, 0):
if label not in label_set.keys():
label_set[label] = [i]
else:
label_set[label].extend([i])
train_id = []
valid_id = []
test_id = []
for key, value in label_set.items():
train_id.extend(value[:int(len(value) * 0.1)])
valid_id.extend(value[int(len(value) * 0.1): int(len(value) * 0.2)])
test_id.extend(value[int(len(value) * 0.2):])
return np.array(train_id), np.array(valid_id), np.array(test_id)
def preprocess_graph(adj, layer, norm='sym', renorm=True):
adj = sp.coo_matrix(adj)
ident = sp.eye(adj.shape[0])
if renorm:
adj_ = adj + ident
else:
adj_ = adj
rowsum = np.array(adj_.sum(1))
if norm == 'sym':
degree_mat_inv_sqrt = sp.diags(np.power(rowsum, -0.5).flatten())
adj_normalized = adj_.dot(degree_mat_inv_sqrt).transpose().dot(degree_mat_inv_sqrt).tocoo()
laplacian = ident - adj_normalized
elif norm == 'left':
degree_mat_inv_sqrt = sp.diags(np.power(rowsum, -1.).flatten())
adj_normalized = degree_mat_inv_sqrt.dot(adj_).tocoo()
laplacian = ident - adj_normalized
reg = [2 / 3] * (layer)
adjs = []
for i in range(len(reg)):
adjs.append(ident - (reg[i] * laplacian))
return adjs
def Laplace(adj, feat):
adj_L = sparse.csr_matrix(adj)
adj_L = adj_L - sp.dia_matrix((adj_L.diagonal()[np.newaxis, :], [0]), shape=adj_L.shape)
adj_L.eliminate_zeros()
adj_norm_s = preprocess_graph(adj, layer=1, norm='sym', renorm=True)
feat_L = torch.FloatTensor(feat)
feat_L = sp.csr_matrix(feat_L).toarray()
for a in adj_norm_s:
feat_L = a.dot(feat_L)
return feat_L
def ppr(a, alpha=0.2, self_loop=True):
if self_loop:
a = a + np.eye(a.shape[0]) # A^ = A + I_n
d = np.diag(np.sum(a, 1)) # D^ = Sigma A^_ii
dinv = fractional_matrix_power(d, -0.5) # D^(-1/2)
at = np.matmul(np.matmul(dinv, a), dinv) # A~ = D^(-1/2) x A^ x D^(-1/2)
return alpha * inv((np.eye(a.shape[0]) - (1 - alpha) * at)) # a(I_n-(1-a)A~)^-1
def compute_heat(graph: nx.Graph, t=5, self_loop=True):
a = nx.convert_matrix.to_numpy_array(graph)
if self_loop:
a = a + np.eye(a.shape[0])
d = np.diag(np.sum(a, 1))
return np.exp(t * (np.matmul(a, inv(d)) - 1))
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 preprocess_features(features):
"""Row-normalize feature matrix and convert to tuple representation"""
rowsum = np.array(features.sum(1))
r_inv = np.power(rowsum, -1).flatten()
r_inv[np.isinf(r_inv)] = 0.
r_mat_inv = sp.diags(r_inv)
features = r_mat_inv.dot(features)
if isinstance(features, np.ndarray):
return features
else:
return features.todense(), sparse_to_tuple(features)
def normalize_adj(adj, self_loop=True):
"""Symmetrically normalize adjacency matrix."""
if self_loop:
adj = adj + sp.eye(adj.shape[0])
adj = sp.coo_matrix(adj)
rowsum = np.array(adj.sum(1))
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()
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)