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.max_num_sols.ratios.bipartite.py 5.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Nov 2 16:17:01 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, max_num_solutions, ratio, trial):
  18. save_file_suffix = '.' + ds_name + '.mnum_sols_' + str(max_num_solutions) + '.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': 'BIPARTITE', # use BIPARTITE huristic.
  25. # 'initialization_method': 'RANDOM', # or 'NODE', etc. (for GEDEnv)
  26. 'lsape_model': 'ECBP', #
  27. # ??when bigger than 1, then the method is considered mIPFP.
  28. # the actual number of computed solutions might be smaller than the specified value
  29. 'max_num_solutions': max_num_solutions,
  30. 'edit_cost': 'CONSTANT', # use CONSTANT cost.
  31. 'greedy_method': 'BASIC', #
  32. # the distance between non-symbolic node/edge labels is computed by euclidean distance.
  33. 'attr_distance': 'euclidean',
  34. 'optimal': True, # if TRUE, the option --greedy-method has no effect
  35. # parallel threads. Do not work if mpg_options['parallel'] = False.
  36. 'threads': multiprocessing.cpu_count(),
  37. 'centrality_method': 'NONE',
  38. 'centrality_weight': 0.7,
  39. 'init_option': 'EAGER_WITHOUT_SHUFFLED_COPIES'
  40. }
  41. edit_cost_constants = [i * ratio for i in [1, 1, 1]] + [1, 1, 1]
  42. # edit_cost_constants = [item * 0.01 for item in edit_cost_constants]
  43. # pickle.dump(edit_cost_constants, open(save_dir + "edit_costs" + save_file_suffix + ".pkl", "wb"))
  44. options = ged_options.copy()
  45. options['edit_cost_constants'] = edit_cost_constants
  46. options['node_labels'] = dataset.node_labels
  47. options['edge_labels'] = dataset.edge_labels
  48. options['node_attrs'] = dataset.node_attrs
  49. options['edge_attrs'] = dataset.edge_attrs
  50. parallel = True # if num_solutions == 1 else False
  51. """**5. Compute GED matrix.**"""
  52. ged_mat = 'error'
  53. runtime = 0
  54. try:
  55. time0 = time.time()
  56. ged_vec_init, ged_mat, n_edit_operations = compute_geds(dataset.graphs, options=options, repeats=1, parallel=parallel, verbose=True)
  57. runtime = time.time() - time0
  58. except Exception as exp:
  59. print('An exception occured when running this experiment:')
  60. LOG_FILENAME = save_dir + 'error.txt'
  61. logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
  62. logging.exception(save_file_suffix)
  63. print(repr(exp))
  64. """**6. Get results.**"""
  65. with open(save_dir + 'ged_matrix' + save_file_suffix + '.pkl', 'wb') as f:
  66. pickle.dump(ged_mat, f)
  67. with open(save_dir + 'runtime' + save_file_suffix + '.pkl', 'wb') as f:
  68. pickle.dump(runtime, f)
  69. return ged_mat, runtime
  70. def save_trials_as_group(dataset, ds_name, max_num_solutions, ratio):
  71. # Return if the group file exists.
  72. name_middle = '.' + ds_name + '.mnum_sols_' + str(max_num_solutions) + '.ratio_' + "{:.2f}".format(ratio) + '.'
  73. name_group = save_dir + 'groups/ged_mats' + name_middle + 'npy'
  74. if os.path.isfile(name_group):
  75. return
  76. ged_mats = []
  77. runtimes = []
  78. for trial in range(1, 101):
  79. print()
  80. print('Trial:', trial)
  81. ged_mat, runtime = xp_compute_ged_matrix(dataset, ds_name, max_num_solutions, ratio, trial)
  82. ged_mats.append(ged_mat)
  83. runtimes.append(runtime)
  84. # Group trials and Remove single files.
  85. name_prefix = 'ged_matrix' + name_middle
  86. group_trials(save_dir, name_prefix, True, True, False)
  87. name_prefix = 'runtime' + name_middle
  88. group_trials(save_dir, name_prefix, True, True, False)
  89. def results_for_a_dataset(ds_name):
  90. """**1. Get dataset.**"""
  91. dataset = get_dataset(ds_name)
  92. for max_num_solutions in mnum_solutions_list:
  93. print()
  94. print('Max # of solutions:', max_num_solutions)
  95. for ratio in ratio_list:
  96. print()
  97. print('Ratio:', ratio)
  98. save_trials_as_group(dataset, ds_name, max_num_solutions, ratio)
  99. def get_param_lists(ds_name):
  100. if ds_name == 'AIDS_symb':
  101. mnum_solutions_list = [1, 20, 40, 60, 80, 100]
  102. ratio_list = [0.1, 0.3, 0.5, 0.7, 0.9, 1, 3, 5, 7, 9]
  103. else:
  104. mnum_solutions_list = [1, 20, 40, 60, 80, 100]
  105. ratio_list = [0.1, 0.3, 0.5, 0.7, 0.9, 1, 3, 5, 7, 9]
  106. return mnum_solutions_list, ratio_list
  107. if __name__ == '__main__':
  108. if len(sys.argv) > 1:
  109. ds_name_list = sys.argv[1:]
  110. else:
  111. ds_name_list = ['MAO', 'Monoterpenoides', 'MUTAG', 'AIDS_symb']
  112. save_dir = 'outputs/edit_costs.max_num_sols.ratios.bipartite/'
  113. os.makedirs(save_dir, exist_ok=True)
  114. os.makedirs(save_dir + 'groups/', exist_ok=True)
  115. for ds_name in ds_name_list:
  116. print()
  117. print('Dataset:', ds_name)
  118. mnum_solutions_list, ratio_list = get_param_lists(ds_name)
  119. results_for_a_dataset(ds_name)

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