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

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

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