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.

xp_fit_method.py 28 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Tue Jan 14 15:39:29 2020
  5. @author: ljia
  6. """
  7. import numpy as np
  8. import random
  9. import csv
  10. from shutil import copyfile
  11. import networkx as nx
  12. import matplotlib.pyplot as plt
  13. import os
  14. from gklearn.utils.graphfiles import loadDataset, loadGXL, saveGXL
  15. from gklearn.preimage.test_k_closest_graphs import median_on_k_closest_graphs, reform_attributes
  16. from gklearn.preimage.utils import get_same_item_indices, kernel_distance_matrix, compute_kernel
  17. from gklearn.preimage.find_best_k import getRelations
  18. def get_dataset(ds_name):
  19. if ds_name == 'Letter-high': # node non-symb
  20. dataset = 'cpp_ext/data/collections/Letter.xml'
  21. graph_dir = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/data/datasets/Letter/HIGH/'
  22. Gn, y_all = loadDataset(dataset, extra_params=graph_dir)
  23. for G in Gn:
  24. reform_attributes(G)
  25. elif ds_name == 'Fingerprint':
  26. # dataset = 'cpp_ext/data/collections/Fingerprint.xml'
  27. # graph_dir = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/generated_datsets/Fingerprint/node_attrs/'
  28. # Gn, y_all = loadDataset(dataset, extra_params=graph_dir)
  29. # for G in Gn:
  30. # reform_attributes(G)
  31. dataset = '../../datasets/Fingerprint/Fingerprint_A.txt'
  32. graph_dir = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/generated_datsets/Fingerprint/node_attrs/'
  33. Gn, y_all = loadDataset(dataset)
  34. elif ds_name == 'SYNTHETIC':
  35. pass
  36. elif ds_name == 'SYNTHETICnew':
  37. dataset = '../../datasets/SYNTHETICnew/SYNTHETICnew_A.txt'
  38. graph_dir = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/generated_datsets/SYNTHETICnew'
  39. # dataset = '../../datasets/Letter-high/Letter-high_A.txt'
  40. # graph_dir = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/data/datasets/Letter/HIGH/'
  41. Gn, y_all = loadDataset(dataset)
  42. elif ds_name == 'Synthie':
  43. pass
  44. elif ds_name == 'COIL-RAG':
  45. pass
  46. elif ds_name == 'COLORS-3':
  47. pass
  48. elif ds_name == 'FRANKENSTEIN':
  49. pass
  50. return Gn, y_all, graph_dir
  51. def init_output_file(ds_name, gkernel, fit_method, dir_output):
  52. # fn_output_detail = 'results_detail.' + ds_name + '.' + gkernel + '.' + fit_method + '.csv'
  53. fn_output_detail = 'results_detail.' + ds_name + '.' + gkernel + '.csv'
  54. f_detail = open(dir_output + fn_output_detail, 'a')
  55. csv.writer(f_detail).writerow(['dataset', 'graph kernel', 'edit cost',
  56. 'GED method', 'attr distance', 'fit method', 'k',
  57. 'target', 'repeat', 'SOD SM', 'SOD GM', 'dis_k SM', 'dis_k GM',
  58. 'min dis_k gi', 'SOD SM -> GM', 'dis_k SM -> GM', 'dis_k gi -> SM',
  59. 'dis_k gi -> GM', 'fitting time', 'generating time', 'total time',
  60. 'median set'])
  61. f_detail.close()
  62. # fn_output_summary = 'results_summary.' + ds_name + '.' + gkernel + '.' + fit_method + '.csv'
  63. fn_output_summary = 'results_summary.' + ds_name + '.' + gkernel + '.csv'
  64. f_summary = open(dir_output + fn_output_summary, 'a')
  65. csv.writer(f_summary).writerow(['dataset', 'graph kernel', 'edit cost',
  66. 'GED method', 'attr distance', 'fit method', 'k',
  67. 'target', 'SOD SM', 'SOD GM', 'dis_k SM', 'dis_k GM',
  68. 'min dis_k gi', 'SOD SM -> GM', 'dis_k SM -> GM', 'dis_k gi -> SM',
  69. 'dis_k gi -> GM', 'fitting time', 'generating time', 'total time',
  70. '# SOD SM -> GM', '# dis_k SM -> GM',
  71. '# dis_k gi -> SM', '# dis_k gi -> GM', 'repeats better SOD SM -> GM',
  72. 'repeats better dis_k SM -> GM', 'repeats better dis_k gi -> SM',
  73. 'repeats better dis_k gi -> GM'])
  74. f_summary.close()
  75. return fn_output_detail, fn_output_summary
  76. def xp_fit_method_for_non_symbolic(parameters, save_results=True, initial_solutions=1,
  77. Gn_data=None, k_dis_data=None, Kmatrix=None):
  78. # 1. set parameters.
  79. print('1. setting parameters...')
  80. ds_name = parameters['ds_name']
  81. gkernel = parameters['gkernel']
  82. edit_cost_name = parameters['edit_cost_name']
  83. ged_method = parameters['ged_method']
  84. attr_distance = parameters['attr_distance']
  85. fit_method = parameters['fit_method']
  86. node_label = None
  87. edge_label = None
  88. dir_output = 'results/xp_fit_method/'
  89. # 2. get dataset.
  90. print('2. getting dataset...')
  91. if Gn_data is None:
  92. Gn, y_all, graph_dir = get_dataset(ds_name)
  93. else:
  94. Gn = Gn_data[0]
  95. y_all = Gn_data[1]
  96. graph_dir = Gn_data[2]
  97. # 3. compute kernel distance matrix.
  98. print('3. computing kernel distance matrix...')
  99. if k_dis_data is None:
  100. dis_mat, dis_max, dis_min, dis_mean = kernel_distance_matrix(Gn, None,
  101. None, Kmatrix=Kmatrix, gkernel=gkernel)
  102. else:
  103. dis_mat = k_dis_data[0]
  104. dis_max = k_dis_data[1]
  105. dis_min = k_dis_data[2]
  106. dis_mean = k_dis_data[3]
  107. print('pair distances - dis_max, dis_min, dis_mean:', dis_max, dis_min, dis_mean)
  108. if save_results:
  109. # create result files.
  110. print('creating output files...')
  111. fn_output_detail, fn_output_summary = init_output_file(ds_name, gkernel,
  112. fit_method, dir_output)
  113. # start repeats.
  114. repeats = 1
  115. # k_list = range(2, 11)
  116. k_list = [0]
  117. # get indices by classes.
  118. y_idx = get_same_item_indices(y_all)
  119. random.seed(1)
  120. rdn_seed_list = random.sample(range(0, repeats * 100), repeats)
  121. for k in k_list:
  122. # print('\n--------- k =', k, '----------')
  123. sod_sm_mean_list = []
  124. sod_gm_mean_list = []
  125. dis_k_sm_mean_list = []
  126. dis_k_gm_mean_list = []
  127. dis_k_gi_min_mean_list = []
  128. time_fitting_mean_list = []
  129. time_generating_mean_list = []
  130. time_total_mean_list = []
  131. # 3. start generating and computing over targets.
  132. print('4. starting generating and computing over targets......')
  133. for i, (y, values) in enumerate(y_idx.items()):
  134. # y = 'I'
  135. # values = y_idx[y]
  136. # values = values[0:10]
  137. print('\ny =', y)
  138. # if y.strip() == 'A':
  139. # continue
  140. k = len(values)
  141. print('\n--------- k =', k, '----------')
  142. sod_sm_list = []
  143. sod_gm_list = []
  144. dis_k_sm_list = []
  145. dis_k_gm_list = []
  146. dis_k_gi_min_list = []
  147. time_fitting_list = []
  148. time_generating_list = []
  149. time_total_list = []
  150. nb_sod_sm2gm = [0, 0, 0]
  151. nb_dis_k_sm2gm = [0, 0, 0]
  152. nb_dis_k_gi2sm = [0, 0, 0]
  153. nb_dis_k_gi2gm = [0, 0, 0]
  154. repeats_better_sod_sm2gm = []
  155. repeats_better_dis_k_sm2gm = []
  156. repeats_better_dis_k_gi2sm = []
  157. repeats_better_dis_k_gi2gm = []
  158. # get Gram matrix for this part of data.
  159. if Kmatrix is not None:
  160. Kmatrix_sub = Kmatrix[values,:]
  161. Kmatrix_sub = Kmatrix_sub[:,values]
  162. else:
  163. Kmatrix_sub = None
  164. for repeat in range(repeats):
  165. print('\nrepeat =', repeat)
  166. random.seed(rdn_seed_list[repeat])
  167. median_set_idx_idx = random.sample(range(0, len(values)), k)
  168. median_set_idx = [values[idx] for idx in median_set_idx_idx]
  169. print('median set: ', median_set_idx)
  170. Gn_median = [Gn[g] for g in values]
  171. # from notebooks.utils.plot_all_graphs import draw_Fingerprint_graph
  172. # for Gn in Gn_median:
  173. # draw_Fingerprint_graph(Gn, save=None)
  174. # GENERATING & COMPUTING!!
  175. res_sods, res_dis_ks, res_times = median_on_k_closest_graphs(Gn_median,
  176. node_label, edge_label,
  177. gkernel, k, fit_method=fit_method, graph_dir=graph_dir,
  178. edit_cost_constants=None, group_min=median_set_idx_idx,
  179. dataset=ds_name, initial_solutions=initial_solutions,
  180. edit_cost_name=edit_cost_name,
  181. Kmatrix=Kmatrix_sub, parallel=False)
  182. sod_sm = res_sods[0]
  183. sod_gm = res_sods[1]
  184. dis_k_sm = res_dis_ks[0]
  185. dis_k_gm = res_dis_ks[1]
  186. dis_k_gi = res_dis_ks[2]
  187. dis_k_gi_min = res_dis_ks[3]
  188. idx_dis_k_gi_min = res_dis_ks[4]
  189. time_fitting = res_times[0]
  190. time_generating = res_times[1]
  191. # write result detail.
  192. sod_sm2gm = getRelations(np.sign(sod_gm - sod_sm))
  193. dis_k_sm2gm = getRelations(np.sign(dis_k_gm - dis_k_sm))
  194. dis_k_gi2sm = getRelations(np.sign(dis_k_sm - dis_k_gi_min))
  195. dis_k_gi2gm = getRelations(np.sign(dis_k_gm - dis_k_gi_min))
  196. if save_results:
  197. f_detail = open(dir_output + fn_output_detail, 'a')
  198. csv.writer(f_detail).writerow([ds_name, gkernel,
  199. edit_cost_name, ged_method, attr_distance,
  200. fit_method, k, y, repeat,
  201. sod_sm, sod_gm, dis_k_sm, dis_k_gm,
  202. dis_k_gi_min, sod_sm2gm, dis_k_sm2gm, dis_k_gi2sm,
  203. dis_k_gi2gm, time_fitting, time_generating,
  204. time_fitting + time_generating, median_set_idx])
  205. f_detail.close()
  206. # compute result summary.
  207. sod_sm_list.append(sod_sm)
  208. sod_gm_list.append(sod_gm)
  209. dis_k_sm_list.append(dis_k_sm)
  210. dis_k_gm_list.append(dis_k_gm)
  211. dis_k_gi_min_list.append(dis_k_gi_min)
  212. time_fitting_list.append(time_fitting)
  213. time_generating_list.append(time_generating)
  214. time_total_list.append(time_fitting + time_generating)
  215. # # SOD SM -> GM
  216. if sod_sm > sod_gm:
  217. nb_sod_sm2gm[0] += 1
  218. repeats_better_sod_sm2gm.append(repeat)
  219. elif sod_sm == sod_gm:
  220. nb_sod_sm2gm[1] += 1
  221. elif sod_sm < sod_gm:
  222. nb_sod_sm2gm[2] += 1
  223. # # dis_k SM -> GM
  224. if dis_k_sm > dis_k_gm:
  225. nb_dis_k_sm2gm[0] += 1
  226. repeats_better_dis_k_sm2gm.append(repeat)
  227. elif dis_k_sm == dis_k_gm:
  228. nb_dis_k_sm2gm[1] += 1
  229. elif dis_k_sm < dis_k_gm:
  230. nb_dis_k_sm2gm[2] += 1
  231. # # dis_k gi -> SM
  232. if dis_k_gi_min > dis_k_sm:
  233. nb_dis_k_gi2sm[0] += 1
  234. repeats_better_dis_k_gi2sm.append(repeat)
  235. elif dis_k_gi_min == dis_k_sm:
  236. nb_dis_k_gi2sm[1] += 1
  237. elif dis_k_gi_min < dis_k_sm:
  238. nb_dis_k_gi2sm[2] += 1
  239. # # dis_k gi -> GM
  240. if dis_k_gi_min > dis_k_gm:
  241. nb_dis_k_gi2gm[0] += 1
  242. repeats_better_dis_k_gi2gm.append(repeat)
  243. elif dis_k_gi_min == dis_k_gm:
  244. nb_dis_k_gi2gm[1] += 1
  245. elif dis_k_gi_min < dis_k_gm:
  246. nb_dis_k_gi2gm[2] += 1
  247. # save median graphs.
  248. fname_sm = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/output/tmp_ged/set_median.gxl'
  249. fn_pre_sm_new = dir_output + 'medians/set_median.' + fit_method \
  250. + '.k' + str(int(k)) + '.y' + str(y) + '.repeat' + str(repeat)
  251. copyfile(fname_sm, fn_pre_sm_new + '.gxl')
  252. fname_gm = os.path.dirname(os.path.realpath(__file__)) + '/cpp_ext/output/tmp_ged/gen_median.gxl'
  253. fn_pre_gm_new = dir_output + 'medians/gen_median.' + fit_method \
  254. + '.k' + str(int(k)) + '.y' + str(y) + '.repeat' + str(repeat)
  255. copyfile(fname_gm, fn_pre_gm_new + '.gxl')
  256. G_best_kernel = Gn_median[idx_dis_k_gi_min].copy()
  257. # reform_attributes(G_best_kernel)
  258. fn_pre_g_best_kernel = dir_output + 'medians/g_best_kernel.' + fit_method \
  259. + '.k' + str(int(k)) + '.y' + str(y) + '.repeat' + str(repeat)
  260. saveGXL(G_best_kernel, fn_pre_g_best_kernel + '.gxl', method='default')
  261. # plot median graphs.
  262. if ds_name == 'Letter-high':
  263. set_median = loadGXL(fn_pre_sm_new + '.gxl')
  264. gen_median = loadGXL(fn_pre_gm_new + '.gxl')
  265. draw_Letter_graph(set_median, fn_pre_sm_new)
  266. draw_Letter_graph(gen_median, fn_pre_gm_new)
  267. draw_Letter_graph(G_best_kernel, fn_pre_g_best_kernel)
  268. # write result summary for each letter.
  269. sod_sm_mean_list.append(np.mean(sod_sm_list))
  270. sod_gm_mean_list.append(np.mean(sod_gm_list))
  271. dis_k_sm_mean_list.append(np.mean(dis_k_sm_list))
  272. dis_k_gm_mean_list.append(np.mean(dis_k_gm_list))
  273. dis_k_gi_min_mean_list.append(np.mean(dis_k_gi_min_list))
  274. time_fitting_mean_list.append(np.mean(time_fitting_list))
  275. time_generating_mean_list.append(np.mean(time_generating_list))
  276. time_total_mean_list.append(np.mean(time_total_list))
  277. sod_sm2gm_mean = getRelations(np.sign(sod_gm_mean_list[-1] - sod_sm_mean_list[-1]))
  278. dis_k_sm2gm_mean = getRelations(np.sign(dis_k_gm_mean_list[-1] - dis_k_sm_mean_list[-1]))
  279. dis_k_gi2sm_mean = getRelations(np.sign(dis_k_sm_mean_list[-1] - dis_k_gi_min_mean_list[-1]))
  280. dis_k_gi2gm_mean = getRelations(np.sign(dis_k_gm_mean_list[-1] - dis_k_gi_min_mean_list[-1]))
  281. if save_results:
  282. f_summary = open(dir_output + fn_output_summary, 'a')
  283. csv.writer(f_summary).writerow([ds_name, gkernel,
  284. edit_cost_name, ged_method, attr_distance,
  285. fit_method, k, y,
  286. sod_sm_mean_list[-1], sod_gm_mean_list[-1],
  287. dis_k_sm_mean_list[-1], dis_k_gm_mean_list[-1],
  288. dis_k_gi_min_mean_list[-1], sod_sm2gm_mean, dis_k_sm2gm_mean,
  289. dis_k_gi2sm_mean, dis_k_gi2gm_mean,
  290. time_fitting_mean_list[-1], time_generating_mean_list[-1],
  291. time_total_mean_list[-1], nb_sod_sm2gm,
  292. nb_dis_k_sm2gm, nb_dis_k_gi2sm, nb_dis_k_gi2gm,
  293. repeats_better_sod_sm2gm, repeats_better_dis_k_sm2gm,
  294. repeats_better_dis_k_gi2sm, repeats_better_dis_k_gi2gm])
  295. f_summary.close()
  296. # write result summary for each letter.
  297. sod_sm_mean = np.mean(sod_sm_mean_list)
  298. sod_gm_mean = np.mean(sod_gm_mean_list)
  299. dis_k_sm_mean = np.mean(dis_k_sm_mean_list)
  300. dis_k_gm_mean = np.mean(dis_k_gm_mean_list)
  301. dis_k_gi_min_mean = np.mean(dis_k_gi_min_list)
  302. time_fitting_mean = np.mean(time_fitting_list)
  303. time_generating_mean = np.mean(time_generating_list)
  304. time_total_mean = np.mean(time_total_list)
  305. sod_sm2gm_mean = getRelations(np.sign(sod_gm_mean - sod_sm_mean))
  306. dis_k_sm2gm_mean = getRelations(np.sign(dis_k_gm_mean - dis_k_sm_mean))
  307. dis_k_gi2sm_mean = getRelations(np.sign(dis_k_sm_mean - dis_k_gi_min_mean))
  308. dis_k_gi2gm_mean = getRelations(np.sign(dis_k_gm_mean - dis_k_gi_min_mean))
  309. if save_results:
  310. f_summary = open(dir_output + fn_output_summary, 'a')
  311. csv.writer(f_summary).writerow([ds_name, gkernel,
  312. edit_cost_name, ged_method, attr_distance,
  313. fit_method, k, 'all',
  314. sod_sm_mean, sod_gm_mean, dis_k_sm_mean, dis_k_gm_mean,
  315. dis_k_gi_min_mean, sod_sm2gm_mean, dis_k_sm2gm_mean,
  316. dis_k_gi2sm_mean, dis_k_gi2gm_mean,
  317. time_fitting_mean, time_generating_mean, time_total_mean])
  318. f_summary.close()
  319. print('\ncomplete.')
  320. #Dessin median courrant
  321. def draw_Letter_graph(graph, file_prefix):
  322. plt.figure()
  323. pos = {}
  324. for n in graph.nodes:
  325. pos[n] = np.array([float(graph.node[n]['x']),float(graph.node[n]['y'])])
  326. nx.draw_networkx(graph, pos)
  327. plt.savefig(file_prefix + '.eps', format='eps', dpi=300)
  328. # plt.show()
  329. plt.clf()
  330. if __name__ == "__main__":
  331. # #### xp 1: Letter-high, spkernel.
  332. # # load dataset.
  333. # print('getting dataset and computing kernel distance matrix first...')
  334. # ds_name = 'Letter-high'
  335. # gkernel = 'spkernel'
  336. # Gn, y_all, graph_dir = get_dataset(ds_name)
  337. # # remove graphs without edges.
  338. # Gn = [(idx, G) for idx, G in enumerate(Gn) if nx.number_of_edges(G) != 0]
  339. # idx = [G[0] for G in Gn]
  340. # Gn = [G[1] for G in Gn]
  341. # y_all = [y_all[i] for i in idx]
  342. ## Gn = Gn[0:50]
  343. ## y_all = y_all[0:50]
  344. # # compute pair distances.
  345. # dis_mat, dis_max, dis_min, dis_mean = kernel_distance_matrix(Gn, None, None,
  346. # Kmatrix=None, gkernel=gkernel, verbose=True)
  347. ## dis_mat, dis_max, dis_min, dis_mean = 0, 0, 0, 0
  348. # # fitting and computing.
  349. # fit_methods = ['random', 'expert', 'k-graphs']
  350. # for fit_method in fit_methods:
  351. # print('\n-------------------------------------')
  352. # print('fit method:', fit_method)
  353. # parameters = {'ds_name': ds_name,
  354. # 'gkernel': gkernel,
  355. # 'edit_cost_name': 'LETTER2',
  356. # 'ged_method': 'mIPFP',
  357. # 'attr_distance': 'euclidean',
  358. # 'fit_method': fit_method}
  359. # xp_fit_method_for_non_symbolic(parameters, save_results=True,
  360. # initial_solutions=40,
  361. # Gn_data = [Gn, y_all, graph_dir],
  362. # k_dis_data = [dis_mat, dis_max, dis_min, dis_mean])
  363. # #### xp 2: Letter-high, sspkernel.
  364. # # load dataset.
  365. # print('getting dataset and computing kernel distance matrix first...')
  366. # ds_name = 'Letter-high'
  367. # gkernel = 'structuralspkernel'
  368. # Gn, y_all, graph_dir = get_dataset(ds_name)
  369. ## Gn = Gn[0:50]
  370. ## y_all = y_all[0:50]
  371. # # compute pair distances.
  372. # dis_mat, dis_max, dis_min, dis_mean = kernel_distance_matrix(Gn, None, None,
  373. # Kmatrix=None, gkernel=gkernel, verbose=True)
  374. ## dis_mat, dis_max, dis_min, dis_mean = 0, 0, 0, 0
  375. # # fitting and computing.
  376. # fit_methods = ['random', 'expert', 'k-graphs']
  377. # for fit_method in fit_methods:
  378. # print('\n-------------------------------------')
  379. # print('fit method:', fit_method)
  380. # parameters = {'ds_name': ds_name,
  381. # 'gkernel': gkernel,
  382. # 'edit_cost_name': 'LETTER2',
  383. # 'ged_method': 'mIPFP',
  384. # 'attr_distance': 'euclidean',
  385. # 'fit_method': fit_method}
  386. # print('parameters: ', parameters)
  387. # xp_fit_method_for_non_symbolic(parameters, save_results=True,
  388. # initial_solutions=40,
  389. # Gn_data = [Gn, y_all, graph_dir],
  390. # k_dis_data = [dis_mat, dis_max, dis_min, dis_mean])
  391. # #### xp 3: SYNTHETICnew, sspkernel, using NON_SYMBOLIC.
  392. # gmfile = np.load('results/xp_fit_method/Kmatrix.SYNTHETICnew.structuralspkernel.gm.npz')
  393. # Kmatrix = gmfile['Kmatrix']
  394. # run_time = gmfile['run_time']
  395. # # normalization
  396. # Kmatrix_diag = Kmatrix.diagonal().copy()
  397. # for i in range(len(Kmatrix)):
  398. # for j in range(i, len(Kmatrix)):
  399. # Kmatrix[i][j] /= np.sqrt(Kmatrix_diag[i] * Kmatrix_diag[j])
  400. # Kmatrix[j][i] = Kmatrix[i][j]
  401. ## np.savez('results/xp_fit_method/Kmatrix.SYNTHETICnew.spkernel.gm',
  402. ## Kmatrix=Kmatrix, run_time=run_time)
  403. # # load dataset.
  404. # print('getting dataset and computing kernel distance matrix first...')
  405. # ds_name = 'SYNTHETICnew'
  406. # gkernel = 'structuralspkernel'
  407. # Gn, y_all, graph_dir = get_dataset(ds_name)
  408. # # remove graphs without nodes and edges.
  409. # Gn = [(idx, G) for idx, G in enumerate(Gn) if (nx.number_of_nodes(G) != 0
  410. # and nx.number_of_edges(G) != 0)]
  411. # idx = [G[0] for G in Gn]
  412. # Gn = [G[1] for G in Gn]
  413. # y_all = [y_all[i] for i in idx]
  414. ## Gn = Gn[0:10]
  415. ## y_all = y_all[0:10]
  416. # for G in Gn:
  417. # G.graph['filename'] = 'graph' + str(G.graph['name']) + '.gxl'
  418. # # compute pair distances.
  419. # dis_mat, dis_max, dis_min, dis_mean = kernel_distance_matrix(Gn, None, None,
  420. # Kmatrix=Kmatrix, gkernel=gkernel, verbose=True)
  421. ## dis_mat, dis_max, dis_min, dis_mean = 0, 0, 0, 0
  422. # # fitting and computing.
  423. # fit_methods = ['k-graphs', 'random', 'random', 'random']
  424. # for fit_method in fit_methods:
  425. # print('\n-------------------------------------')
  426. # print('fit method:', fit_method)
  427. # parameters = {'ds_name': ds_name,
  428. # 'gkernel': gkernel,
  429. # 'edit_cost_name': 'NON_SYMBOLIC',
  430. # 'ged_method': 'mIPFP',
  431. # 'attr_distance': 'euclidean',
  432. # 'fit_method': fit_method}
  433. # xp_fit_method_for_non_symbolic(parameters, save_results=True,
  434. # initial_solutions=1,
  435. # Gn_data = [Gn, y_all, graph_dir],
  436. # k_dis_data = [dis_mat, dis_max, dis_min, dis_mean],
  437. # Kmatrix=Kmatrix)
  438. # ### xp 4: SYNTHETICnew, spkernel, using NON_SYMBOLIC.
  439. # gmfile = np.load('results/xp_fit_method/Kmatrix.SYNTHETICnew.spkernel.gm.npz')
  440. # Kmatrix = gmfile['Kmatrix']
  441. # # normalization
  442. # Kmatrix_diag = Kmatrix.diagonal().copy()
  443. # for i in range(len(Kmatrix)):
  444. # for j in range(i, len(Kmatrix)):
  445. # Kmatrix[i][j] /= np.sqrt(Kmatrix_diag[i] * Kmatrix_diag[j])
  446. # Kmatrix[j][i] = Kmatrix[i][j]
  447. # run_time = 21821.35
  448. # np.savez('results/xp_fit_method/Kmatrix.SYNTHETICnew.spkernel.gm',
  449. # Kmatrix=Kmatrix, run_time=run_time)
  450. #
  451. # # load dataset.
  452. # print('getting dataset and computing kernel distance matrix first...')
  453. # ds_name = 'SYNTHETICnew'
  454. # gkernel = 'spkernel'
  455. # Gn, y_all, graph_dir = get_dataset(ds_name)
  456. ## # remove graphs without nodes and edges.
  457. ## Gn = [(idx, G) for idx, G in enumerate(Gn) if (nx.number_of_node(G) != 0
  458. ## and nx.number_of_edges(G) != 0)]
  459. ## idx = [G[0] for G in Gn]
  460. ## Gn = [G[1] for G in Gn]
  461. ## y_all = [y_all[i] for i in idx]
  462. ## Gn = Gn[0:5]
  463. ## y_all = y_all[0:5]
  464. # for G in Gn:
  465. # G.graph['filename'] = 'graph' + str(G.graph['name']) + '.gxl'
  466. #
  467. # # compute/read Gram matrix and pair distances.
  468. ## Kmatrix = compute_kernel(Gn, gkernel, None, None, True)
  469. ## np.savez('results/xp_fit_method/Kmatrix.' + ds_name + '.' + gkernel + '.gm',
  470. ## Kmatrix=Kmatrix)
  471. # gmfile = np.load('results/xp_fit_method/Kmatrix.' + ds_name + '.' + gkernel + '.gm.npz')
  472. # Kmatrix = gmfile['Kmatrix']
  473. # run_time = gmfile['run_time']
  474. ## Kmatrix = Kmatrix[[0,1,2,3,4],:]
  475. ## Kmatrix = Kmatrix[:,[0,1,2,3,4]]
  476. # print('\nTime to compute Gram matrix for the whole dataset: ', run_time)
  477. # dis_mat, dis_max, dis_min, dis_mean = kernel_distance_matrix(Gn, None, None,
  478. # Kmatrix=Kmatrix, gkernel=gkernel, verbose=True)
  479. ## Kmatrix = np.zeros((len(Gn), len(Gn)))
  480. ## dis_mat, dis_max, dis_min, dis_mean = 0, 0, 0, 0
  481. #
  482. # # fitting and computing.
  483. # fit_methods = ['k-graphs', 'random', 'random', 'random']
  484. # for fit_method in fit_methods:
  485. # print('\n-------------------------------------')
  486. # print('fit method:', fit_method)
  487. # parameters = {'ds_name': ds_name,
  488. # 'gkernel': gkernel,
  489. # 'edit_cost_name': 'NON_SYMBOLIC',
  490. # 'ged_method': 'mIPFP',
  491. # 'attr_distance': 'euclidean',
  492. # 'fit_method': fit_method}
  493. # xp_fit_method_for_non_symbolic(parameters, save_results=True,
  494. # initial_solutions=1,
  495. # Gn_data=[Gn, y_all, graph_dir],
  496. # k_dis_data=[dis_mat, dis_max, dis_min, dis_mean],
  497. # Kmatrix=Kmatrix)
  498. #### xp 5: Fingerprint, sspkernel, using LETTER2.
  499. # load dataset.
  500. print('getting dataset and computing kernel distance matrix first...')
  501. ds_name = 'Fingerprint'
  502. gkernel = 'structuralspkernel'
  503. Gn, y_all, graph_dir = get_dataset(ds_name)
  504. # remove graphs without nodes and edges.
  505. Gn = [(idx, G) for idx, G in enumerate(Gn) if (nx.number_of_nodes(G) != 0)]
  506. # and nx.number_of_edges(G) != 0)]
  507. idx = [G[0] for G in Gn]
  508. Gn = [G[1] for G in Gn]
  509. y_all = [y_all[i] for i in idx]
  510. y_idx = get_same_item_indices(y_all)
  511. # remove unused labels.
  512. for G in Gn:
  513. G.graph['edge_attrs'] = []
  514. for edge in G.edges:
  515. del G.edges[edge]['attributes']
  516. del G.edges[edge]['orient']
  517. del G.edges[edge]['angle']
  518. Gn = Gn[805:815]
  519. y_all = y_all[805:815]
  520. for G in Gn:
  521. G.graph['filename'] = 'graph' + str(G.graph['name']) + '.gxl'
  522. # compute/read Gram matrix and pair distances.
  523. Kmatrix = compute_kernel(Gn, gkernel, None, None, True, parallel='imap_unordered')
  524. np.savez('results/xp_fit_method/Kmatrix.' + ds_name + '.' + gkernel + '.gm',
  525. Kmatrix=Kmatrix)
  526. # gmfile = np.load('results/xp_fit_method/Kmatrix.' + ds_name + '.' + gkernel + '.gm.npz')
  527. # Kmatrix = gmfile['Kmatrix']
  528. # run_time = gmfile['run_time']
  529. # Kmatrix = Kmatrix[[0,1,2,3,4],:]
  530. # Kmatrix = Kmatrix[:,[0,1,2,3,4]]
  531. # print('\nTime to compute Gram matrix for the whole dataset: ', run_time)
  532. dis_mat, dis_max, dis_min, dis_mean = kernel_distance_matrix(Gn, None, None,
  533. Kmatrix=Kmatrix, gkernel=gkernel, verbose=True)
  534. # Kmatrix = np.zeros((len(Gn), len(Gn)))
  535. # dis_mat, dis_max, dis_min, dis_mean = 0, 0, 0, 0
  536. # compute pair distances.
  537. # dis_mat, dis_max, dis_min, dis_mean = kernel_distance_matrix(Gn, None, None,
  538. # Kmatrix=None, gkernel=gkernel, verbose=True)
  539. # dis_mat, dis_max, dis_min, dis_mean = 0, 0, 0, 0
  540. # fitting and computing.
  541. fit_methods = ['k-graphs', 'expert', 'random', 'random', 'random']
  542. for fit_method in fit_methods:
  543. print('\n-------------------------------------')
  544. print('fit method:', fit_method)
  545. parameters = {'ds_name': ds_name,
  546. 'gkernel': gkernel,
  547. 'edit_cost_name': 'LETTER2',
  548. 'ged_method': 'mIPFP',
  549. 'attr_distance': 'euclidean',
  550. 'fit_method': fit_method}
  551. xp_fit_method_for_non_symbolic(parameters, save_results=True,
  552. initial_solutions=40,
  553. Gn_data = [Gn, y_all, graph_dir],
  554. k_dis_data = [dis_mat, dis_max, dis_min, dis_mean],
  555. Kmatrix=Kmatrix)

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