-
Notifications
You must be signed in to change notification settings - Fork 0
/
hypergraph_rooted_kernel.py
190 lines (183 loc) · 7.31 KB
/
hypergraph_rooted_kernel.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
from collections import defaultdict
import torch
import numpy as np
# Hypergraph Kernel from "Learning from Interpretations: A Rooted Kernel for Ordered Hypergraphs"
class HypergraphRootedKernel:
def __init__(self, max_walk_len=4, gamma=0.5, normalize=True, degree_as_label=True):
self.n_seq = 20
self.gamma = gamma
self.max_walk_len = max_walk_len
self.normalize = normalize
self.degree_as_label = degree_as_label
self._seq_map = {idx: dict() for idx in range(1, max_walk_len + 1)}
def count2mat(self, count, l):
row_idx, col_idx, data = [], [], []
for idx, g in enumerate(count):
for lbl, cnt in g.items():
row_idx.append(idx)
col_idx.append(lbl)
data.append(cnt)
return (
torch.sparse_coo_tensor(
torch.tensor([row_idx, col_idx]),
torch.tensor(data),
size=(len(count), len(self._seq_map[l])),
)
.coalesce()
.float()
)
def fuse(self, fts):
res = None
for i, ft in fts.items():
if res is None:
res = ft * self.gamma**i
else:
res += ft * self.gamma**i
return res
def fit_transform(self, hg_list):
# initialize the sequence count
self._count = {
idx: [defaultdict(int) for _ in range(len(hg_list))]
for idx in range(1, self.max_walk_len + 1)
}
# initialize the hyperedge feature
if not self.degree_as_label:
e_lbl = [hg["e_lbl"] for hg in hg_list]
else:
e_lbl = [[int(e) for e in hg["dhg"].deg_e] for hg in hg_list]
# initialize the hyperedge transfer matrix
# P = D_e^-1 H^T W D_v^-1 H
T = [
hg["dhg"]
.W_e.mm(hg["dhg"].D_e_neg_1)
.mm(hg["dhg"].H.t())
.mm(hg["dhg"].D_v_neg_1)
.mm(hg["dhg"].H)
.to_dense()
.numpy()
for hg in hg_list
]
# estimate the sequence count
# N_e, D_e, D_v = [], [], []
# for hg in hg_list:
# N_e.append(hg["dhg"].num_e)
# D_e.append(np.mean(hg["dhg"].deg_e))
# D_v.append(np.mean(hg["dhg"].deg_v))
# N_e, D_e, D_v = np.mean(N_e), np.mean(D_e), np.mean(D_v)
# self.n_seq = int(N_e * (D_e * D_v) ** self.max_walk_len / 100)
# self.prob_len = [(D_e * D_v)**i for i in range(self.max_walk_len)]
self.prob_len = [2**i for i in range(1, self.max_walk_len + 1)]
self.prob_len = np.array(self.prob_len) / np.sum(self.prob_len)
# walk on the hypergraph
for hg_idx, hg in enumerate(hg_list):
# print(f"Processing training hypergraph {hg_idx}/{len(hg_list)}")
# estimate the sequence count
if self.n_seq == -1:
n_seq = int(
hg["dhg"].num_e
* (np.mean(hg["dhg"].deg_e) * np.mean(hg["dhg"].deg_v))
** self.max_walk_len
/ 200
)
else:
n_seq = self.n_seq
num_e = hg["dhg"].num_e
seq_list = []
for _ in range(n_seq):
cur_len = np.random.choice(self.max_walk_len, p=self.prob_len)
seq_idx = [np.random.choice(num_e)]
seq = [e_lbl[hg_idx][seq_idx[-1]]]
for _ in range(cur_len):
seq_idx.append(np.random.choice(num_e, p=T[hg_idx][seq_idx[-1]]))
seq.append(e_lbl[hg_idx][seq_idx[-1]])
seq_list.append(seq)
# count the sequence
for seq in seq_list:
code = ",".join([str(s) for s in seq])
if code not in self._seq_map[len(seq)]:
self._seq_map[len(seq)][code] = len(self._seq_map[len(seq)])
self._count[len(seq)][hg_idx][self._seq_map[len(seq)][code]] += 1
# compute the kernel matrix
self.raw_train_cnt = {l: self.count2mat(c, l) for l, c in self._count.items()}
self.raw_train_ft = {
l: self.raw_train_cnt[l].mm(self.raw_train_cnt[l].t()).to_dense()
for l in self.raw_train_cnt
}
self.train_ft = self.fuse(self.raw_train_ft)
if self.normalize:
self.train_ft_diag = torch.diag(self.train_ft)
self.train_ft = (
self.train_ft
/ torch.outer(self.train_ft_diag, self.train_ft_diag).sqrt()
)
self.train_ft[torch.isnan(self.train_ft)] = 0
return self.train_ft
def transform(self, hg_list):
# initialize the sequence count
count = {
idx: [defaultdict(int) for _ in range(len(hg_list))]
for idx in range(1, self.max_walk_len + 1)
}
# initialize the hyperedge feature
if not self.degree_as_label:
e_lbl = [hg["e_lbl"] for hg in hg_list]
else:
e_lbl = [[int(e) for e in hg["dhg"].deg_e] for hg in hg_list]
# initialize the hyperedge transfer matrix
# P = D_e^-1 H^T W D_v^-1 H
T = [
hg["dhg"]
.W_e.mm(hg["dhg"].D_e_neg_1)
.mm(hg["dhg"].H.t())
.mm(hg["dhg"].D_v_neg_1)
.mm(hg["dhg"].H)
.to_dense()
.numpy()
for hg in hg_list
]
# walk on the hypergraph
for hg_idx, hg in enumerate(hg_list):
print(f"Processing testing hypergraph {hg_idx}/{len(hg_list)}")
# estimate the sequence count
if self.n_seq == -1:
n_seq = int(
hg["dhg"].num_e
* (np.mean(hg["dhg"].deg_e) * np.mean(hg["dhg"].deg_v))
** self.max_walk_len
/ 200
)
else:
n_seq = self.n_seq
num_e = hg["dhg"].num_e
seq_list = []
for _ in range(n_seq):
cur_len = np.random.choice(self.max_walk_len, p=self.prob_len)
seq_idx = [np.random.choice(num_e)]
seq = [e_lbl[hg_idx][seq_idx[-1]]]
for _ in range(cur_len):
seq_idx.append(np.random.choice(num_e, p=T[hg_idx][seq_idx[-1]]))
seq.append(e_lbl[hg_idx][seq_idx[-1]])
seq_list.append(seq)
# count the sequence
for seq in seq_list:
code = ",".join([str(s) for s in seq])
if code not in self._seq_map[len(seq)]:
continue
count[len(seq)][hg_idx][self._seq_map[len(seq)][code]] += 1
# compute the kernel matrix
raw_test_cnt = {l: self.count2mat(c, l) for l, c in count.items()}
raw_test_ft = {
l: raw_test_cnt[l].mm(self.raw_train_cnt[l].t()).to_dense()
for l in raw_test_cnt
}
test_ft = self.fuse(raw_test_ft)
if self.normalize:
test_ft_diag = self.fuse(
{
l: torch.sparse.sum(tc * tc, dim=1).to_dense()
for l, tc in raw_test_cnt.items()
}
)
test_ft = test_ft / torch.outer(test_ft_diag, self.train_ft_diag).sqrt()
test_ft[torch.isnan(test_ft)] = 0
return test_ft