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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. def model_selection_for_precomputed_kernel(datafile, estimator,
  2. param_grid_precomputed, param_grid,
  3. model_type, NUM_TRIALS=30,
  4. datafile_y=''):
  5. """Perform model selection, fitting and testing for precomputed kernels using nested cv. Print out neccessary data during the process then finally the results.
  6. Parameters
  7. ----------
  8. datafile : string
  9. Path of dataset file.
  10. estimator : function
  11. kernel function used to estimate. This function needs to return a gram matrix.
  12. param_grid_precomputed : dictionary
  13. 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.
  14. param_grid : dictionary
  15. 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.
  16. model_type : string
  17. Typr of the problem, can be regression or classification.
  18. NUM_TRIALS : integer
  19. Number of random trials of outer cv loop. The default is 30.
  20. datafile_y : string
  21. Path of file storing y data. This parameter is optional depending on the given dataset file.
  22. Examples
  23. --------
  24. >>> import numpy as np
  25. >>> import sys
  26. >>> sys.path.insert(0, "../")
  27. >>> from pygraph.utils.model_selection_precomputed import model_selection_for_precomputed_kernel
  28. >>> from pygraph.kernels.weisfeilerLehmanKernel import weisfeilerlehmankernel
  29. >>>
  30. >>> datafile = '../../../../datasets/acyclic/Acyclic/dataset_bps.ds'
  31. >>> estimator = weisfeilerlehmankernel
  32. >>> param_grid_precomputed = {'height': [0,1,2,3,4,5,6,7,8,9,10], 'base_kernel': ['subtree']}
  33. >>> param_grid = {"alpha": np.logspace(-2, 2, num = 10, base = 10)}
  34. >>>
  35. >>> model_selection_for_precomputed_kernel(datafile, estimator, param_grid_precomputed, param_grid, 'regression')
  36. """
  37. import numpy as np
  38. from matplotlib import pyplot as plt
  39. from sklearn.kernel_ridge import KernelRidge
  40. from sklearn.svm import SVC
  41. from sklearn.metrics import accuracy_score, mean_squared_error
  42. from sklearn.model_selection import KFold, train_test_split, ParameterGrid
  43. import sys
  44. sys.path.insert(0, "../")
  45. import os
  46. from os.path import basename
  47. from pygraph.utils.graphfiles import loadDataset
  48. from tqdm import tqdm
  49. tqdm.monitor_interval = 0
  50. results_dir = '../notebooks/results/' + estimator.__name__
  51. if not os.path.exists(results_dir):
  52. os.makedirs(results_dir)
  53. results_name_pre = results_dir + '/' + basename(datafile) + '_'
  54. # setup the model type
  55. model_type = model_type.lower()
  56. if model_type != 'regression' and model_type != 'classification':
  57. raise Exception(
  58. 'The model type is incorrect! Please choose from regression or classification.')
  59. print()
  60. print('--- This is a %s problem ---' % model_type)
  61. # Load the dataset
  62. print()
  63. print('1. Loading dataset from file...')
  64. dataset, y = loadDataset(datafile, filename_y=datafile_y)
  65. # Grid of parameters with a discrete number of values for each.
  66. param_list_precomputed = list(ParameterGrid(param_grid_precomputed))
  67. param_list = list(ParameterGrid(param_grid))
  68. # np.savetxt(results_name_pre + 'param_grid_precomputed.dt',
  69. # [[key, value] for key, value in sorted(param_grid_precomputed)])
  70. # np.savetxt(results_name_pre + 'param_grid.dt',
  71. # [[key, value] for key, value in sorted(param_grid)])
  72. gram_matrices = [] # a list to store gram matrices for all param_grid_precomputed
  73. gram_matrix_time = [] # a list to store time to calculate gram matrices
  74. param_list_pre_revised = [] # list to store param grids precomputed ignoring the useless ones
  75. # calculate all gram matrices
  76. print()
  77. print('2. Calculating gram matrices. This could take a while...')
  78. nb_gm_ignore = 0 # the number of gram matrices those should not be considered, as they may contain elements that are not numbers (NaN)
  79. for params_out in param_list_precomputed:
  80. print()
  81. print('gram matrix with parameters', params_out, 'is: ')
  82. Kmatrix, current_run_time = estimator(dataset, **params_out)
  83. Kmatrix_diag = Kmatrix.diagonal().copy()
  84. for i in range(len(Kmatrix)):
  85. for j in range(i, len(Kmatrix)):
  86. Kmatrix[i][j] /= np.sqrt(Kmatrix_diag[i] * Kmatrix_diag[j])
  87. Kmatrix[j][i] = Kmatrix[i][j]
  88. if np.isnan(Kmatrix).any(): # if the matrix contains elements that are not numbers
  89. nb_gm_ignore += 1
  90. print('ignored, as it contains elements that are not numbers.')
  91. else:
  92. print(Kmatrix)
  93. plt.matshow(Kmatrix)
  94. plt.colorbar()
  95. fig_name_suffix = '_'.join(['{}-{}'.format(key, val)
  96. for key, val in sorted(params_out.items())])
  97. plt.savefig(
  98. results_name_pre + 'gram_matrix_{}.png'.format(fig_name_suffix))
  99. plt.show()
  100. gram_matrices.append(Kmatrix)
  101. gram_matrix_time.append(current_run_time)
  102. param_list_pre_revised.append(params_out)
  103. np.save(results_name_pre + 'gram_matrices.dt', gram_matrices)
  104. np.save(results_name_pre + 'param_list_precomputed.dt', param_list_pre_revised)
  105. np.save(results_name_pre + 'param_list.dt', param_list)
  106. print()
  107. print('{} gram matrices are calculated, {} of which are ignored.'.format(len(param_list_precomputed), nb_gm_ignore))
  108. print()
  109. print('3. Fitting and predicting using nested cross validation. This could really take a while...')
  110. # Arrays to store scores
  111. train_pref = np.zeros(
  112. (NUM_TRIALS, len(param_list_pre_revised), len(param_list)))
  113. val_pref = np.zeros(
  114. (NUM_TRIALS, len(param_list_pre_revised), len(param_list)))
  115. test_pref = np.zeros(
  116. (NUM_TRIALS, len(param_list_pre_revised), len(param_list)))
  117. # Loop for each trial
  118. pbar = tqdm(total=NUM_TRIALS * len(param_list_pre_revised) * len(param_list),
  119. desc='calculate performance', file=sys.stdout)
  120. for trial in range(NUM_TRIALS): # Test set level
  121. # loop for each outer param tuple
  122. for index_out, params_out in enumerate(param_list_pre_revised):
  123. # split gram matrix and y to app and test sets.
  124. X_app, X_test, y_app, y_test = train_test_split(
  125. gram_matrices[index_out], y, test_size=0.1)
  126. split_index_app = [y.index(y_i) for y_i in y_app if y_i in y]
  127. # split_index_test = [y.index(y_i) for y_i in y_test if y_i in y]
  128. X_app = X_app[:, split_index_app]
  129. X_test = X_test[:, split_index_app]
  130. y_app = np.array(y_app)
  131. y_test = np.array(y_test)
  132. # loop for each inner param tuple
  133. for index_in, params_in in enumerate(param_list):
  134. inner_cv = KFold(n_splits=10, shuffle=True, random_state=trial)
  135. current_train_perf = []
  136. current_valid_perf = []
  137. current_test_perf = []
  138. # For regression use the Kernel Ridge method
  139. try:
  140. if model_type == 'regression':
  141. KR = KernelRidge(kernel='precomputed', **params_in)
  142. # loop for each split on validation set level
  143. # validation set level
  144. for train_index, valid_index in inner_cv.split(X_app):
  145. KR.fit(X_app[train_index, :]
  146. [:, train_index], y_app[train_index])
  147. # predict on the train, validation and test set
  148. y_pred_train = KR.predict(
  149. X_app[train_index, :][:, train_index])
  150. y_pred_valid = KR.predict(
  151. X_app[valid_index, :][:, train_index])
  152. y_pred_test = KR.predict(X_test[:, train_index])
  153. # root mean squared errors
  154. current_train_perf.append(
  155. np.sqrt(mean_squared_error(y_app[train_index], y_pred_train)))
  156. current_valid_perf.append(
  157. np.sqrt(mean_squared_error(y_app[valid_index], y_pred_valid)))
  158. current_test_perf.append(
  159. np.sqrt(mean_squared_error(y_test, y_pred_test)))
  160. # For clcassification use SVM
  161. else:
  162. KR = SVC(kernel='precomputed', **params_in)
  163. # loop for each split on validation set level
  164. # validation set level
  165. for train_index, valid_index in inner_cv.split(X_app):
  166. KR.fit(X_app[train_index, :]
  167. [:, train_index], y_app[train_index])
  168. # predict on the train, validation and test set
  169. y_pred_train = KR.predict(
  170. X_app[train_index, :][:, train_index])
  171. y_pred_valid = KR.predict(
  172. X_app[valid_index, :][:, train_index])
  173. y_pred_test = KR.predict(
  174. X_test[:, train_index])
  175. # root mean squared errors
  176. current_train_perf.append(accuracy_score(
  177. y_app[train_index], y_pred_train))
  178. current_valid_perf.append(accuracy_score(
  179. y_app[valid_index], y_pred_valid))
  180. current_test_perf.append(
  181. accuracy_score(y_test, y_pred_test))
  182. except ValueError:
  183. print(sys.exc_info()[0])
  184. print(params_out, params_in)
  185. # average performance on inner splits
  186. train_pref[trial][index_out][index_in] = np.mean(
  187. current_train_perf)
  188. val_pref[trial][index_out][index_in] = np.mean(
  189. current_valid_perf)
  190. test_pref[trial][index_out][index_in] = np.mean(
  191. current_test_perf)
  192. pbar.update(1)
  193. pbar.clear()
  194. np.save(results_name_pre + 'train_pref.dt', train_pref)
  195. np.save(results_name_pre + 'val_pref.dt', val_pref)
  196. np.save(results_name_pre + 'test_pref.dt', test_pref)
  197. # print('val_pref: ', val_pref) #####
  198. # print(val_pref.shape)
  199. print()
  200. print('4. Getting final performances...')
  201. # averages and confidences of performances on outer trials for each combination of parameters
  202. average_train_scores = np.mean(train_pref, axis=0)
  203. average_val_scores = np.mean(val_pref, axis=0)
  204. # print('average_val_scores: ', average_val_scores) #####
  205. # print(average_val_scores.shape)
  206. average_perf_scores = np.mean(test_pref, axis=0)
  207. # sample std is used here
  208. std_train_scores = np.std(train_pref, axis=0, ddof=1)
  209. std_val_scores = np.std(val_pref, axis=0, ddof=1)
  210. std_perf_scores = np.std(test_pref, axis=0, ddof=1)
  211. if model_type == 'regression':
  212. best_val_perf = np.amin(average_val_scores)
  213. else:
  214. best_val_perf = np.amax(average_val_scores)
  215. # print()
  216. # print('best_val_perf: ', best_val_perf) #####
  217. # print(best_val_perf.shape)
  218. best_params_index = np.where(average_val_scores == best_val_perf)
  219. # print('best_params_index: ', best_params_index) #####
  220. #print(best_params_index[0])
  221. #print(best_params_index[1])
  222. # print(best_params_index.shape)
  223. best_params_out = [param_list_pre_revised[i] for i in best_params_index[0]]
  224. best_params_in = [param_list[i] for i in best_params_index[1]]
  225. # print('best_params_index: ', best_params_index)
  226. print('best_params_out: ', best_params_out)
  227. print('best_params_in: ', best_params_in)
  228. print()
  229. print('best_val_perf: ', best_val_perf)
  230. # below: only find one performance; muitiple pref might exist
  231. best_val_std = std_val_scores[best_params_index[0]
  232. [0]][best_params_index[1][0]]
  233. print('best_val_std: ', best_val_std)
  234. final_performance = average_perf_scores[best_params_index[0]
  235. [0]][best_params_index[1][0]]
  236. final_confidence = std_perf_scores[best_params_index[0]
  237. [0]][best_params_index[1][0]]
  238. print('final_performance: ', final_performance)
  239. print('final_confidence: ', final_confidence)
  240. train_performance = average_train_scores[best_params_index[0]
  241. [0]][best_params_index[1][0]]
  242. train_std = std_train_scores[best_params_index[0]
  243. [0]][best_params_index[1][0]]
  244. print('train_performance: ', train_performance)
  245. print('train_std: ', train_std)
  246. print()
  247. average_gram_matrix_time = np.mean(gram_matrix_time)
  248. std_gram_matrix_time = np.std(gram_matrix_time, ddof=1)
  249. best_gram_matrix_time = gram_matrix_time[best_params_index[0][0]]
  250. print('time to calculate gram matrix with different hyperpapams: {:.2f}±{:.2f}'
  251. .format(average_gram_matrix_time, std_gram_matrix_time))
  252. print('time to calculate best gram matrix: ', best_gram_matrix_time, 's')
  253. # save results to file
  254. np.savetxt(results_name_pre + 'average_train_scores.dt',
  255. average_train_scores)
  256. np.savetxt(results_name_pre + 'average_val_scores', average_val_scores)
  257. np.savetxt(results_name_pre + 'average_perf_scores.dt',
  258. average_perf_scores)
  259. np.savetxt(results_name_pre + 'std_train_scores.dt', std_train_scores)
  260. np.savetxt(results_name_pre + 'std_val_scores.dt', std_val_scores)
  261. np.savetxt(results_name_pre + 'std_perf_scores.dt', std_perf_scores)
  262. np.save(results_name_pre + 'best_params_index', best_params_index)
  263. np.save(results_name_pre + 'best_params_pre.dt', best_params_out)
  264. np.save(results_name_pre + 'best_params_in.dt', best_params_in)
  265. np.save(results_name_pre + 'best_val_perf.dt', best_val_perf)
  266. np.save(results_name_pre + 'best_val_std.dt', best_val_std)
  267. np.save(results_name_pre + 'final_performance.dt', final_performance)
  268. np.save(results_name_pre + 'final_confidence.dt', final_confidence)
  269. np.save(results_name_pre + 'train_performance.dt', train_performance)
  270. np.save(results_name_pre + 'train_std.dt', train_std)
  271. np.save(results_name_pre + 'gram_matrix_time.dt', gram_matrix_time)
  272. np.save(results_name_pre + 'average_gram_matrix_time.dt',
  273. average_gram_matrix_time)
  274. np.save(results_name_pre + 'std_gram_matrix_time.dt',
  275. std_gram_matrix_time)
  276. np.save(results_name_pre + 'best_gram_matrix_time.dt',
  277. best_gram_matrix_time)
  278. # print out as table.
  279. from collections import OrderedDict
  280. from tabulate import tabulate
  281. table_dict = {}
  282. if model_type == 'regression':
  283. for param_in in param_list:
  284. param_in['alpha'] = '{:.2e}'.format(param_in['alpha'])
  285. else:
  286. for param_in in param_list:
  287. param_in['C'] = '{:.2e}'.format(param_in['C'])
  288. table_dict['params'] = [{**param_out, **param_in}
  289. for param_in in param_list for param_out in param_list_pre_revised]
  290. table_dict['gram_matrix_time'] = ['{:.2f}'.format(gram_matrix_time[index_out])
  291. for param_in in param_list for index_out, _ in enumerate(param_list_pre_revised)]
  292. table_dict['valid_perf'] = ['{:.2f}±{:.2f}'.format(average_val_scores[index_out][index_in], std_val_scores[index_out][index_in])
  293. for index_in, _ in enumerate(param_list) for index_out, _ in enumerate(param_list_pre_revised)]
  294. table_dict['test_perf'] = ['{:.2f}±{:.2f}'.format(average_perf_scores[index_out][index_in], std_perf_scores[index_out][index_in])
  295. for index_in, _ in enumerate(param_list) for index_out, _ in enumerate(param_list_pre_revised)]
  296. table_dict['train_perf'] = ['{:.2f}±{:.2f}'.format(average_train_scores[index_out][index_in], std_train_scores[index_out][index_in])
  297. for index_in, _ in enumerate(param_list) for index_out, _ in enumerate(param_list_pre_revised)]
  298. keyorder = ['params', 'train_perf', 'valid_perf',
  299. 'test_perf', 'gram_matrix_time']
  300. print()
  301. print(tabulate(OrderedDict(sorted(table_dict.items(),
  302. key=lambda i: keyorder.index(i[0]))), headers='keys'))
  303. np.save(results_name_pre + 'results_vs_params.dt', table_dict)

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