You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

marginalizedKernel.py 12 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. """
  2. @author: linlin
  3. @references:
  4. [1] H. Kashima, K. Tsuda, and A. Inokuchi. Marginalized kernels between
  5. labeled graphs. In Proceedings of the 20th International Conference on
  6. Machine Learning, Washington, DC, United States, 2003.
  7. [2] Pierre Mahé, Nobuhisa Ueda, Tatsuya Akutsu, Jean-Luc Perret, and
  8. Jean-Philippe Vert. Extensions of marginalized graph kernels. In
  9. Proceedings of the twenty-first international conference on Machine
  10. learning, page 70. ACM, 2004.
  11. """
  12. import sys
  13. import time
  14. from functools import partial
  15. from multiprocessing import Pool
  16. from tqdm import tqdm
  17. tqdm.monitor_interval = 0
  18. #import traceback
  19. import networkx as nx
  20. import numpy as np
  21. from gklearn.utils.kernels import deltakernel
  22. from gklearn.utils.utils import untotterTransformation
  23. from gklearn.utils.graphdataset import get_dataset_attributes
  24. from gklearn.utils.parallel import parallel_gm
  25. sys.path.insert(0, "../")
  26. def marginalizedkernel(*args,
  27. node_label='atom',
  28. edge_label='bond_type',
  29. p_quit=0.5,
  30. n_iteration=20,
  31. remove_totters=False,
  32. n_jobs=None,
  33. verbose=True):
  34. """Calculate marginalized graph kernels between graphs.
  35. Parameters
  36. ----------
  37. Gn : List of NetworkX graph
  38. List of graphs between which the kernels are calculated.
  39. G1, G2 : NetworkX graphs
  40. Two graphs between which the kernel is calculated.
  41. node_label : string
  42. Node attribute used as symbolic label. The default node label is 'atom'.
  43. edge_label : string
  44. Edge attribute used as symbolic label. The default edge label is 'bond_type'.
  45. p_quit : integer
  46. The termination probability in the random walks generating step.
  47. n_iteration : integer
  48. Time of iterations to calculate R_inf.
  49. remove_totters : boolean
  50. Whether to remove totterings by method introduced in [2]. The default
  51. value is False.
  52. n_jobs : int
  53. Number of jobs for parallelization.
  54. Return
  55. ------
  56. Kmatrix : Numpy matrix
  57. Kernel matrix, each element of which is the marginalized kernel between
  58. 2 praphs.
  59. """
  60. # pre-process
  61. n_iteration = int(n_iteration)
  62. Gn = args[0][:] if len(args) == 1 else [args[0].copy(), args[1].copy()]
  63. Gn = [g.copy() for g in Gn]
  64. ds_attrs = get_dataset_attributes(
  65. Gn,
  66. attr_names=['node_labeled', 'edge_labeled', 'is_directed'],
  67. node_label=node_label, edge_label=edge_label)
  68. if not ds_attrs['node_labeled'] or node_label == None:
  69. node_label = 'atom'
  70. for G in Gn:
  71. nx.set_node_attributes(G, '0', 'atom')
  72. if not ds_attrs['edge_labeled'] or edge_label == None:
  73. edge_label = 'bond_type'
  74. for G in Gn:
  75. nx.set_edge_attributes(G, '0', 'bond_type')
  76. start_time = time.time()
  77. if remove_totters:
  78. # ---- use pool.imap_unordered to parallel and track progress. ----
  79. pool = Pool(n_jobs)
  80. untotter_partial = partial(wrapper_untotter, Gn, node_label, edge_label)
  81. if len(Gn) < 100 * n_jobs:
  82. chunksize = int(len(Gn) / n_jobs) + 1
  83. else:
  84. chunksize = 100
  85. for i, g in tqdm(
  86. pool.imap_unordered(
  87. untotter_partial, range(0, len(Gn)), chunksize),
  88. desc='removing tottering',
  89. file=sys.stdout):
  90. Gn[i] = g
  91. pool.close()
  92. pool.join()
  93. # # ---- direct running, normally use single CPU core. ----
  94. # Gn = [
  95. # untotterTransformation(G, node_label, edge_label)
  96. # for G in tqdm(Gn, desc='removing tottering', file=sys.stdout)
  97. # ]
  98. Kmatrix = np.zeros((len(Gn), len(Gn)))
  99. # ---- use pool.imap_unordered to parallel and track progress. ----
  100. def init_worker(gn_toshare):
  101. global G_gn
  102. G_gn = gn_toshare
  103. do_partial = partial(wrapper_marg_do, node_label, edge_label,
  104. p_quit, n_iteration)
  105. parallel_gm(do_partial, Kmatrix, Gn, init_worker=init_worker,
  106. glbv=(Gn,), n_jobs=n_jobs, verbose=verbose)
  107. # # ---- direct running, normally use single CPU core. ----
  108. ## pbar = tqdm(
  109. ## total=(1 + len(Gn)) * len(Gn) / 2,
  110. ## desc='calculating kernels',
  111. ## file=sys.stdout)
  112. # for i in range(0, len(Gn)):
  113. # for j in range(i, len(Gn)):
  114. ## print(i, j)
  115. # Kmatrix[i][j] = _marginalizedkernel_do(Gn[i], Gn[j], node_label,
  116. # edge_label, p_quit, n_iteration)
  117. # Kmatrix[j][i] = Kmatrix[i][j]
  118. ## pbar.update(1)
  119. run_time = time.time() - start_time
  120. if verbose:
  121. print("\n --- marginalized kernel matrix of size %d built in %s seconds ---"
  122. % (len(Gn), run_time))
  123. return Kmatrix, run_time
  124. def _marginalizedkernel_do(g1, g2, node_label, edge_label, p_quit, n_iteration):
  125. """Calculate marginalized graph kernel between 2 graphs.
  126. Parameters
  127. ----------
  128. G1, G2 : NetworkX graphs
  129. 2 graphs between which the kernel is calculated.
  130. node_label : string
  131. node attribute used as label.
  132. edge_label : string
  133. edge attribute used as label.
  134. p_quit : integer
  135. the termination probability in the random walks generating step.
  136. n_iteration : integer
  137. time of iterations to calculate R_inf.
  138. Return
  139. ------
  140. kernel : float
  141. Marginalized Kernel between 2 graphs.
  142. """
  143. # init parameters
  144. kernel = 0
  145. num_nodes_G1 = nx.number_of_nodes(g1)
  146. num_nodes_G2 = nx.number_of_nodes(g2)
  147. # the initial probability distribution in the random walks generating step
  148. # (uniform distribution over |G|)
  149. p_init_G1 = 1 / num_nodes_G1
  150. p_init_G2 = 1 / num_nodes_G2
  151. q = p_quit * p_quit
  152. r1 = q
  153. # # initial R_inf
  154. # # matrix to save all the R_inf for all pairs of nodes
  155. # R_inf = np.zeros([num_nodes_G1, num_nodes_G2])
  156. #
  157. # # calculate R_inf with a simple interative method
  158. # for i in range(1, n_iteration):
  159. # R_inf_new = np.zeros([num_nodes_G1, num_nodes_G2])
  160. # R_inf_new.fill(r1)
  161. #
  162. # # calculate R_inf for each pair of nodes
  163. # for node1 in g1.nodes(data=True):
  164. # neighbor_n1 = g1[node1[0]]
  165. # # the transition probability distribution in the random walks
  166. # # generating step (uniform distribution over the vertices adjacent
  167. # # to the current vertex)
  168. # if len(neighbor_n1) > 0:
  169. # p_trans_n1 = (1 - p_quit) / len(neighbor_n1)
  170. # for node2 in g2.nodes(data=True):
  171. # neighbor_n2 = g2[node2[0]]
  172. # if len(neighbor_n2) > 0:
  173. # p_trans_n2 = (1 - p_quit) / len(neighbor_n2)
  174. #
  175. # for neighbor1 in neighbor_n1:
  176. # for neighbor2 in neighbor_n2:
  177. # t = p_trans_n1 * p_trans_n2 * \
  178. # deltakernel(g1.node[neighbor1][node_label],
  179. # g2.node[neighbor2][node_label]) * \
  180. # deltakernel(
  181. # neighbor_n1[neighbor1][edge_label],
  182. # neighbor_n2[neighbor2][edge_label])
  183. #
  184. # R_inf_new[node1[0]][node2[0]] += t * R_inf[neighbor1][
  185. # neighbor2] # ref [1] equation (8)
  186. # R_inf[:] = R_inf_new
  187. #
  188. # # add elements of R_inf up and calculate kernel
  189. # for node1 in g1.nodes(data=True):
  190. # for node2 in g2.nodes(data=True):
  191. # s = p_init_G1 * p_init_G2 * deltakernel(
  192. # node1[1][node_label], node2[1][node_label])
  193. # kernel += s * R_inf[node1[0]][node2[0]] # ref [1] equation (6)
  194. R_inf = {} # dict to save all the R_inf for all pairs of nodes
  195. # initial R_inf, the 1st iteration.
  196. for node1 in g1.nodes():
  197. for node2 in g2.nodes():
  198. # R_inf[(node1[0], node2[0])] = r1
  199. if len(g1[node1]) > 0:
  200. if len(g2[node2]) > 0:
  201. R_inf[(node1, node2)] = r1
  202. else:
  203. R_inf[(node1, node2)] = p_quit
  204. else:
  205. if len(g2[node2]) > 0:
  206. R_inf[(node1, node2)] = p_quit
  207. else:
  208. R_inf[(node1, node2)] = 1
  209. # compute all transition probability first.
  210. t_dict = {}
  211. if n_iteration > 1:
  212. for node1 in g1.nodes():
  213. neighbor_n1 = g1[node1]
  214. # the transition probability distribution in the random walks
  215. # generating step (uniform distribution over the vertices adjacent
  216. # to the current vertex)
  217. if len(neighbor_n1) > 0:
  218. p_trans_n1 = (1 - p_quit) / len(neighbor_n1)
  219. for node2 in g2.nodes():
  220. neighbor_n2 = g2[node2]
  221. if len(neighbor_n2) > 0:
  222. p_trans_n2 = (1 - p_quit) / len(neighbor_n2)
  223. for neighbor1 in neighbor_n1:
  224. for neighbor2 in neighbor_n2:
  225. t_dict[(node1, node2, neighbor1, neighbor2)] = \
  226. p_trans_n1 * p_trans_n2 * \
  227. deltakernel(g1.node[neighbor1][node_label],
  228. g2.node[neighbor2][node_label]) * \
  229. deltakernel(
  230. neighbor_n1[neighbor1][edge_label],
  231. neighbor_n2[neighbor2][edge_label])
  232. # calculate R_inf with a simple interative method
  233. for i in range(2, n_iteration + 1):
  234. R_inf_old = R_inf.copy()
  235. # calculate R_inf for each pair of nodes
  236. for node1 in g1.nodes():
  237. neighbor_n1 = g1[node1]
  238. # the transition probability distribution in the random walks
  239. # generating step (uniform distribution over the vertices adjacent
  240. # to the current vertex)
  241. if len(neighbor_n1) > 0:
  242. for node2 in g2.nodes():
  243. neighbor_n2 = g2[node2]
  244. if len(neighbor_n2) > 0:
  245. R_inf[(node1, node2)] = r1
  246. for neighbor1 in neighbor_n1:
  247. for neighbor2 in neighbor_n2:
  248. R_inf[(node1, node2)] += \
  249. (t_dict[(node1, node2, neighbor1, neighbor2)] * \
  250. R_inf_old[(neighbor1, neighbor2)]) # ref [1] equation (8)
  251. # add elements of R_inf up and calculate kernel
  252. for (n1, n2), value in R_inf.items():
  253. s = p_init_G1 * p_init_G2 * deltakernel(
  254. g1.nodes[n1][node_label], g2.nodes[n2][node_label])
  255. kernel += s * value # ref [1] equation (6)
  256. return kernel
  257. def wrapper_marg_do(node_label, edge_label, p_quit, n_iteration, itr):
  258. i= itr[0]
  259. j = itr[1]
  260. return i, j, _marginalizedkernel_do(G_gn[i], G_gn[j], node_label, edge_label, p_quit, n_iteration)
  261. def wrapper_untotter(Gn, node_label, edge_label, i):
  262. return i, untotterTransformation(Gn[i], node_label, edge_label)

A Python package for graph kernels, graph edit distances and graph pre-image problem.