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,
  72. # so the kernel between such a graph and itself will be zero.
  73. len_gn = len(Gn)
  74. Gn = [(idx, G) for idx, G in enumerate(Gn) if nx.number_of_edges(G) != 0]
  75. idx = [G[0] for G in Gn]
  76. Gn = [G[1] for G in Gn]
  77. if len(Gn) != len_gn:
  78. print('\n %d graphs are removed as they don\'t contain edges.\n' %
  79. (len_gn - len(Gn)))
  80. start_time = time.time()
  81. pool = Pool(n_jobs)
  82. # get shortest path graphs of Gn
  83. getsp_partial = partial(wrap_getSPGraph, Gn, weight)
  84. if len(Gn) < 1000 * n_jobs:
  85. # # use default chunksize as pool.map when iterable is less than 100
  86. # chunksize, extra = divmod(len(Gn), n_jobs * 4)
  87. # if extra:
  88. # chunksize += 1
  89. chunksize = int(len(Gn) / n_jobs) + 1
  90. else:
  91. chunksize = 1000
  92. # chunksize = 300 # int(len(list(itr)) / n_jobs)
  93. for i, g in tqdm(
  94. pool.imap_unordered(getsp_partial, range(0, len(Gn)), chunksize),
  95. desc='getting sp graphs', file=sys.stdout):
  96. Gn[i] = g
  97. pool.close()
  98. pool.join()
  99. # # ---- direct running, normally use single CPU core. ----
  100. # for i in tqdm(range(len(Gn)), desc='getting sp graphs', file=sys.stdout):
  101. # i, Gn[i] = wrap_getSPGraph(Gn, weight, i)
  102. # # ---- use pool.map to parallel ----
  103. # result_sp = pool.map(getsp_partial, range(0, len(Gn)))
  104. # for i in result_sp:
  105. # Gn[i[0]] = i[1]
  106. # or
  107. # getsp_partial = partial(wrap_getSPGraph, Gn, weight)
  108. # for i, g in tqdm(
  109. # pool.map(getsp_partial, range(0, len(Gn))),
  110. # desc='getting sp graphs',
  111. # file=sys.stdout):
  112. # Gn[i] = g
  113. # # ---- only for the Fast Computation of Shortest Path Kernel (FCSP)
  114. # sp_ml = [0] * len(Gn) # shortest path matrices
  115. # for i in result_sp:
  116. # sp_ml[i[0]] = i[1]
  117. # edge_x_g = [[] for i in range(len(sp_ml))]
  118. # edge_y_g = [[] for i in range(len(sp_ml))]
  119. # edge_w_g = [[] for i in range(len(sp_ml))]
  120. # for idx, item in enumerate(sp_ml):
  121. # for i1 in range(len(item)):
  122. # for i2 in range(i1 + 1, len(item)):
  123. # if item[i1, i2] != np.inf:
  124. # edge_x_g[idx].append(i1)
  125. # edge_y_g[idx].append(i2)
  126. # edge_w_g[idx].append(item[i1, i2])
  127. # print(len(edge_x_g[0]))
  128. # print(len(edge_y_g[0]))
  129. # print(len(edge_w_g[0]))
  130. Kmatrix = np.zeros((len(Gn), len(Gn)))
  131. # ---- use pool.imap_unordered to parallel and track progress. ----
  132. pool = Pool(n_jobs)
  133. do_partial = partial(spkernel_do, Gn, ds_attrs, node_label, node_kernels)
  134. itr = combinations_with_replacement(range(0, len(Gn)), 2)
  135. len_itr = int(len(Gn) * (len(Gn) + 1) / 2)
  136. if len_itr < 1000 * n_jobs:
  137. chunksize = int(len_itr / n_jobs) + 1
  138. else:
  139. chunksize = 1000
  140. for i, j, kernel in tqdm(
  141. pool.imap_unordered(do_partial, itr, chunksize),
  142. desc='calculating kernels',
  143. file=sys.stdout):
  144. Kmatrix[i][j] = kernel
  145. Kmatrix[j][i] = kernel
  146. pool.close()
  147. pool.join()
  148. # # ---- use pool.map to parallel. ----
  149. # # result_perf = pool.map(do_partial, itr)
  150. # do_partial = partial(spkernel_do, Gn, ds_attrs, node_label, node_kernels)
  151. # itr = combinations_with_replacement(range(0, len(Gn)), 2)
  152. # for i, j, kernel in tqdm(
  153. # pool.map(do_partial, itr), desc='calculating kernels',
  154. # file=sys.stdout):
  155. # Kmatrix[i][j] = kernel
  156. # Kmatrix[j][i] = kernel
  157. # pool.close()
  158. # pool.join()
  159. # # ---- use joblib.Parallel to parallel and track progress. ----
  160. # result_perf = Parallel(
  161. # n_jobs=n_jobs, verbose=10)(
  162. # delayed(do_partial)(ij)
  163. # for ij in combinations_with_replacement(range(0, len(Gn)), 2))
  164. # result_perf = [
  165. # do_partial(ij)
  166. # for ij in combinations_with_replacement(range(0, len(Gn)), 2)
  167. # ]
  168. # for i in result_perf:
  169. # Kmatrix[i[0]][i[1]] = i[2]
  170. # Kmatrix[i[1]][i[0]] = i[2]
  171. # # ---- direct running, normally use single CPU core. ----
  172. # itr = combinations_with_replacement(range(0, len(Gn)), 2)
  173. # for gs in tqdm(itr, desc='calculating kernels', file=sys.stdout):
  174. # i, j, kernel = spkernel_do(Gn, ds_attrs, node_label, node_kernels, gs)
  175. # Kmatrix[i][j] = kernel
  176. # Kmatrix[j][i] = kernel
  177. run_time = time.time() - start_time
  178. print(
  179. "\n --- shortest path kernel matrix of size %d built in %s seconds ---"
  180. % (len(Gn), run_time))
  181. return Kmatrix, run_time, idx
  182. def spkernel_do(Gn, ds_attrs, node_label, node_kernels, ij):
  183. i = ij[0]
  184. j = ij[1]
  185. g1 = Gn[i]
  186. g2 = Gn[j]
  187. kernel = 0
  188. # try:
  189. # compute shortest path matrices first, method borrowed from FCSP.
  190. if ds_attrs['node_labeled']:
  191. # node symb and non-synb labeled
  192. if ds_attrs['node_attr_dim'] > 0:
  193. kn = node_kernels['mix']
  194. vk_dict = {} # shortest path matrices dict
  195. for n1, n2 in product(
  196. g1.nodes(data=True), g2.nodes(data=True)):
  197. vk_dict[(n1[0], n2[0])] = kn(
  198. n1[1][node_label], n2[1][node_label],
  199. n1[1]['attributes'], n2[1]['attributes'])
  200. # node symb labeled
  201. else:
  202. kn = node_kernels['symb']
  203. vk_dict = {} # shortest path matrices dict
  204. for n1 in g1.nodes(data=True):
  205. for n2 in g2.nodes(data=True):
  206. vk_dict[(n1[0], n2[0])] = kn(n1[1][node_label],
  207. n2[1][node_label])
  208. else:
  209. # node non-synb labeled
  210. if ds_attrs['node_attr_dim'] > 0:
  211. kn = node_kernels['nsymb']
  212. vk_dict = {} # shortest path matrices dict
  213. for n1 in g1.nodes(data=True):
  214. for n2 in g2.nodes(data=True):
  215. vk_dict[(n1[0], n2[0])] = kn(n1[1]['attributes'],
  216. n2[1]['attributes'])
  217. # node unlabeled
  218. else:
  219. for e1, e2 in product(
  220. g1.edges(data=True), g2.edges(data=True)):
  221. if e1[2]['cost'] == e2[2]['cost']:
  222. kernel += 1
  223. return i, j, kernel
  224. # compute graph kernels
  225. if ds_attrs['is_directed']:
  226. for e1, e2 in product(g1.edges(data=True), g2.edges(data=True)):
  227. if e1[2]['cost'] == e2[2]['cost']:
  228. nk11, nk22 = vk_dict[(e1[0], e2[0])], vk_dict[(e1[1],
  229. e2[1])]
  230. kn1 = nk11 * nk22
  231. kernel += kn1
  232. else:
  233. for e1, e2 in product(g1.edges(data=True), g2.edges(data=True)):
  234. if e1[2]['cost'] == e2[2]['cost']:
  235. # each edge walk is counted twice, starting from both its extreme nodes.
  236. nk11, nk12, nk21, nk22 = vk_dict[(e1[0], e2[0])], vk_dict[(
  237. e1[0], e2[1])], vk_dict[(e1[1],
  238. e2[0])], vk_dict[(e1[1],
  239. e2[1])]
  240. kn1 = nk11 * nk22
  241. kn2 = nk12 * nk21
  242. kernel += kn1 + kn2
  243. # # ---- exact implementation of the Fast Computation of Shortest Path Kernel (FCSP), reference [2], sadly it is slower than the current implementation
  244. # # compute vertex kernels
  245. # try:
  246. # vk_mat = np.zeros((nx.number_of_nodes(g1),
  247. # nx.number_of_nodes(g2)))
  248. # g1nl = enumerate(g1.nodes(data=True))
  249. # g2nl = enumerate(g2.nodes(data=True))
  250. # for i1, n1 in g1nl:
  251. # for i2, n2 in g2nl:
  252. # vk_mat[i1][i2] = kn(
  253. # n1[1][node_label], n2[1][node_label],
  254. # [n1[1]['attributes']], [n2[1]['attributes']])
  255. # range1 = range(0, len(edge_w_g[i]))
  256. # range2 = range(0, len(edge_w_g[j]))
  257. # for i1 in range1:
  258. # x1 = edge_x_g[i][i1]
  259. # y1 = edge_y_g[i][i1]
  260. # w1 = edge_w_g[i][i1]
  261. # for i2 in range2:
  262. # x2 = edge_x_g[j][i2]
  263. # y2 = edge_y_g[j][i2]
  264. # w2 = edge_w_g[j][i2]
  265. # ke = (w1 == w2)
  266. # if ke > 0:
  267. # kn1 = vk_mat[x1][x2] * vk_mat[y1][y2]
  268. # kn2 = vk_mat[x1][y2] * vk_mat[y1][x2]
  269. # kernel += kn1 + kn2
  270. # except KeyError: # missing labels or attributes
  271. # pass
  272. return i, j, kernel
  273. def wrap_getSPGraph(Gn, weight, i):
  274. return i, getSPGraph(Gn[i], edge_weight=weight)
  275. # return i, nx.floyd_warshall_numpy(Gn[i], weight=weight)

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