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.

edit_costs.nums_sols.ratios.IPFP.py 4.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Wed Oct 20 11:48:02 2020
  5. @author: ljia
  6. """
  7. # This script tests the influence of the ratios between node costs and edge costs on the stability of the GED computation, where the base edit costs are [1, 1, 1, 1, 1, 1].
  8. import os
  9. import multiprocessing
  10. import pickle
  11. import logging
  12. from gklearn.ged.util import compute_geds
  13. import numpy as np
  14. import time
  15. from utils import get_dataset
  16. import sys
  17. def xp_compute_ged_matrix(dataset, ds_name, num_solutions, ratio, trial):
  18. save_file_suffix = '.' + ds_name + '.num_sols_' + str(num_solutions) + '.ratio_' + "{:.2f}".format(ratio) + '.trial_' + str(trial)
  19. """**2. Set parameters.**"""
  20. # Parameters for GED computation.
  21. ged_options = {'method': 'IPFP', # use IPFP huristic.
  22. 'initialization_method': 'RANDOM', # or 'NODE', etc.
  23. # when bigger than 1, then the method is considered mIPFP.
  24. 'initial_solutions': int(num_solutions * 4),
  25. 'edit_cost': 'CONSTANT', # use CONSTANT cost.
  26. # the distance between non-symbolic node/edge labels is computed by euclidean distance.
  27. 'attr_distance': 'euclidean',
  28. 'ratio_runs_from_initial_solutions': 0.25,
  29. # parallel threads. Do not work if mpg_options['parallel'] = False.
  30. 'threads': multiprocessing.cpu_count(),
  31. 'init_option': 'EAGER_WITHOUT_SHUFFLED_COPIES'
  32. }
  33. edit_cost_constants = [i * ratio for i in [1, 1, 1]] + [1, 1, 1]
  34. # edit_cost_constants = [item * 0.01 for item in edit_cost_constants]
  35. # pickle.dump(edit_cost_constants, open(save_dir + "edit_costs" + save_file_suffix + ".pkl", "wb"))
  36. options = ged_options.copy()
  37. options['edit_cost_constants'] = edit_cost_constants
  38. options['node_labels'] = dataset.node_labels
  39. options['edge_labels'] = dataset.edge_labels
  40. options['node_attrs'] = dataset.node_attrs
  41. options['edge_attrs'] = dataset.edge_attrs
  42. parallel = True # if num_solutions == 1 else False
  43. """**5. Compute GED matrix.**"""
  44. ged_mat = 'error'
  45. runtime = 0
  46. try:
  47. time0 = time.time()
  48. ged_vec_init, ged_mat, n_edit_operations = compute_geds(dataset.graphs, options=options, parallel=parallel, verbose=True)
  49. runtime = time.time() - time0
  50. except Exception as exp:
  51. print('An exception occured when running this experiment:')
  52. LOG_FILENAME = save_dir + 'error.txt'
  53. logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
  54. logging.exception(save_file_suffix)
  55. print(repr(exp))
  56. """**6. Get results.**"""
  57. with open(save_dir + 'ged_matrix' + save_file_suffix + '.pkl', 'wb') as f:
  58. pickle.dump(ged_mat, f)
  59. with open(save_dir + 'runtime' + save_file_suffix + '.pkl', 'wb') as f:
  60. pickle.dump(runtime, f)
  61. return ged_mat, runtime
  62. def save_trials_as_group(dataset, ds_name, num_solutions, ratio):
  63. ged_mats = []
  64. runtimes = []
  65. for trial in range(1, 101):
  66. print()
  67. print('Trial:', trial)
  68. ged_mat, runtime = xp_compute_ged_matrix(dataset, ds_name, num_solutions, ratio, trial)
  69. ged_mats.append(ged_mat)
  70. runtimes.append(runtime)
  71. # save_file_suffix = '.' + ds_name + '.num_sols_' + str(num_solutions) + '.ratio_' + "{:.2f}".format(ratio)
  72. # with open(save_dir + 'groups/ged_mats' + save_file_suffix + '.npy', 'wb') as f:
  73. # np.save(f, np.array(ged_mats))
  74. # with open(save_dir + 'groups/runtimes' + save_file_suffix + '.pkl', 'wb') as f:
  75. # pickle.dump(runtime, f)
  76. def results_for_a_dataset(ds_name):
  77. """**1. Get dataset.**"""
  78. dataset = get_dataset(ds_name)
  79. for num_solutions in [1, 20, 40, 60, 80, 100]:
  80. print()
  81. print('# of solutions:', num_solutions)
  82. for ratio in [0.1, 0.3, 0.5, 0.7, 0.9, 1, 3, 5, 7, 9]:
  83. print()
  84. print('Ratio:', ratio)
  85. save_trials_as_group(dataset, ds_name, num_solutions, ratio)
  86. if __name__ == '__main__':
  87. if len(sys.argv) > 1:
  88. ds_name_list = sys.argv[1:]
  89. else:
  90. ds_name_list = ['MAO', 'Monoterpenoides', 'MUTAG', 'AIDS_symb']
  91. save_dir = 'outputs/edit_costs.num_sols.ratios.IPFP/'
  92. os.makedirs(save_dir, exist_ok=True)
  93. os.makedirs(save_dir + 'groups/', exist_ok=True)
  94. for ds_name in ds_name_list:
  95. print()
  96. print('Dataset:', ds_name)
  97. results_for_a_dataset(ds_name)

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