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

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

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