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.

commonWalkKernel.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. """
  2. @author: linlin
  3. @references:
  4. [1] Thomas Gärtner, Peter Flach, and Stefan Wrobel. On graph kernels:
  5. Hardness results and efficient alternatives. Learning Theory and Kernel
  6. Machines, pages 129–143, 2003.
  7. """
  8. import sys
  9. import time
  10. from collections import Counter
  11. from functools import partial
  12. import networkx as nx
  13. import numpy as np
  14. sys.path.insert(0, "../")
  15. from pygraph.utils.utils import direct_product
  16. from pygraph.utils.graphdataset import get_dataset_attributes
  17. from pygraph.utils.parallel import parallel_gm
  18. def commonwalkkernel(*args,
  19. node_label='atom',
  20. edge_label='bond_type',
  21. n=None,
  22. weight=1,
  23. compute_method=None,
  24. n_jobs=None):
  25. """Calculate common walk graph kernels between graphs.
  26. Parameters
  27. ----------
  28. Gn : List of NetworkX graph
  29. List of graphs between which the kernels are calculated.
  30. /
  31. G1, G2 : NetworkX graphs
  32. 2 graphs between which the kernel is calculated.
  33. node_label : string
  34. node attribute used as label. The default node label is atom.
  35. edge_label : string
  36. edge attribute used as label. The default edge label is bond_type.
  37. n : integer
  38. Longest length of walks. Only useful when applying the 'brute' method.
  39. weight: integer
  40. Weight coefficient of different lengths of walks, which represents beta
  41. in 'exp' method and gamma in 'geo'.
  42. compute_method : string
  43. Method used to compute walk kernel. The Following choices are
  44. available:
  45. 'exp' : exponential serial method applied on the direct product graph,
  46. as shown in reference [1]. The time complexity is O(n^6) for graphs
  47. with n vertices.
  48. 'geo' : geometric serial method applied on the direct product graph, as
  49. shown in reference [1]. The time complexity is O(n^6) for graphs with n
  50. vertices.
  51. 'brute' : brute force, simply search for all walks and compare them.
  52. Return
  53. ------
  54. Kmatrix : Numpy matrix
  55. Kernel matrix, each element of which is a common walk kernel between 2
  56. graphs.
  57. """
  58. compute_method = compute_method.lower()
  59. # arrange all graphs in a list
  60. Gn = args[0] if len(args) == 1 else [args[0], args[1]]
  61. # remove graphs with only 1 node, as they do not have adjacency matrices
  62. len_gn = len(Gn)
  63. Gn = [(idx, G) for idx, G in enumerate(Gn) if nx.number_of_nodes(G) != 1]
  64. idx = [G[0] for G in Gn]
  65. Gn = [G[1] for G in Gn]
  66. if len(Gn) != len_gn:
  67. print('\n %d graphs are removed as they have only 1 node.\n' %
  68. (len_gn - len(Gn)))
  69. ds_attrs = get_dataset_attributes(
  70. Gn,
  71. attr_names=['node_labeled', 'edge_labeled', 'is_directed'],
  72. node_label=node_label, edge_label=edge_label)
  73. if not ds_attrs['node_labeled']:
  74. for G in Gn:
  75. nx.set_node_attributes(G, '0', 'atom')
  76. if not ds_attrs['edge_labeled']:
  77. for G in Gn:
  78. nx.set_edge_attributes(G, '0', 'bond_type')
  79. if not ds_attrs['is_directed']: # convert
  80. Gn = [G.to_directed() for G in Gn]
  81. start_time = time.time()
  82. Kmatrix = np.zeros((len(Gn), len(Gn)))
  83. # ---- use pool.imap_unordered to parallel and track progress. ----
  84. def init_worker(gn_toshare):
  85. global G_gn
  86. G_gn = gn_toshare
  87. # direct product graph method - exponential
  88. if compute_method == 'exp':
  89. do_partial = partial(wrapper_cw_exp, node_label, edge_label, weight)
  90. # direct product graph method - geometric
  91. elif compute_method == 'geo':
  92. do_partial = partial(wrapper_cw_geo, node_label, edge_label, weight)
  93. parallel_gm(do_partial, Kmatrix, Gn, init_worker=init_worker,
  94. glbv=(Gn,), n_jobs=n_jobs)
  95. # pool = Pool(n_jobs)
  96. # itr = zip(combinations_with_replacement(Gn, 2),
  97. # combinations_with_replacement(range(0, len(Gn)), 2))
  98. # len_itr = int(len(Gn) * (len(Gn) + 1) / 2)
  99. # if len_itr < 1000 * n_jobs:
  100. # chunksize = int(len_itr / n_jobs) + 1
  101. # else:
  102. # chunksize = 1000
  103. #
  104. # # direct product graph method - exponential
  105. # if compute_method == 'exp':
  106. # do_partial = partial(wrapper_cw_exp, node_label, edge_label, weight)
  107. # # direct product graph method - geometric
  108. # elif compute_method == 'geo':
  109. # do_partial = partial(wrapper_cw_geo, node_label, edge_label, weight)
  110. #
  111. # for i, j, kernel in tqdm(
  112. # pool.imap_unordered(do_partial, itr, chunksize),
  113. # desc='calculating kernels',
  114. # file=sys.stdout):
  115. # Kmatrix[i][j] = kernel
  116. # Kmatrix[j][i] = kernel
  117. # pool.close()
  118. # pool.join()
  119. # # ---- direct running, normally use single CPU core. ----
  120. # # direct product graph method - exponential
  121. # itr = combinations_with_replacement(range(0, len(Gn)), 2)
  122. # if compute_method == 'exp':
  123. # for i, j in tqdm(itr, desc='calculating kernels', file=sys.stdout):
  124. # Kmatrix[i][j] = _commonwalkkernel_exp(Gn[i], Gn[j], node_label,
  125. # edge_label, weight)
  126. # Kmatrix[j][i] = Kmatrix[i][j]
  127. #
  128. # # direct product graph method - geometric
  129. # elif compute_method == 'geo':
  130. # for i, j in tqdm(itr, desc='calculating kernels', file=sys.stdout):
  131. # Kmatrix[i][j] = _commonwalkkernel_geo(Gn[i], Gn[j], node_label,
  132. # edge_label, weight)
  133. # Kmatrix[j][i] = Kmatrix[i][j]
  134. # # search all paths use brute force.
  135. # elif compute_method == 'brute':
  136. # n = int(n)
  137. # # get all paths of all graphs before calculating kernels to save time, but this may cost a lot of memory for large dataset.
  138. # all_walks = [
  139. # find_all_walks_until_length(Gn[i], n, node_label, edge_label)
  140. # for i in range(0, len(Gn))
  141. # ]
  142. #
  143. # for i in range(0, len(Gn)):
  144. # for j in range(i, len(Gn)):
  145. # Kmatrix[i][j] = _commonwalkkernel_brute(
  146. # all_walks[i],
  147. # all_walks[j],
  148. # node_label=node_label,
  149. # edge_label=edge_label)
  150. # Kmatrix[j][i] = Kmatrix[i][j]
  151. run_time = time.time() - start_time
  152. print(
  153. "\n --- kernel matrix of common walk kernel of size %d built in %s seconds ---"
  154. % (len(Gn), run_time))
  155. return Kmatrix, run_time, idx
  156. def _commonwalkkernel_exp(g1, g2, node_label, edge_label, beta):
  157. """Calculate walk graph kernels up to n between 2 graphs using exponential
  158. series.
  159. Parameters
  160. ----------
  161. Gn : List of NetworkX graph
  162. List of graphs between which the kernels are calculated.
  163. node_label : string
  164. Node attribute used as label.
  165. edge_label : string
  166. Edge attribute used as label.
  167. beta : integer
  168. Weight.
  169. ij : tuple of integer
  170. Index of graphs between which the kernel is computed.
  171. Return
  172. ------
  173. kernel : float
  174. The common walk Kernel between 2 graphs.
  175. """
  176. # get tensor product / direct product
  177. gp = direct_product(g1, g2, node_label, edge_label)
  178. # return 0 if the direct product graph have no more than 1 node.
  179. if nx.number_of_nodes(gp) < 2:
  180. return 0
  181. A = nx.adjacency_matrix(gp).todense()
  182. # print(A)
  183. # from matplotlib import pyplot as plt
  184. # nx.draw_networkx(G1)
  185. # plt.show()
  186. # nx.draw_networkx(G2)
  187. # plt.show()
  188. # nx.draw_networkx(gp)
  189. # plt.show()
  190. # print(G1.nodes(data=True))
  191. # print(G2.nodes(data=True))
  192. # print(gp.nodes(data=True))
  193. # print(gp.edges(data=True))
  194. ew, ev = np.linalg.eig(A)
  195. # print('ew: ', ew)
  196. # print(ev)
  197. # T = np.matrix(ev)
  198. # print('T: ', T)
  199. # T = ev.I
  200. D = np.zeros((len(ew), len(ew)))
  201. for i in range(len(ew)):
  202. D[i][i] = np.exp(beta * ew[i])
  203. # print('D: ', D)
  204. # print('hshs: ', T.I * D * T)
  205. # print(np.exp(-2))
  206. # print(D)
  207. # print(np.exp(weight * D))
  208. # print(ev)
  209. # print(np.linalg.inv(ev))
  210. exp_D = ev * D * ev.T
  211. # print(exp_D)
  212. # print(np.exp(weight * A))
  213. # print('-------')
  214. return exp_D.sum()
  215. def wrapper_cw_exp(node_label, edge_label, beta, itr):
  216. i = itr[0]
  217. j = itr[1]
  218. return i, j, _commonwalkkernel_exp(G_gn[i], G_gn[j], node_label, edge_label, beta)
  219. def _commonwalkkernel_geo(g1, g2, node_label, edge_label, gamma):
  220. """Calculate common walk graph kernels up to n between 2 graphs using
  221. geometric series.
  222. Parameters
  223. ----------
  224. Gn : List of NetworkX graph
  225. List of graphs between which the kernels are calculated.
  226. node_label : string
  227. Node attribute used as label.
  228. edge_label : string
  229. Edge attribute used as label.
  230. gamma: integer
  231. Weight.
  232. ij : tuple of integer
  233. Index of graphs between which the kernel is computed.
  234. Return
  235. ------
  236. kernel : float
  237. The common walk Kernel between 2 graphs.
  238. """
  239. # get tensor product / direct product
  240. gp = direct_product(g1, g2, node_label, edge_label)
  241. # return 0 if the direct product graph have no more than 1 node.
  242. if nx.number_of_nodes(gp) < 2:
  243. return 0
  244. A = nx.adjacency_matrix(gp).todense()
  245. mat = np.identity(len(A)) - gamma * A
  246. # try:
  247. return mat.I.sum()
  248. # except np.linalg.LinAlgError:
  249. # return np.nan
  250. def wrapper_cw_geo(node_label, edge_label, gama, itr):
  251. i = itr[0]
  252. j = itr[1]
  253. return i, j, _commonwalkkernel_geo(G_gn[i], G_gn[j], node_label, edge_label, gama)
  254. def _commonwalkkernel_brute(walks1,
  255. walks2,
  256. node_label='atom',
  257. edge_label='bond_type',
  258. labeled=True):
  259. """Calculate walk graph kernels up to n between 2 graphs.
  260. Parameters
  261. ----------
  262. walks1, walks2 : list
  263. List of walks in 2 graphs, where for unlabeled graphs, each walk is
  264. represented by a list of nodes; while for labeled graphs, each walk is
  265. represented by a string consists of labels of nodes and edges on that
  266. walk.
  267. node_label : string
  268. node attribute used as label. The default node label is atom.
  269. edge_label : string
  270. edge attribute used as label. The default edge label is bond_type.
  271. labeled : boolean
  272. Whether the graphs are labeled. The default is True.
  273. Return
  274. ------
  275. kernel : float
  276. Treelet Kernel between 2 graphs.
  277. """
  278. counts_walks1 = dict(Counter(walks1))
  279. counts_walks2 = dict(Counter(walks2))
  280. all_walks = list(set(walks1 + walks2))
  281. vector1 = [(counts_walks1[walk] if walk in walks1 else 0)
  282. for walk in all_walks]
  283. vector2 = [(counts_walks2[walk] if walk in walks2 else 0)
  284. for walk in all_walks]
  285. kernel = np.dot(vector1, vector2)
  286. return kernel
  287. # this method find walks repetively, it could be faster.
  288. def find_all_walks_until_length(G,
  289. length,
  290. node_label='atom',
  291. edge_label='bond_type',
  292. labeled=True):
  293. """Find all walks with a certain maximum length in a graph.
  294. A recursive depth first search is applied.
  295. Parameters
  296. ----------
  297. G : NetworkX graphs
  298. The graph in which walks are searched.
  299. length : integer
  300. The maximum length of walks.
  301. node_label : string
  302. node attribute used as label. The default node label is atom.
  303. edge_label : string
  304. edge attribute used as label. The default edge label is bond_type.
  305. labeled : boolean
  306. Whether the graphs are labeled. The default is True.
  307. Return
  308. ------
  309. walk : list
  310. List of walks retrieved, where for unlabeled graphs, each walk is
  311. represented by a list of nodes; while for labeled graphs, each walk
  312. is represented by a string consists of labels of nodes and edges on
  313. that walk.
  314. """
  315. all_walks = []
  316. # @todo: in this way, the time complexity is close to N(d^n+d^(n+1)+...+1), which could be optimized to O(Nd^n)
  317. for i in range(0, length + 1):
  318. new_walks = find_all_walks(G, i)
  319. if new_walks == []:
  320. break
  321. all_walks.extend(new_walks)
  322. if labeled == True: # convert paths to strings
  323. walk_strs = []
  324. for walk in all_walks:
  325. strlist = [
  326. G.node[node][node_label] +
  327. G[node][walk[walk.index(node) + 1]][edge_label]
  328. for node in walk[:-1]
  329. ]
  330. walk_strs.append(''.join(strlist) + G.node[walk[-1]][node_label])
  331. return walk_strs
  332. return all_walks
  333. def find_walks(G, source_node, length):
  334. """Find all walks with a certain length those start from a source node. A
  335. recursive depth first search is applied.
  336. Parameters
  337. ----------
  338. G : NetworkX graphs
  339. The graph in which walks are searched.
  340. source_node : integer
  341. The number of the node from where all walks start.
  342. length : integer
  343. The length of walks.
  344. Return
  345. ------
  346. walk : list of list
  347. List of walks retrieved, where each walk is represented by a list of
  348. nodes.
  349. """
  350. return [[source_node]] if length == 0 else \
  351. [[source_node] + walk for neighbor in G[source_node]
  352. for walk in find_walks(G, neighbor, length - 1)]
  353. def find_all_walks(G, length):
  354. """Find all walks with a certain length in a graph. A recursive depth first
  355. search is applied.
  356. Parameters
  357. ----------
  358. G : NetworkX graphs
  359. The graph in which walks are searched.
  360. length : integer
  361. The length of walks.
  362. Return
  363. ------
  364. walk : list of list
  365. List of walks retrieved, where each walk is represented by a list of
  366. nodes.
  367. """
  368. all_walks = []
  369. for node in G:
  370. all_walks.extend(find_walks(G, node, length))
  371. # The following process is not carried out according to the original article
  372. # all_paths_r = [ path[::-1] for path in all_paths ]
  373. # # For each path, two presentation are retrieved from its two extremities. Remove one of them.
  374. # for idx, path in enumerate(all_paths[:-1]):
  375. # for path2 in all_paths_r[idx+1::]:
  376. # if path == path2:
  377. # all_paths[idx] = []
  378. # break
  379. # return list(filter(lambda a: a != [], all_paths))
  380. return all_walks

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