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

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