|
| 1 | +""" |
| 2 | +fit_ged_model |
| 3 | +
|
| 4 | +@Author: jajupmochi |
| 5 | +@Date: May 22 2025 |
| 6 | +""" |
| 7 | +from typing import List |
| 8 | + |
| 9 | +import networkx as nx |
| 10 | +import numpy as np |
| 11 | + |
| 12 | +ISSUE_TAG = "\033[91m[issue]\033[0m " # Red |
| 13 | +INFO_TAG = "\033[94m[info]\033[0m " # Blue |
| 14 | +SUCCESS_TAG = "\033[92m[success]\033[0m " # Green |
| 15 | + |
| 16 | + |
| 17 | +def fit_model_ged( |
| 18 | + graphs_X: List[nx.Graph], |
| 19 | + graphs_Y: List[nx.Graph] = None, |
| 20 | + ged_options: dict = None, |
| 21 | + parallel: bool = None, |
| 22 | + n_jobs: int = None, |
| 23 | + chunksize: int = None, |
| 24 | + copy_graphs: bool = True, |
| 25 | + read_resu_from_file: int = 1, |
| 26 | + output_dir: str = None, |
| 27 | + params_idx: str = None, |
| 28 | + reorder_graphs: bool = False, |
| 29 | + verbose: int = 2, |
| 30 | + **kwargs |
| 31 | +): |
| 32 | + # if read_resu_from_file >= 1: |
| 33 | + # fn_model = os.path.join( |
| 34 | + # output_dir, 'metric_model.params_{}.pkl'.format( |
| 35 | + # params_idx |
| 36 | + # ) |
| 37 | + # ) |
| 38 | + # # Load model from file if it exists: |
| 39 | + # if os.path.exists(fn_model) and os.path.getsize(fn_model) > 0: |
| 40 | + # print('\nLoading model from file...') |
| 41 | + # resu = pickle.load(open(fn_model, 'rb')) |
| 42 | + # return resu['model'], resu['history'], resu['model'].dis_matrix |
| 43 | + |
| 44 | + # Reorder graphs if specified: |
| 45 | + if reorder_graphs: |
| 46 | + graphs_X = reorder_graphs_by_index(graphs_X, idx_key='id') |
| 47 | + if graphs_Y is not None: |
| 48 | + graphs_Y = reorder_graphs_by_index(graphs_Y, idx_key='id') |
| 49 | + |
| 50 | + # Compute metric matrix otherwise: |
| 51 | + print(f'{INFO_TAG}Computing metric matrix...') |
| 52 | + all_graphs = graphs_X + graphs_Y if graphs_Y else graphs_X |
| 53 | + nl_names = list( |
| 54 | + all_graphs[0].nodes[list(all_graphs[0].nodes)[0]].keys() |
| 55 | + ) if graphs_X else [] |
| 56 | + if not all_graphs: |
| 57 | + el_names = [] |
| 58 | + else: |
| 59 | + idx_edge = ( |
| 60 | + np.where(np.array([nx.number_of_edges(g) for g in all_graphs]) > 0)[0] |
| 61 | + ) |
| 62 | + if len(idx_edge) == 0: |
| 63 | + el_names = [] |
| 64 | + else: |
| 65 | + el_names = list( |
| 66 | + all_graphs[idx_edge[0]].edges[ |
| 67 | + list(all_graphs[idx_edge[0]].edges)[0]].keys() |
| 68 | + ) |
| 69 | + |
| 70 | + from .parallel_version import GEDModel |
| 71 | + |
| 72 | + if parallel is False: |
| 73 | + parallel = None |
| 74 | + elif parallel is True: |
| 75 | + parallel = 'imap_unordered' |
| 76 | + |
| 77 | + model = GEDModel( |
| 78 | + ed_method=ged_options['method'], |
| 79 | + edit_cost_fun=ged_options['edit_cost_fun'], |
| 80 | + init_edit_cost_constants=ged_options['edit_costs'], |
| 81 | + optim_method=ged_options['optim_method'], |
| 82 | + node_labels=nl_names, edge_labels=el_names, |
| 83 | + parallel=parallel, |
| 84 | + n_jobs=n_jobs, |
| 85 | + chunksize=chunksize, |
| 86 | + copy_graphs=copy_graphs, |
| 87 | + # make sure it is a full deep copy. and faster! |
| 88 | + verbose=verbose |
| 89 | + ) |
| 90 | + |
| 91 | + # Train model. |
| 92 | + try: |
| 93 | + if graphs_Y is None: |
| 94 | + # Compute the distance matrix for the same set of graphs: |
| 95 | + matrix = model.fit_transform( |
| 96 | + graphs_X, y=graphs_Y, |
| 97 | + save_dm_train=True, repeats=ged_options['repeats'], |
| 98 | + ) |
| 99 | + else: |
| 100 | + model.fit(graphs_X, repeats=ged_options['repeats']) |
| 101 | + matrix = model.transform( |
| 102 | + graphs_Y, |
| 103 | + save_dm_test=True, repeats=ged_options['repeats'], |
| 104 | + ) |
| 105 | + |
| 106 | + except OSError as exception: |
| 107 | + if 'GLIBC_2.23' in exception.args[0]: |
| 108 | + msg = \ |
| 109 | + 'This error is very likely due to the low version of GLIBC ' \ |
| 110 | + 'on your system. ' \ |
| 111 | + 'The required version of GLIBC is 2.23. This may happen on the ' \ |
| 112 | + 'CentOS 7 system, where the highest version of GLIBC is 2.17. ' \ |
| 113 | + 'You may check your CLIBC version by bash command `rpm -q glibc`. ' \ |
| 114 | + 'The `graphkit-learn` library comes with GLIBC_2.23, which you can ' \ |
| 115 | + 'install by enable the `--build-gedlib` option: ' \ |
| 116 | + '`python3 setup.py install --build-gedlib`. This will compile the C++ ' \ |
| 117 | + 'module `gedlib`, which requires a C++ compiler and CMake.' |
| 118 | + raise AssertionError(msg) from exception |
| 119 | + else: |
| 120 | + assert False, exception |
| 121 | + except Exception as exception: |
| 122 | + assert False, exception |
| 123 | + |
| 124 | + # Save history: |
| 125 | + # For graph kernels it is n * (n - 1) / 2: |
| 126 | + if graphs_Y is None: |
| 127 | + n_pairs = len(graphs_X) * (len(graphs_X) - 1) / 2 |
| 128 | + else: |
| 129 | + n_pairs = len(graphs_X) * len(graphs_Y) |
| 130 | + # history = {'run_time': AverageMeter()} |
| 131 | + # history['run_time'].update(model.run_time / n_pairs, n_pairs) |
| 132 | + |
| 133 | + # # Save model and history to file: |
| 134 | + # if read_resu_from_file >= 1: |
| 135 | + # os.makedirs(os.path.dirname(fn_model), exist_ok=True) |
| 136 | + # pickle.dump({'model': model, 'history': history}, open(fn_model, 'wb')) |
| 137 | + |
| 138 | + # Print out the information: |
| 139 | + params_msg = f' for parameters {params_idx}' if params_idx else '' |
| 140 | + print( |
| 141 | + f'{SUCCESS_TAG}Computed metric matrix of size {matrix.shape} in {model.run_time:.3f} ' |
| 142 | + f'seconds ({(model.run_time / n_pairs):.9f} s per pair){params_msg}.' |
| 143 | + ) |
| 144 | + |
| 145 | + stats = { |
| 146 | + 'n_pairs': n_pairs, |
| 147 | + 'matrix_shape': matrix.shape, |
| 148 | + 'run_time': model.run_time, |
| 149 | + 'run_time_per_pair': model.run_time / n_pairs, |
| 150 | + } |
| 151 | + |
| 152 | + return model, matrix, stats |
| 153 | + |
| 154 | + |
| 155 | +def fit_model_ged_test(): |
| 156 | + # Example usage: |
| 157 | + from gklearn.experiments.ged.ged_model.graph_generator import GraphGenerator |
| 158 | + generator = GraphGenerator( |
| 159 | + num_graphs=10, |
| 160 | + max_num_nodes=5, |
| 161 | + min_num_nodes=3, |
| 162 | + max_num_edges=10, |
| 163 | + min_num_edges=5, |
| 164 | + with_discrete_n_features=True, |
| 165 | + with_discrete_e_features=True, |
| 166 | + with_continuous_n_features=True, |
| 167 | + with_continuous_e_features=True, |
| 168 | + # node_features=['color', 'shape'], |
| 169 | + # edge_features=['weight'], |
| 170 | + # node_feature_values={'color': ['red', 'blue'], 'shape': ['circle', 'square']}, |
| 171 | + # edge_feature_values={'weight': [1, 2, 3]}, |
| 172 | + ) |
| 173 | + graphs = generator.generate_graphs() |
| 174 | + ged_options = { |
| 175 | + 'method': 'ged', |
| 176 | + 'edit_cost_fun': 'NON_SYMBOLIC', |
| 177 | + 'edit_costs': [3, 3, 1, 3, 3, 1], |
| 178 | + 'optim_method': 'init', |
| 179 | + 'repeats': 1 |
| 180 | + } |
| 181 | + model, matrix, stats = fit_model_ged(graphs, ged_options) |
| 182 | + print("Model:", model) |
| 183 | + print("Matrix shape:", matrix.shape) |
| 184 | + |
| 185 | + |
| 186 | +if __name__ == '__main__': |
| 187 | + # Test the class |
| 188 | + fit_model_ged_test() |
0 commit comments