-
Notifications
You must be signed in to change notification settings - Fork 4
/
benchmark_regularized_village.py
335 lines (286 loc) · 11.1 KB
/
benchmark_regularized_village.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
330
331
332
333
334
335
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib
import time
import ot
from scipy import linalg
from scipy import sparse
import gromovWassersteinAveraging as gwa
import spectralGW as sgw
from geodesicVisualization import *
import json
# Load the S-GWL code
import DataIO as DataIO
import EvaluationMeasure as Eval
import GromovWassersteinGraphToolkit as GwGt
import pickle
import warnings
# Load modules for network partitioning experiments
import community
from networkx.algorithms.community import greedy_modularity_communities
from networkx.algorithms.community.asyn_fluid import asyn_fluidc
from sklearn import metrics
from infomap import Infomap
warnings.filterwarnings("ignore")
# dictionaries for holding results
scores = {}
runtimes = {}
avetimes = {}
# load data
num_nodes = 1991
num_partitions = 12
with open('data/India_database.p', 'rb') as f:
database = pickle.load(f)
G = nx.Graph()
nG = nx.Graph()
for i in range(num_nodes):
G.add_node(i)
nG.add_node(i)
for edge in database['edges']:
G.add_edge(edge[0], edge[1])
nG.add_edge(edge[0], edge[1])
start_edges = nx.number_of_edges(G)
# add noise
for j in range(int(0.1*G.number_of_edges() ) ):
x1 = int(num_nodes * np.random.rand())
x2 = int(num_nodes * np.random.rand())
if database['label'][x1] != database['label'][x2]:
nG.add_edge(x1, x2)
print('---{:3d} edges in raw version \n'.format(G.number_of_edges()))
print('---Added {:d} edges to create noisy version \n'.format(nx.number_of_edges(nG)-start_edges))
database['labels'] = database['label']
print('---Data files loaded. Computing...\n')
def process_sgwl_village(cost,database,num_nodes,num_partitions,beta=5e-5,verbose=False):
# p_s = np.zeros((num_nodes, 1))
# p_s[:, 0] = np.sum(cost, axis=1) ** 0.001
# p_s /= np.sum(p_s)
# p_t = GwGt.estimate_target_distribution({0: p_s}, dim_t=num_partitions)
p_s = database['prob'] + 5e-1
p_s /= np.sum(p_s)
p_t = GwGt.estimate_target_distribution({0: p_s}, dim_t=num_partitions)
ot_dict = {'loss_type': 'L2', # the key hyperparameters of GW distance
'ot_method': 'proximal',
'beta': beta,
'outer_iteration': 200,
# outer, inner iteration, error bound of optimal transport
'iter_bound': 1e-30,
'inner_iteration': 1,
'sk_bound': 1e-30,
'node_prior': 0,
'max_iter': 200, # iteration and error bound for calcuating barycenter
'cost_bound': 1e-16,
'update_p': False, # optional updates of source distribution
'lr': 0,
'alpha': 0}
time_s = time.time()
sub_costs, sub_probs, sub_idx2nodes, trans = GwGt.graph_partition(cost,
p_s,
p_t,
database['idx2node'],
ot_dict)
est_idx = np.argmax(trans, axis=1)
mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
if verbose:
print('---Mutual information score = {:3.3f}'.format(mutual_info))
return mutual_info
# ###########################################################
# ###########################################################
# # Method: Fluid communities
# ###########################################################
# # Raw data
# if not nx.is_connected(G):
# #print('---Fluid community requires connected graph, skipping raw version---')
# scores['fluid-raw'] = 'failed'
# runtimes['fluid-raw'] = 'failed'
# else:
# time_s = time.time()
# comp = asyn_fluidc(G.to_undirected(), k=num_partitions)
# list_nodes = [frozenset(c) for c in comp]
# est_idx = np.zeros((num_nodes,))
# for i in range(len(list_nodes)):
# for idx in list_nodes[i]:
# est_idx[idx] = i
# runtime = time.time() - time_s
# mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
# scores['fluid-raw'] = mutual_info
# runtimes['fluid-raw'] = runtime
# # Noisy data
# if not nx.is_connected(nG):
# print('---Fluid community requires connected graph, skipping noisy version---')
# scores['fluid-noisy'] = 'failed'
# runtimes['fluid-noisy'] = 'failed'
# else:
# time_s = time.time()
# comp = asyn_fluidc(nG.to_undirected(), k=num_partitions)
# list_nodes = [frozenset(c) for c in comp]
# est_idx = np.zeros((num_nodes,))
# for i in range(len(list_nodes)):
# for idx in list_nodes[i]:
# est_idx[idx] = i
# runtime = time.time() - time_s
# mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
# scores['fluid-noisy'] = mutual_info
# runtimes['fluid-noisy'] = runtime
# ###########################################################
# ###########################################################
# # Method: FastGreedy
# ###########################################################
# # Raw
# time_s = time.time()
# list_nodes = list(greedy_modularity_communities(G))
# est_idx = np.zeros((num_nodes,))
# for i in range(len(list_nodes)):
# for idx in list_nodes[i]:
# est_idx[idx] = i
# runtime = time.time() - time_s
# mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
# scores['fastgreedy-raw'] = mutual_info
# runtimes['fastgreedy-raw'] = runtime
# # Noisy
# time_s = time.time()
# list_nodes = list(greedy_modularity_communities(nG))
# est_idx = np.zeros((num_nodes,))
# for i in range(len(list_nodes)):
# for idx in list_nodes[i]:
# est_idx[idx] = i
# runtime = time.time() - time_s
# mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
# scores['fastgreedy-noisy'] = mutual_info
# runtimes['fastgreedy-noisy'] = runtime
# ###########################################################
# ###########################################################
# # Method: Louvain
# ###########################################################
# # Raw
# time_s = time.time()
# partition = community.best_partition(G)
# est_idx = np.zeros((num_nodes,))
# for com in set(partition.values()):
# list_nodes = [nodes for nodes in partition.keys()
# if partition[nodes] == com]
# for idx in list_nodes:
# est_idx[idx] = com
# runtime = time.time() - time_s
# mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
# scores['louvain-raw'] = mutual_info
# runtimes['louvain-raw'] = runtime
# # Noisy
# time_s = time.time()
# partition = community.best_partition(nG)
# est_idx = np.zeros((num_nodes,))
# for com in set(partition.values()):
# list_nodes = [nodes for nodes in partition.keys()
# if partition[nodes] == com]
# for idx in list_nodes:
# est_idx[idx] = com
# runtime = time.time() - time_s
# mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
# scores['louvain-noisy'] = mutual_info
# runtimes['louvain-noisy'] = runtime
# ###########################################################
# ###########################################################
# # Method: Infomap
# ###########################################################
# # Raw
# time_s = time.time()
# im = Infomap()
# for node in G.nodes:
# im.add_node(node)
# for edge in G.edges:
# im.add_link(edge[0], edge[1])
# im.add_link(edge[1],edge[0])
# # Run the Infomap search algorithm to find optimal modules
# im.run()
# # print(f"Found {im.num_top_modules} modules with Infomap")
# est_idx = np.zeros((num_nodes,))
# for node in im.tree:
# if node.is_leaf:
# est_idx[node.node_id] = node.module_id
# runtime = time.time() - time_s
# mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
# scores['infomap-raw'] = mutual_info
# runtimes['infomap-raw'] = runtime
# # Noisy
# print('---Running Infomap with noisy data---\n')
# time_s = time.time()
# im = Infomap()
# for node in nG.nodes:
# im.add_node(node)
# for edge in nG.edges:
# im.add_link(edge[0], edge[1])
# im.add_link(edge[1],edge[0])
# # Run the Infomap search algorithm to find optimal modules
# im.run()
# # print(f"Found {im.num_top_modules} modules with Infomap")
# est_idx = np.zeros((num_nodes,))
# for node in im.tree:
# if node.is_leaf:
# est_idx[node.node_id] = node.module_id
# runtime = time.time() - time_s
# mutual_info = metrics.adjusted_mutual_info_score(database['labels'], est_idx)
# scores['infomap-noisy'] = mutual_info
# runtimes['infomap-noisy'] = runtime
###########################################################
###########################################################
# Method: GWL
###########################################################
# Raw
start = time.time()
cost = nx.adjacency_matrix(G).toarray() #database['cost']
mutual_info = process_sgwl_village(cost,database,num_nodes,num_partitions,beta=5e-5);
end = time.time()
scores['gwl-raw'] = mutual_info
runtimes['gwl-raw'] = end-start
# Noisy
start = time.time()
cost = nx.adjacency_matrix(nG).toarray()
mutual_info = process_sgwl_village(cost,database,num_nodes,num_partitions,beta=5e-5);
end = time.time()
scores['gwl-noisy'] = mutual_info
runtimes['gwl-noisy'] = end-start
###########################################################
###########################################################
# Proposed method: SpecGWL
###########################################################
# Raw
mis = []
rt = []
ts = [8.4]#np.linspace(7,9,20)
for t in ts:
start = time.time()
cost = sgw.undirected_normalized_heat_kernel(G,t)
mutual_info = process_sgwl_village(cost,database,num_nodes,num_partitions,beta=5e-6);
mis.append(mutual_info)
end = time.time()
rt.append(end-start)
# print('--- Raw data | SpecGWL | Best mutual information score: {:3.3f} | @t = {:3.3f} | average runtime per iteration = {:3.3f}'.format(max(mis), ts[np.argmax(mis)], np.mean(rt)))
scores['specgwl-raw'] = max(mis)
runtimes['specgwl-raw'] = sum(rt)
# avetimes['specgwl-raw'] = np.mean(rt)
# Noisy
mis = []
rt = []
ts = [8.4]#np.linspace(7,9,20)
for t in ts:
start = time.time()
cost = sgw.undirected_normalized_heat_kernel(nG,t)
mi = process_sgwl_village(cost,database,num_nodes,num_partitions,beta=5e-6);
mis.append(mi)
end = time.time()
rt.append(end-start)
# print('--- Noisy data | SpecGWL | Best mutual information score: {:3.3f} | @t = {:3.3f} | average runtime per iteration = {:3.3f}'.format(max(mis), ts[np.argmax(mis)], np.mean(rt)))
scores['specgwl-noisy'] = max(mis)
runtimes['specgwl-noisy'] = sum(rt)
# avetimes['specgwl-noisy'] = np.mean(rt)
print('Mutual information scores')
print(json.dumps(scores,indent=1))
print('Runtimes')
print(json.dumps(runtimes,indent=1))
# print('Average runtime of SpecGWL')
# print(json.dumps(avetimes,indent=1))
with open('res_benchmark_regularized_village.txt', 'w') as outfile:
json.dump(['Adjusted mutual information scores',
scores,
'Runtimes',
runtimes], outfile,indent=1)