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 4.6 kB

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

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