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.

model_selection_precomputed.py 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. def model_selection_for_precomputed_kernel(datafile, estimator, param_grid_precomputed, param_grid, model_type, NUM_TRIALS = 30, datafile_y = ''):
  2. """Perform model selection, fitting and testing for precomputed kernels using nested cv. Print out neccessary data during the process then finally the results.
  3. Parameters
  4. ----------
  5. datafile : string
  6. Path of dataset file.
  7. estimator : function
  8. kernel function used to estimate. This function needs to return a gram matrix.
  9. param_grid_precomputed : dictionary
  10. Dictionary with names (string) of parameters used to calculate gram matrices as keys and lists of parameter settings to try as values. This enables searching over any sequence of parameter settings.
  11. param_grid : dictionary
  12. Dictionary with names (string) of parameters used as penelties as keys and lists of parameter settings to try as values. This enables searching over any sequence of parameter settings.
  13. model_type : string
  14. Typr of the problem, can be regression or classification.
  15. NUM_TRIALS : integer
  16. Number of random trials of outer cv loop. The default is 30.
  17. datafile_y : string
  18. Path of file storing y data. This parameter is optional depending on the given dataset file.
  19. Examples
  20. --------
  21. >>> import numpy as np
  22. >>> import sys
  23. >>> sys.path.insert(0, "../")
  24. >>> from pygraph.utils.model_selection_precomputed import model_selection_for_precomputed_kernel
  25. >>> from pygraph.kernels.weisfeilerLehmanKernel import weisfeilerlehmankernel
  26. >>>
  27. >>> datafile = '../../../../datasets/acyclic/Acyclic/dataset_bps.ds'
  28. >>> estimator = weisfeilerlehmankernel
  29. >>> param_grid_precomputed = {'height': [0,1,2,3,4,5,6,7,8,9,10], 'base_kernel': ['subtree']}
  30. >>> param_grid = {"alpha": np.logspace(-2, 2, num = 10, base = 10)}
  31. >>>
  32. >>> model_selection_for_precomputed_kernel(datafile, estimator, param_grid_precomputed, param_grid, 'regression')
  33. """
  34. import numpy as np
  35. from matplotlib import pyplot as plt
  36. from sklearn.kernel_ridge import KernelRidge
  37. from sklearn.svm import SVC
  38. from sklearn.metrics import accuracy_score, mean_squared_error
  39. from sklearn.model_selection import KFold, train_test_split, ParameterGrid
  40. import sys
  41. sys.path.insert(0, "../")
  42. from pygraph.utils.graphfiles import loadDataset
  43. from tqdm import tqdm
  44. # setup the model type
  45. model_type = model_type.lower()
  46. if model_type != 'regression' and model_type != 'classification':
  47. raise Exception('The model type is incorrect! Please choose from regression or classification.')
  48. print()
  49. print('--- This is a %s problem ---' % model_type)
  50. # Load the dataset
  51. print()
  52. print('1. Loading dataset from file...')
  53. dataset, y = loadDataset(datafile, filename_y = datafile_y)
  54. # Grid of parameters with a discrete number of values for each.
  55. param_list_precomputed = list(ParameterGrid(param_grid_precomputed))
  56. param_list = list(ParameterGrid(param_grid))
  57. # Arrays to store scores
  58. train_pref = np.zeros((NUM_TRIALS, len(param_list_precomputed), len(param_list)))
  59. val_pref = np.zeros((NUM_TRIALS, len(param_list_precomputed), len(param_list)))
  60. test_pref = np.zeros((NUM_TRIALS, len(param_list_precomputed), len(param_list)))
  61. gram_matrices = [] # a list to store gram matrices for all param_grid_precomputed
  62. gram_matrix_time = [] # a list to store time to calculate gram matrices
  63. # calculate all gram matrices
  64. print()
  65. print('2. Calculating gram matrices. This could take a while...')
  66. for params_out in param_list_precomputed:
  67. Kmatrix, current_run_time = estimator(dataset, **params_out)
  68. print()
  69. print('gram matrix with parameters', params_out, 'is: ')
  70. print(Kmatrix)
  71. plt.matshow(Kmatrix)
  72. plt.show()
  73. # plt.savefig('../../notebooks/gram_matrix_figs/{}_{}'.format(estimator.__name__, params_out))
  74. gram_matrices.append(Kmatrix)
  75. gram_matrix_time.append(current_run_time)
  76. print()
  77. print('3. Fitting and predicting using nested cross validation. This could really take a while...')
  78. # Loop for each trial
  79. pbar = tqdm(total = NUM_TRIALS * len(param_list_precomputed) * len(param_list),
  80. desc = 'calculate performance', file=sys.stdout)
  81. for trial in range(NUM_TRIALS): # Test set level
  82. # loop for each outer param tuple
  83. for index_out, params_out in enumerate(param_list_precomputed):
  84. # split gram matrix and y to app and test sets.
  85. X_app, X_test, y_app, y_test = train_test_split(gram_matrices[index_out], y, test_size=0.1)
  86. split_index_app = [y.index(y_i) for y_i in y_app if y_i in y]
  87. split_index_test = [y.index(y_i) for y_i in y_test if y_i in y]
  88. X_app = X_app[:,split_index_app]
  89. X_test = X_test[:,split_index_app]
  90. y_app = np.array(y_app)
  91. y_test = np.array(y_test)
  92. # loop for each inner param tuple
  93. for index_in, params_in in enumerate(param_list):
  94. inner_cv = KFold(n_splits=10, shuffle=True, random_state=trial)
  95. current_train_perf = []
  96. current_valid_perf = []
  97. current_test_perf = []
  98. # For regression use the Kernel Ridge method
  99. if model_type == 'regression':
  100. KR = KernelRidge(kernel = 'precomputed', **params_in)
  101. # loop for each split on validation set level
  102. for train_index, valid_index in inner_cv.split(X_app): # validation set level
  103. KR.fit(X_app[train_index,:][:,train_index], y_app[train_index])
  104. # predict on the train, validation and test set
  105. y_pred_train = KR.predict(X_app[train_index,:][:,train_index])
  106. y_pred_valid = KR.predict(X_app[valid_index,:][:,train_index])
  107. y_pred_test = KR.predict(X_test[:,train_index])
  108. # root mean squared errors
  109. current_train_perf.append(np.sqrt(mean_squared_error(y_app[train_index], y_pred_train)))
  110. current_valid_perf.append(np.sqrt(mean_squared_error(y_app[valid_index], y_pred_valid)))
  111. current_test_perf.append(np.sqrt(mean_squared_error(y_test, y_pred_test)))
  112. # For clcassification use SVM
  113. else:
  114. KR = SVC(kernel = 'precomputed', **params_in)
  115. # loop for each split on validation set level
  116. for train_index, valid_index in inner_cv.split(X_app): # validation set level
  117. KR.fit(X_app[train_index,:][:,train_index], y_app[train_index])
  118. # predict on the train, validation and test set
  119. y_pred_train = KR.predict(X_app[train_index,:][:,train_index])
  120. y_pred_valid = KR.predict(X_app[valid_index,:][:,train_index])
  121. y_pred_test = KR.predict(X_test[:,train_index])
  122. # root mean squared errors
  123. current_train_perf.append(accuracy_score(y_app[train_index], y_pred_train))
  124. current_valid_perf.append(accuracy_score(y_app[valid_index], y_pred_valid))
  125. current_test_perf.append(accuracy_score(y_test, y_pred_test))
  126. # average performance on inner splits
  127. train_pref[trial][index_out][index_in] = np.mean(current_train_perf)
  128. val_pref[trial][index_out][index_in] = np.mean(current_valid_perf)
  129. test_pref[trial][index_out][index_in] = np.mean(current_test_perf)
  130. pbar.update(1)
  131. pbar.clear()
  132. print()
  133. print('4. Getting final performances...')
  134. # averages and confidences of performances on outer trials for each combination of parameters
  135. average_train_scores = np.mean(train_pref, axis=0)
  136. average_val_scores = np.mean(val_pref, axis=0)
  137. average_perf_scores = np.mean(test_pref, axis=0)
  138. std_train_scores = np.std(train_pref, axis=0, ddof=1) # sample std is used here
  139. std_val_scores = np.std(val_pref, axis=0, ddof=1)
  140. std_perf_scores = np.std(test_pref, axis=0, ddof=1)
  141. if model_type == 'regression':
  142. best_val_perf = np.amin(average_val_scores)
  143. else:
  144. best_val_perf = np.amax(average_val_scores)
  145. print()
  146. best_params_index = np.where(average_val_scores == best_val_perf)
  147. best_params_out = [param_list_precomputed[i] for i in best_params_index[0]]
  148. best_params_in = [param_list[i] for i in best_params_index[1]]
  149. # print('best_params_index: ', best_params_index)
  150. print('best_params_out: ', best_params_out)
  151. print('best_params_in: ', best_params_in)
  152. print('best_val_perf: ', best_val_perf)
  153. # below: only find one performance; muitiple pref might exist
  154. best_val_std = std_val_scores[best_params_index[0][0]][best_params_index[1][0]]
  155. print('best_val_std: ', best_val_std)
  156. final_performance = average_perf_scores[best_params_index[0][0]][best_params_index[1][0]]
  157. final_confidence = std_perf_scores[best_params_index[0][0]][best_params_index[1][0]]
  158. print('final_performance: ', final_performance)
  159. print('final_confidence: ', final_confidence)
  160. train_performance = average_train_scores[best_params_index[0][0]][best_params_index[1][0]]
  161. train_std = std_train_scores[best_params_index[0][0]][best_params_index[1][0]]
  162. print('train_performance: ', train_performance)
  163. print('train_std: ', train_std)
  164. best_gram_matrix_time = gram_matrix_time[best_params_index[0][0]]
  165. print('time to calculate gram matrix: ', best_gram_matrix_time, 's')
  166. # print out as table.
  167. from collections import OrderedDict
  168. from tabulate import tabulate
  169. table_dict = {}
  170. if model_type == 'regression':
  171. for param_in in param_list:
  172. param_in['alpha'] = '{:.2e}'.format(param_in['alpha'])
  173. else:
  174. for param_in in param_list:
  175. param_in['C'] = '{:.2e}'.format(param_in['C'])
  176. table_dict['params'] = [ {**param_out, **param_in} for param_in in param_list for param_out in param_list_precomputed ]
  177. table_dict['gram_matrix_time'] = [ '{:.2f}'.format(gram_matrix_time[index_out])
  178. for param_in in param_list for index_out, _ in enumerate(param_list_precomputed) ]
  179. table_dict['valid_perf'] = [ '{:.2f}±{:.2f}'.format(average_val_scores[index_out][index_in], std_val_scores[index_out][index_in])
  180. for index_in, _ in enumerate(param_list) for index_out, _ in enumerate(param_list_precomputed) ]
  181. table_dict['test_perf'] = [ '{:.2f}±{:.2f}'.format(average_perf_scores[index_out][index_in], std_perf_scores[index_out][index_in])
  182. for index_in, _ in enumerate(param_list) for index_out, _ in enumerate(param_list_precomputed) ]
  183. table_dict['train_perf'] = [ '{:.2f}±{:.2f}'.format(average_train_scores[index_out][index_in], std_train_scores[index_out][index_in])
  184. for index_in, _ in enumerate(param_list) for index_out, _ in enumerate(param_list_precomputed) ]
  185. keyorder = ['params', 'train_perf', 'valid_perf', 'test_perf', 'gram_matrix_time']
  186. print()
  187. print(tabulate(OrderedDict(sorted(table_dict.items(), key = lambda i:keyorder.index(i[0]))), headers='keys'))

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