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 11 kB

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

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