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

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

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