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.

spKernel.py 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. """
  2. @author: linlin
  3. @references: Borgwardt KM, Kriegel HP. Shortest-path kernels on graphs. InData
  4. Mining, Fifth IEEE International Conference on 2005 Nov 27 (pp. 8-pp). IEEE.
  5. """
  6. import sys
  7. import time
  8. from itertools import combinations_with_replacement, product
  9. from functools import partial
  10. from joblib import Parallel, delayed
  11. from multiprocessing import Pool
  12. from tqdm import tqdm
  13. import networkx as nx
  14. import numpy as np
  15. from pygraph.utils.utils import getSPGraph
  16. from pygraph.utils.graphdataset import get_dataset_attributes
  17. sys.path.insert(0, "../")
  18. def spkernel(*args,
  19. node_label='atom',
  20. edge_weight=None,
  21. node_kernels=None,
  22. n_jobs=None):
  23. """Calculate shortest-path kernels 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_weight : string
  34. Edge attribute name corresponding to the edge weight.
  35. node_kernels: dict
  36. A dictionary of kernel functions for nodes, including 3 items: 'symb'
  37. for symbolic node labels, 'nsymb' for non-symbolic node labels, 'mix'
  38. for both labels. The first 2 functions take two node labels as
  39. parameters, and the 'mix' function takes 4 parameters, a symbolic and a
  40. non-symbolic label for each the two nodes. Each label is in form of 2-D
  41. dimension array (n_samples, n_features). Each function returns an
  42. number as the kernel value. Ignored when nodes are unlabeled.
  43. Return
  44. ------
  45. Kmatrix : Numpy matrix
  46. Kernel matrix, each element of which is the sp kernel between 2 praphs.
  47. """
  48. # pre-process
  49. Gn = args[0] if len(args) == 1 else [args[0], args[1]]
  50. weight = None
  51. if edge_weight is None:
  52. print('\n None edge weight specified. Set all weight to 1.\n')
  53. else:
  54. try:
  55. some_weight = list(
  56. nx.get_edge_attributes(Gn[0], edge_weight).values())[0]
  57. if isinstance(some_weight, (float, int)):
  58. weight = edge_weight
  59. else:
  60. print(
  61. '\n Edge weight with name %s is not float or integer. Set all weight to 1.\n'
  62. % edge_weight)
  63. except:
  64. print(
  65. '\n Edge weight with name "%s" is not found in the edge attributes. Set all weight to 1.\n'
  66. % edge_weight)
  67. ds_attrs = get_dataset_attributes(
  68. Gn,
  69. attr_names=['node_labeled', 'node_attr_dim', 'is_directed'],
  70. node_label=node_label)
  71. # remove graphs with no edges, as no sp can be found in their structures, so the kernel between such a graph and itself will be zero.
  72. len_gn = len(Gn)
  73. Gn = [(idx, G) for idx, G in enumerate(Gn) if nx.number_of_edges(G) != 0]
  74. idx = [G[0] for G in Gn]
  75. Gn = [G[1] for G in Gn]
  76. if len(Gn) != len_gn:
  77. print('\n %d graphs are removed as they don\'t contain edges.\n' %
  78. (len_gn - len(Gn)))
  79. start_time = time.time()
  80. pool = Pool(n_jobs)
  81. # get shortest path graphs of Gn
  82. getsp_partial = partial(wrap_getSPGraph, Gn, weight)
  83. if len(Gn) < 1000 * n_jobs:
  84. # # use default chunksize as pool.map when iterable is less than 100
  85. # chunksize, extra = divmod(len(Gn), n_jobs * 4)
  86. # if extra:
  87. # chunksize += 1
  88. chunksize = int(len(Gn) / n_jobs) + 1
  89. else:
  90. chunksize = 1000
  91. # chunksize = 300 # int(len(list(itr)) / n_jobs)
  92. for i, g in tqdm(
  93. pool.imap_unordered(getsp_partial, range(0, len(Gn)), chunksize),
  94. desc='getting sp graphs', file=sys.stdout):
  95. Gn[i] = g
  96. pool.close()
  97. pool.join()
  98. # # ---- direct running, normally use single CPU core. ----
  99. # for i in tqdm(range(len(Gn)), desc='getting sp graphs', file=sys.stdout):
  100. # i, Gn[i] = wrap_getSPGraph(Gn, weight, i)
  101. # # ---- use pool.map to parallel ----
  102. # result_sp = pool.map(getsp_partial, range(0, len(Gn)))
  103. # for i in result_sp:
  104. # Gn[i[0]] = i[1]
  105. # or
  106. # getsp_partial = partial(wrap_getSPGraph, Gn, weight)
  107. # for i, g in tqdm(
  108. # pool.map(getsp_partial, range(0, len(Gn))),
  109. # desc='getting sp graphs',
  110. # file=sys.stdout):
  111. # Gn[i] = g
  112. # # ---- only for the Fast Computation of Shortest Path Kernel (FCSP)
  113. # sp_ml = [0] * len(Gn) # shortest path matrices
  114. # for i in result_sp:
  115. # sp_ml[i[0]] = i[1]
  116. # edge_x_g = [[] for i in range(len(sp_ml))]
  117. # edge_y_g = [[] for i in range(len(sp_ml))]
  118. # edge_w_g = [[] for i in range(len(sp_ml))]
  119. # for idx, item in enumerate(sp_ml):
  120. # for i1 in range(len(item)):
  121. # for i2 in range(i1 + 1, len(item)):
  122. # if item[i1, i2] != np.inf:
  123. # edge_x_g[idx].append(i1)
  124. # edge_y_g[idx].append(i2)
  125. # edge_w_g[idx].append(item[i1, i2])
  126. # print(len(edge_x_g[0]))
  127. # print(len(edge_y_g[0]))
  128. # print(len(edge_w_g[0]))
  129. Kmatrix = np.zeros((len(Gn), len(Gn)))
  130. # ---- use pool.imap_unordered to parallel and track progress. ----
  131. pool = Pool(n_jobs)
  132. do_partial = partial(spkernel_do, Gn, ds_attrs, node_label, node_kernels)
  133. itr = combinations_with_replacement(range(0, len(Gn)), 2)
  134. len_itr = int(len(Gn) * (len(Gn) + 1) / 2)
  135. if len_itr < 1000 * n_jobs:
  136. chunksize = int(len_itr / n_jobs) + 1
  137. else:
  138. chunksize = 1000
  139. for i, j, kernel in tqdm(
  140. pool.imap_unordered(do_partial, itr, chunksize),
  141. desc='calculating kernels',
  142. file=sys.stdout):
  143. Kmatrix[i][j] = kernel
  144. Kmatrix[j][i] = kernel
  145. pool.close()
  146. pool.join()
  147. # # ---- use pool.map to parallel. ----
  148. # # result_perf = pool.map(do_partial, itr)
  149. # do_partial = partial(spkernel_do, Gn, ds_attrs, node_label, node_kernels)
  150. # itr = combinations_with_replacement(range(0, len(Gn)), 2)
  151. # for i, j, kernel in tqdm(
  152. # pool.map(do_partial, itr), desc='calculating kernels',
  153. # file=sys.stdout):
  154. # Kmatrix[i][j] = kernel
  155. # Kmatrix[j][i] = kernel
  156. # pool.close()
  157. # pool.join()
  158. # # ---- use joblib.Parallel to parallel and track progress. ----
  159. # result_perf = Parallel(
  160. # n_jobs=n_jobs, verbose=10)(
  161. # delayed(do_partial)(ij)
  162. # for ij in combinations_with_replacement(range(0, len(Gn)), 2))
  163. # result_perf = [
  164. # do_partial(ij)
  165. # for ij in combinations_with_replacement(range(0, len(Gn)), 2)
  166. # ]
  167. # for i in result_perf:
  168. # Kmatrix[i[0]][i[1]] = i[2]
  169. # Kmatrix[i[1]][i[0]] = i[2]
  170. # # ---- direct running, normally use single CPU core. ----
  171. # itr = combinations_with_replacement(range(0, len(Gn)), 2)
  172. # for gs in tqdm(itr, desc='calculating kernels', file=sys.stdout):
  173. # i, j, kernel = spkernel_do(Gn, ds_attrs, node_label, node_kernels, gs)
  174. # Kmatrix[i][j] = kernel
  175. # Kmatrix[j][i] = kernel
  176. run_time = time.time() - start_time
  177. print(
  178. "\n --- shortest path kernel matrix of size %d built in %s seconds ---"
  179. % (len(Gn), run_time))
  180. return Kmatrix, run_time, idx
  181. def spkernel_do(Gn, ds_attrs, node_label, node_kernels, ij):
  182. i = ij[0]
  183. j = ij[1]
  184. g1 = Gn[i]
  185. g2 = Gn[j]
  186. kernel = 0
  187. try:
  188. # compute shortest path matrices first, method borrowed from FCSP.
  189. if ds_attrs['node_labeled']:
  190. # node symb and non-synb labeled
  191. if ds_attrs['node_attr_dim'] > 0:
  192. kn = node_kernels['mix']
  193. vk_dict = {} # shortest path matrices dict
  194. for n1, n2 in product(
  195. g1.nodes(data=True), g2.nodes(data=True)):
  196. vk_dict[(n1[0], n2[0])] = kn(
  197. n1[1][node_label], n2[1][node_label],
  198. [n1[1]['attributes']], [n2[1]['attributes']])
  199. # node symb labeled
  200. else:
  201. kn = node_kernels['symb']
  202. vk_dict = {} # shortest path matrices dict
  203. for n1 in g1.nodes(data=True):
  204. for n2 in g2.nodes(data=True):
  205. vk_dict[(n1[0], n2[0])] = kn(n1[1][node_label],
  206. n2[1][node_label])
  207. else:
  208. # node non-synb labeled
  209. if ds_attrs['node_attr_dim'] > 0:
  210. kn = node_kernels['nsymb']
  211. vk_dict = {} # shortest path matrices dict
  212. for n1 in g1.nodes(data=True):
  213. for n2 in g2.nodes(data=True):
  214. vk_dict[(n1[0], n2[0])] = kn([n1[1]['attributes']],
  215. [n2[1]['attributes']])
  216. # node unlabeled
  217. else:
  218. for e1, e2 in product(
  219. g1.edges(data=True), g2.edges(data=True)):
  220. if e1[2]['cost'] == e2[2]['cost']:
  221. kernel += 1
  222. return i, j, kernel
  223. # compute graph kernels
  224. if ds_attrs['is_directed']:
  225. for e1, e2 in product(g1.edges(data=True), g2.edges(data=True)):
  226. if e1[2]['cost'] == e2[2]['cost']:
  227. nk11, nk22 = vk_dict[(e1[0], e2[0])], vk_dict[(e1[1],
  228. e2[1])]
  229. kn1 = nk11 * nk22
  230. kernel += kn1
  231. else:
  232. for e1, e2 in product(g1.edges(data=True), g2.edges(data=True)):
  233. if e1[2]['cost'] == e2[2]['cost']:
  234. # each edge walk is counted twice, starting from both its extreme nodes.
  235. nk11, nk12, nk21, nk22 = vk_dict[(e1[0], e2[0])], vk_dict[(
  236. e1[0], e2[1])], vk_dict[(e1[1],
  237. e2[0])], vk_dict[(e1[1],
  238. e2[1])]
  239. kn1 = nk11 * nk22
  240. kn2 = nk12 * nk21
  241. kernel += kn1 + kn2
  242. # # ---- exact implementation of the Fast Computation of Shortest Path Kernel (FCSP), reference [2], sadly it is slower than the current implementation
  243. # # compute vertex kernels
  244. # try:
  245. # vk_mat = np.zeros((nx.number_of_nodes(g1),
  246. # nx.number_of_nodes(g2)))
  247. # g1nl = enumerate(g1.nodes(data=True))
  248. # g2nl = enumerate(g2.nodes(data=True))
  249. # for i1, n1 in g1nl:
  250. # for i2, n2 in g2nl:
  251. # vk_mat[i1][i2] = kn(
  252. # n1[1][node_label], n2[1][node_label],
  253. # [n1[1]['attributes']], [n2[1]['attributes']])
  254. # range1 = range(0, len(edge_w_g[i]))
  255. # range2 = range(0, len(edge_w_g[j]))
  256. # for i1 in range1:
  257. # x1 = edge_x_g[i][i1]
  258. # y1 = edge_y_g[i][i1]
  259. # w1 = edge_w_g[i][i1]
  260. # for i2 in range2:
  261. # x2 = edge_x_g[j][i2]
  262. # y2 = edge_y_g[j][i2]
  263. # w2 = edge_w_g[j][i2]
  264. # ke = (w1 == w2)
  265. # if ke > 0:
  266. # kn1 = vk_mat[x1][x2] * vk_mat[y1][y2]
  267. # kn2 = vk_mat[x1][y2] * vk_mat[y1][x2]
  268. # kernel += kn1 + kn2
  269. except KeyError: # missing labels or attributes
  270. pass
  271. return i, j, kernel
  272. def wrap_getSPGraph(Gn, weight, i):
  273. return i, getSPGraph(Gn[i], edge_weight=weight)
  274. # return i, nx.floyd_warshall_numpy(Gn[i], weight=weight)

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