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.repeats.ratios.IPFP.py 4.7 kB

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

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