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.real_data.nums_sols.ratios.IPFP.py 6.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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 time
  14. from utils import get_dataset, set_edit_cost_consts, dichotomous_permutation, mix_param_grids
  15. import sys
  16. from group_results import group_trials, check_group_existence, update_group_marker
  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. # 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': int(num_solutions * 4),
  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': 0.25,
  32. # parallel threads. Set to 1 automatically if parallel=True in compute_geds().
  33. 'threads': multiprocessing.cpu_count(),
  34. 'init_option': 'EAGER_WITHOUT_SHUFFLED_COPIES'
  35. }
  36. edit_cost_constants = set_edit_cost_consts(ratio,
  37. node_labeled=len(dataset.node_labels),
  38. edge_labeled=len(dataset.edge_labels),
  39. mode='uniform')
  40. # edit_cost_constants = [item * 0.01 for item in edit_cost_constants]
  41. # pickle.dump(edit_cost_constants, open(save_dir + "edit_costs" + save_file_suffix + ".pkl", "wb"))
  42. options = ged_options.copy()
  43. options['edit_cost_constants'] = edit_cost_constants
  44. options['node_labels'] = dataset.node_labels
  45. options['edge_labels'] = dataset.edge_labels
  46. options['node_attrs'] = dataset.node_attrs
  47. options['edge_attrs'] = dataset.edge_attrs
  48. parallel = True # if num_solutions == 1 else False
  49. """**5. Compute GED matrix.**"""
  50. ged_mat = 'error'
  51. runtime = 0
  52. try:
  53. time0 = time.time()
  54. ged_vec_init, ged_mat, n_edit_operations = compute_geds(dataset.graphs, options=options, repeats=1, parallel=parallel, verbose=True)
  55. runtime = time.time() - time0
  56. except Exception as exp:
  57. print('An exception occured when running this experiment:')
  58. LOG_FILENAME = save_dir + 'error.txt'
  59. logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
  60. logging.exception(save_file_suffix)
  61. print(repr(exp))
  62. """**6. Get results.**"""
  63. with open(save_dir + 'ged_matrix' + save_file_suffix + '.pkl', 'wb') as f:
  64. pickle.dump(ged_mat, f)
  65. with open(save_dir + 'runtime' + save_file_suffix + '.pkl', 'wb') as f:
  66. pickle.dump(runtime, f)
  67. return ged_mat, runtime
  68. def save_trials_as_group(dataset, ds_name, num_solutions, ratio):
  69. # Return if the group file exists.
  70. name_middle = '.' + ds_name + '.num_sols_' + str(num_solutions) + '.ratio_' + "{:.2f}".format(ratio) + '.'
  71. name_group = save_dir + 'groups/ged_mats' + name_middle + 'npy'
  72. if check_group_existence(name_group):
  73. return
  74. ged_mats = []
  75. runtimes = []
  76. num_trials = 100
  77. for trial in range(1, num_trials + 1):
  78. print()
  79. print('Trial:', trial)
  80. ged_mat, runtime = xp_compute_ged_matrix(dataset, ds_name, num_solutions, ratio, trial)
  81. ged_mats.append(ged_mat)
  82. runtimes.append(runtime)
  83. # Group trials and remove single files.
  84. # @todo: if the program stops between the following lines, then there may be errors.
  85. name_prefix = 'ged_matrix' + name_middle
  86. group_trials(save_dir, name_prefix, True, True, False, num_trials=num_trials)
  87. name_prefix = 'runtime' + name_middle
  88. group_trials(save_dir, name_prefix, True, True, False, num_trials=num_trials)
  89. update_group_marker(name_group)
  90. def results_for_a_dataset(ds_name):
  91. """**1. Get dataset.**"""
  92. dataset = get_dataset(ds_name)
  93. for params in list(param_grid):
  94. print()
  95. print(params)
  96. save_trials_as_group(dataset, ds_name, params['num_solutions'], params['ratio'])
  97. def get_param_lists(ds_name, mode='test'):
  98. if mode == 'test':
  99. num_solutions_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]
  100. ratio_list = [10]
  101. return num_solutions_list, ratio_list
  102. elif mode == 'simple':
  103. from sklearn.model_selection import ParameterGrid
  104. param_grid = mix_param_grids([list(ParameterGrid([
  105. {'num_solutions': dichotomous_permutation([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 40, 50, 60, 70, 80, 90, 100]), 'ratio': [10]}])),
  106. list(ParameterGrid([
  107. {'num_solutions': [10], 'ratio': dichotomous_permutation([0.1, 0.3, 0.5, 0.7, 0.9, 1, 3, 5, 7, 9, 10])}]))])
  108. # print(list(param_grid))
  109. if ds_name == 'AIDS_symb':
  110. num_solutions_list = [1, 20, 40, 60, 80, 100]
  111. ratio_list = [0.1, 0.3, 0.5, 0.7, 0.9, 1, 3, 5, 7, 9]
  112. else:
  113. num_solutions_list = [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] # [1, 20, 40, 60, 80, 100]
  114. ratio_list = [0.1, 0.3, 0.5, 0.7, 0.9, 1, 3, 5, 7, 9, 10][::-1]
  115. return param_grid
  116. if __name__ == '__main__':
  117. if len(sys.argv) > 1:
  118. ds_name_list = sys.argv[1:]
  119. else:
  120. ds_name_list = ['Acyclic', 'Alkane_unlabeled', 'MAO_lite', 'Monoterpenoides', 'MUTAG']
  121. # ds_name_list = ['MUTAG'] # 'Alkane_unlabeled']
  122. # ds_name_list = ['Acyclic', 'MAO', 'Monoterpenoides', 'MUTAG', 'AIDS_symb']
  123. save_dir = 'outputs/CRIANN/edit_costs.real_data.num_sols.ratios.IPFP/'
  124. os.makedirs(save_dir, exist_ok=True)
  125. os.makedirs(save_dir + 'groups/', exist_ok=True)
  126. for ds_name in ds_name_list:
  127. print()
  128. print('Dataset:', ds_name)
  129. param_grid = get_param_lists(ds_name, mode='simple')
  130. results_for_a_dataset(ds_name)

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