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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. import numpy as np
  2. import matplotlib
  3. matplotlib.use('Agg')
  4. from matplotlib import pyplot as plt
  5. from sklearn.kernel_ridge import KernelRidge
  6. from sklearn.svm import SVC
  7. from sklearn.metrics import accuracy_score, mean_squared_error
  8. from sklearn.model_selection import KFold, train_test_split, ParameterGrid
  9. #from joblib import Parallel, delayed
  10. from multiprocessing import Pool
  11. from functools import partial
  12. import sys
  13. sys.path.insert(0, "../")
  14. import os
  15. import time
  16. import datetime
  17. #from os.path import basename, splitext
  18. from pygraph.utils.graphfiles import loadDataset
  19. from tqdm import tqdm
  20. def model_selection_for_precomputed_kernel(datafile,
  21. estimator,
  22. param_grid_precomputed,
  23. param_grid,
  24. model_type,
  25. NUM_TRIALS=30,
  26. datafile_y=None,
  27. extra_params=None,
  28. ds_name='ds-unknown',
  29. n_jobs=1,
  30. read_gm_from_file=False):
  31. """Perform model selection, fitting and testing for precomputed kernels using nested cv. Print out neccessary data during the process then finally the results.
  32. Parameters
  33. ----------
  34. datafile : string
  35. Path of dataset file.
  36. estimator : function
  37. kernel function used to estimate. This function needs to return a gram matrix.
  38. param_grid_precomputed : dictionary
  39. 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. Params with length 1 will be omitted.
  40. param_grid : dictionary
  41. 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. Params with length 1 will be omitted.
  42. model_type : string
  43. Typr of the problem, can be regression or classification.
  44. NUM_TRIALS : integer
  45. Number of random trials of outer cv loop. The default is 30.
  46. datafile_y : string
  47. Path of file storing y data. This parameter is optional depending on the given dataset file.
  48. read_gm_from_file : boolean
  49. Whether gram matrices are loaded from file.
  50. Examples
  51. --------
  52. >>> import numpy as np
  53. >>> import sys
  54. >>> sys.path.insert(0, "../")
  55. >>> from pygraph.utils.model_selection_precomputed import model_selection_for_precomputed_kernel
  56. >>> from pygraph.kernels.weisfeilerLehmanKernel import weisfeilerlehmankernel
  57. >>>
  58. >>> datafile = '../../../../datasets/acyclic/Acyclic/dataset_bps.ds'
  59. >>> estimator = weisfeilerlehmankernel
  60. >>> param_grid_precomputed = {'height': [0,1,2,3,4,5,6,7,8,9,10], 'base_kernel': ['subtree']}
  61. >>> param_grid = {"alpha": np.logspace(-2, 2, num = 10, base = 10)}
  62. >>>
  63. >>> model_selection_for_precomputed_kernel(datafile, estimator, param_grid_precomputed, param_grid, 'regression')
  64. """
  65. tqdm.monitor_interval = 0
  66. results_dir = '../notebooks/results/' + estimator.__name__
  67. if not os.path.exists(results_dir):
  68. os.makedirs(results_dir)
  69. # a string to save all the results.
  70. str_fw = '###################### log time: ' + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + '. ######################\n\n'
  71. str_fw += '# This file contains results of ' + estimator.__name__ + ' on dataset ' + ds_name + ',\n# including gram matrices, serial numbers for gram matrix figures and performance.\n\n'
  72. # setup the model type
  73. model_type = model_type.lower()
  74. if model_type != 'regression' and model_type != 'classification':
  75. raise Exception(
  76. 'The model type is incorrect! Please choose from regression or classification.'
  77. )
  78. print()
  79. print('--- This is a %s problem ---' % model_type)
  80. str_fw += 'This is a %s problem.\n' % model_type
  81. # calculate gram matrices rather than read them from file.
  82. if read_gm_from_file == False:
  83. # Load the dataset
  84. print()
  85. print('\n1. Loading dataset from file...')
  86. dataset, y = loadDataset(
  87. datafile, filename_y=datafile_y, extra_params=extra_params)
  88. # import matplotlib.pyplot as plt
  89. # import networkx as nx
  90. # nx.draw_networkx(dataset[30])
  91. # plt.show()
  92. # Grid of parameters with a discrete number of values for each.
  93. param_list_precomputed = list(ParameterGrid(param_grid_precomputed))
  94. param_list = list(ParameterGrid(param_grid))
  95. gram_matrices = [
  96. ] # a list to store gram matrices for all param_grid_precomputed
  97. gram_matrix_time = [
  98. ] # a list to store time to calculate gram matrices
  99. param_list_pre_revised = [
  100. ] # list to store param grids precomputed ignoring the useless ones
  101. # calculate all gram matrices
  102. print()
  103. print('2. Calculating gram matrices. This could take a while...')
  104. str_fw += '\nII. Gram matrices.\n\n'
  105. tts = time.time() # start training time
  106. nb_gm_ignore = 0 # the number of gram matrices those should not be considered, as they may contain elements that are not numbers (NaN)
  107. for idx, params_out in enumerate(param_list_precomputed):
  108. params_out['n_jobs'] = n_jobs
  109. rtn_data = estimator(dataset, **params_out)
  110. Kmatrix = rtn_data[0]
  111. current_run_time = rtn_data[1]
  112. # for some kernels, some graphs in datasets may not meet the
  113. # kernels' requirements for graph structure. These graphs are trimmed.
  114. if len(rtn_data) == 3:
  115. idx_trim = rtn_data[2] # the index of trimmed graph list
  116. y = [y[idxt] for idxt in idx_trim] # trim y accordingly
  117. Kmatrix_diag = Kmatrix.diagonal().copy()
  118. # remove graphs whose kernels with themselves are zeros
  119. nb_g_ignore = 0
  120. for idxk, diag in enumerate(Kmatrix_diag):
  121. if diag == 0:
  122. Kmatrix = np.delete(Kmatrix, (idxk - nb_g_ignore), axis=0)
  123. Kmatrix = np.delete(Kmatrix, (idxk - nb_g_ignore), axis=1)
  124. nb_g_ignore += 1
  125. # normalization
  126. for i in range(len(Kmatrix)):
  127. for j in range(i, len(Kmatrix)):
  128. Kmatrix[i][j] /= np.sqrt(Kmatrix_diag[i] * Kmatrix_diag[j])
  129. Kmatrix[j][i] = Kmatrix[i][j]
  130. print()
  131. if params_out == {}:
  132. print('the gram matrix is: ')
  133. str_fw += 'the gram matrix is:\n\n'
  134. else:
  135. print('the gram matrix with parameters', params_out, 'is: ')
  136. str_fw += 'the gram matrix with parameters %s is:\n\n' % params_out
  137. if len(Kmatrix) < 2:
  138. nb_gm_ignore += 1
  139. print('ignored, as at most only one of all its diagonal value is non-zero.')
  140. str_fw += 'ignored, as at most only one of all its diagonal value is non-zero.\n\n'
  141. else:
  142. if np.isnan(Kmatrix).any(
  143. ): # if the matrix contains elements that are not numbers
  144. nb_gm_ignore += 1
  145. print('ignored, as it contains elements that are not numbers.')
  146. str_fw += 'ignored, as it contains elements that are not numbers.\n\n'
  147. else:
  148. # print(Kmatrix)
  149. str_fw += np.array2string(
  150. Kmatrix,
  151. separator=',') + '\n\n'
  152. # separator=',',
  153. # threshold=np.inf,
  154. # floatmode='unique') + '\n\n'
  155. fig_file_name = results_dir + '/GM[ds]' + ds_name
  156. if params_out != {}:
  157. fig_file_name += '[params]' + str(idx)
  158. plt.imshow(Kmatrix)
  159. plt.colorbar()
  160. plt.savefig(fig_file_name + '.eps', format='eps', dpi=300)
  161. # plt.show()
  162. plt.clf()
  163. gram_matrices.append(Kmatrix)
  164. gram_matrix_time.append(current_run_time)
  165. param_list_pre_revised.append(params_out)
  166. if nb_g_ignore > 0:
  167. print(', where %d graphs are ignored as their graph kernels with themselves are zeros.' % nb_g_ignore)
  168. str_fw += ', where %d graphs are ignored as their graph kernels with themselves are zeros.' % nb_g_ignore
  169. print()
  170. print(
  171. '{} gram matrices are calculated, {} of which are ignored.'.format(
  172. len(param_list_precomputed), nb_gm_ignore))
  173. str_fw += '{} gram matrices are calculated, {} of which are ignored.\n\n'.format(len(param_list_precomputed), nb_gm_ignore)
  174. str_fw += 'serial numbers of gram matrix figures and their corresponding parameters settings:\n\n'
  175. str_fw += ''.join([
  176. '{}: {}\n'.format(idx, params_out)
  177. for idx, params_out in enumerate(param_list_precomputed)
  178. ])
  179. print()
  180. if len(gram_matrices) == 0:
  181. print('all gram matrices are ignored, no results obtained.')
  182. str_fw += '\nall gram matrices are ignored, no results obtained.\n\n'
  183. else:
  184. # save gram matrices to file.
  185. np.savez(results_dir + '/' + ds_name + '.gm',
  186. gms=gram_matrices, params=param_list_pre_revised, y=y,
  187. gmtime=gram_matrix_time)
  188. print(
  189. '3. Fitting and predicting using nested cross validation. This could really take a while...'
  190. )
  191. # pool = Pool(n_jobs)
  192. # trial_do_partial = partial(trial_do, param_list_pre_revised, param_list, gram_matrices, y, model_type)
  193. # train_pref = []
  194. # val_pref = []
  195. # test_pref = []
  196. ## if NUM_TRIALS < 1000 * n_jobs:
  197. ## chunksize = int(NUM_TRIALS / n_jobs) + 1
  198. ## else:
  199. ## chunksize = 1000
  200. # chunksize = 1
  201. # for o1, o2, o3 in tqdm(pool.imap_unordered(trial_do_partial, range(NUM_TRIALS), chunksize), desc='cross validation', file=sys.stdout):
  202. # train_pref.append(o1)
  203. # val_pref.append(o2)
  204. # test_pref.append(o3)
  205. # pool.close()
  206. # pool.join()
  207. # ---- use pool.map to parallel. ----
  208. pool = Pool(n_jobs)
  209. trial_do_partial = partial(trial_do, param_list_pre_revised, param_list, gram_matrices, y, model_type)
  210. result_perf = pool.map(trial_do_partial, range(NUM_TRIALS))
  211. train_pref = [item[0] for item in result_perf]
  212. val_pref = [item[1] for item in result_perf]
  213. test_pref = [item[2] for item in result_perf]
  214. # # ---- direct running, normally use a single CPU core. ----
  215. # train_pref = []
  216. # val_pref = []
  217. # test_pref = []
  218. # for i in tqdm(range(NUM_TRIALS), desc='cross validation', file=sys.stdout):
  219. # o1, o2, o3 = trial_do(param_list_pre_revised, param_list, gram_matrices, y, model_type, i)
  220. # train_pref.append(o1)
  221. # val_pref.append(o2)
  222. # test_pref.append(o3)
  223. # print()
  224. print()
  225. print('4. Getting final performance...')
  226. str_fw += '\nIII. Performance.\n\n'
  227. # averages and confidences of performances on outer trials for each combination of parameters
  228. average_train_scores = np.mean(train_pref, axis=0)
  229. # print('val_pref: ', val_pref[0][0])
  230. average_val_scores = np.mean(val_pref, axis=0)
  231. # print('test_pref: ', test_pref[0][0])
  232. average_perf_scores = np.mean(test_pref, axis=0)
  233. # sample std is used here
  234. std_train_scores = np.std(train_pref, axis=0, ddof=1)
  235. std_val_scores = np.std(val_pref, axis=0, ddof=1)
  236. std_perf_scores = np.std(test_pref, axis=0, ddof=1)
  237. if model_type == 'regression':
  238. best_val_perf = np.amin(average_val_scores)
  239. else:
  240. best_val_perf = np.amax(average_val_scores)
  241. # print('average_val_scores: ', average_val_scores)
  242. # print('best_val_perf: ', best_val_perf)
  243. # print()
  244. best_params_index = np.where(average_val_scores == best_val_perf)
  245. # find smallest val std with best val perf.
  246. best_val_stds = [
  247. std_val_scores[value][best_params_index[1][idx]]
  248. for idx, value in enumerate(best_params_index[0])
  249. ]
  250. min_val_std = np.amin(best_val_stds)
  251. best_params_index = np.where(std_val_scores == min_val_std)
  252. best_params_out = [
  253. param_list_pre_revised[i] for i in best_params_index[0]
  254. ]
  255. best_params_in = [param_list[i] for i in best_params_index[1]]
  256. print('best_params_out: ', best_params_out)
  257. print('best_params_in: ', best_params_in)
  258. print()
  259. print('best_val_perf: ', best_val_perf)
  260. print('best_val_std: ', min_val_std)
  261. str_fw += 'best settings of hyper-params to build gram matrix: %s\n' % best_params_out
  262. str_fw += 'best settings of other hyper-params: %s\n\n' % best_params_in
  263. str_fw += 'best_val_perf: %s\n' % best_val_perf
  264. str_fw += 'best_val_std: %s\n' % min_val_std
  265. # print(best_params_index)
  266. # print(best_params_index[0])
  267. # print(average_perf_scores)
  268. final_performance = [
  269. average_perf_scores[value][best_params_index[1][idx]]
  270. for idx, value in enumerate(best_params_index[0])
  271. ]
  272. final_confidence = [
  273. std_perf_scores[value][best_params_index[1][idx]]
  274. for idx, value in enumerate(best_params_index[0])
  275. ]
  276. print('final_performance: ', final_performance)
  277. print('final_confidence: ', final_confidence)
  278. str_fw += 'final_performance: %s\n' % final_performance
  279. str_fw += 'final_confidence: %s\n' % final_confidence
  280. train_performance = [
  281. average_train_scores[value][best_params_index[1][idx]]
  282. for idx, value in enumerate(best_params_index[0])
  283. ]
  284. train_std = [
  285. std_train_scores[value][best_params_index[1][idx]]
  286. for idx, value in enumerate(best_params_index[0])
  287. ]
  288. print('train_performance: %s' % train_performance)
  289. print('train_std: ', train_std)
  290. str_fw += 'train_performance: %s\n' % train_performance
  291. str_fw += 'train_std: %s\n\n' % train_std
  292. print()
  293. tt_total = time.time() - tts # training time for all hyper-parameters
  294. average_gram_matrix_time = np.mean(gram_matrix_time)
  295. std_gram_matrix_time = np.std(gram_matrix_time, ddof=1)
  296. best_gram_matrix_time = [
  297. gram_matrix_time[i] for i in best_params_index[0]
  298. ]
  299. ave_bgmt = np.mean(best_gram_matrix_time)
  300. std_bgmt = np.std(best_gram_matrix_time, ddof=1)
  301. print(
  302. 'time to calculate gram matrix with different hyper-params: {:.2f}±{:.2f}s'
  303. .format(average_gram_matrix_time, std_gram_matrix_time))
  304. print('time to calculate best gram matrix: {:.2f}±{:.2f}s'.format(
  305. ave_bgmt, std_bgmt))
  306. print(
  307. 'total training time with all hyper-param choices: {:.2f}s'.format(
  308. tt_total))
  309. str_fw += 'time to calculate gram matrix with different hyper-params: {:.2f}±{:.2f}s\n'.format(average_gram_matrix_time, std_gram_matrix_time)
  310. str_fw += 'time to calculate best gram matrix: {:.2f}±{:.2f}s\n'.format(ave_bgmt, std_bgmt)
  311. str_fw += 'total training time with all hyper-param choices: {:.2f}s\n\n'.format(tt_total)
  312. # # save results to file
  313. # np.savetxt(results_name_pre + 'average_train_scores.dt',
  314. # average_train_scores)
  315. # np.savetxt(results_name_pre + 'average_val_scores', average_val_scores)
  316. # np.savetxt(results_name_pre + 'average_perf_scores.dt',
  317. # average_perf_scores)
  318. # np.savetxt(results_name_pre + 'std_train_scores.dt', std_train_scores)
  319. # np.savetxt(results_name_pre + 'std_val_scores.dt', std_val_scores)
  320. # np.savetxt(results_name_pre + 'std_perf_scores.dt', std_perf_scores)
  321. # np.save(results_name_pre + 'best_params_index', best_params_index)
  322. # np.save(results_name_pre + 'best_params_pre.dt', best_params_out)
  323. # np.save(results_name_pre + 'best_params_in.dt', best_params_in)
  324. # np.save(results_name_pre + 'best_val_perf.dt', best_val_perf)
  325. # np.save(results_name_pre + 'best_val_std.dt', best_val_std)
  326. # np.save(results_name_pre + 'final_performance.dt', final_performance)
  327. # np.save(results_name_pre + 'final_confidence.dt', final_confidence)
  328. # np.save(results_name_pre + 'train_performance.dt', train_performance)
  329. # np.save(results_name_pre + 'train_std.dt', train_std)
  330. # np.save(results_name_pre + 'gram_matrix_time.dt', gram_matrix_time)
  331. # np.save(results_name_pre + 'average_gram_matrix_time.dt',
  332. # average_gram_matrix_time)
  333. # np.save(results_name_pre + 'std_gram_matrix_time.dt',
  334. # std_gram_matrix_time)
  335. # np.save(results_name_pre + 'best_gram_matrix_time.dt',
  336. # best_gram_matrix_time)
  337. # print out as table.
  338. from collections import OrderedDict
  339. from tabulate import tabulate
  340. table_dict = {}
  341. if model_type == 'regression':
  342. for param_in in param_list:
  343. param_in['alpha'] = '{:.2e}'.format(param_in['alpha'])
  344. else:
  345. for param_in in param_list:
  346. param_in['C'] = '{:.2e}'.format(param_in['C'])
  347. table_dict['params'] = [{**param_out, **param_in}
  348. for param_in in param_list for param_out in param_list_pre_revised]
  349. table_dict['gram_matrix_time'] = [
  350. '{:.2f}'.format(gram_matrix_time[index_out])
  351. for param_in in param_list
  352. for index_out, _ in enumerate(param_list_pre_revised)
  353. ]
  354. table_dict['valid_perf'] = [
  355. '{:.2f}±{:.2f}'.format(average_val_scores[index_out][index_in],
  356. std_val_scores[index_out][index_in])
  357. for index_in, _ in enumerate(param_list)
  358. for index_out, _ in enumerate(param_list_pre_revised)
  359. ]
  360. table_dict['test_perf'] = [
  361. '{:.2f}±{:.2f}'.format(average_perf_scores[index_out][index_in],
  362. std_perf_scores[index_out][index_in])
  363. for index_in, _ in enumerate(param_list)
  364. for index_out, _ in enumerate(param_list_pre_revised)
  365. ]
  366. table_dict['train_perf'] = [
  367. '{:.2f}±{:.2f}'.format(average_train_scores[index_out][index_in],
  368. std_train_scores[index_out][index_in])
  369. for index_in, _ in enumerate(param_list)
  370. for index_out, _ in enumerate(param_list_pre_revised)
  371. ]
  372. keyorder = [
  373. 'params', 'train_perf', 'valid_perf', 'test_perf',
  374. 'gram_matrix_time'
  375. ]
  376. print()
  377. tb_print = tabulate(
  378. OrderedDict(
  379. sorted(table_dict.items(),
  380. key=lambda i: keyorder.index(i[0]))),
  381. headers='keys')
  382. # print(tb_print)
  383. str_fw += 'table of performance v.s. hyper-params:\n\n%s\n\n' % tb_print
  384. # read gram matrices from file.
  385. else:
  386. # Grid of parameters with a discrete number of values for each.
  387. # param_list_precomputed = list(ParameterGrid(param_grid_precomputed))
  388. param_list = list(ParameterGrid(param_grid))
  389. # read gram matrices from file.
  390. print()
  391. print('2. Reading gram matrices from file...')
  392. str_fw += '\nII. Gram matrices.\n\nGram matrices are read from file, see last log for detail.\n'
  393. gmfile = np.load(results_dir + '/' + ds_name + '.gm.npz')
  394. gram_matrices = gmfile['gms'] # a list to store gram matrices for all param_grid_precomputed
  395. param_list_pre_revised = gmfile['params'] # list to store param grids precomputed ignoring the useless ones
  396. y = gmfile['y'].tolist()
  397. tts = time.time() # start training time
  398. # nb_gm_ignore = 0 # the number of gram matrices those should not be considered, as they may contain elements that are not numbers (NaN)
  399. print(
  400. '3. Fitting and predicting using nested cross validation. This could really take a while...'
  401. )
  402. pool = Pool(n_jobs)
  403. trial_do_partial = partial(trial_do, param_list_pre_revised, param_list, gram_matrices, y, model_type)
  404. train_pref = []
  405. val_pref = []
  406. test_pref = []
  407. if NUM_TRIALS < 100:
  408. chunksize, extra = divmod(NUM_TRIALS, n_jobs * 4)
  409. if extra:
  410. chunksize += 1
  411. else:
  412. chunksize = 100
  413. for o1, o2, o3 in tqdm(pool.imap_unordered(trial_do_partial, range(NUM_TRIALS), chunksize), desc='cross validation', file=sys.stdout):
  414. train_pref.append(o1)
  415. val_pref.append(o2)
  416. test_pref.append(o3)
  417. pool.close()
  418. pool.join()
  419. # # ---- use pool.map to parallel. ----
  420. # result_perf = pool.map(trial_do_partial, range(NUM_TRIALS))
  421. # train_pref = [item[0] for item in result_perf]
  422. # val_pref = [item[1] for item in result_perf]
  423. # test_pref = [item[2] for item in result_perf]
  424. # # ---- use joblib.Parallel to parallel and track progress. ----
  425. # trial_do_partial = partial(trial_do, param_list_pre_revised, param_list, gram_matrices, y, model_type)
  426. # result_perf = Parallel(n_jobs=n_jobs, verbose=10)(delayed(trial_do_partial)(trial) for trial in range(NUM_TRIALS))
  427. # train_pref = [item[0] for item in result_perf]
  428. # val_pref = [item[1] for item in result_perf]
  429. # test_pref = [item[2] for item in result_perf]
  430. # # ---- direct running, normally use a single CPU core. ----
  431. # train_pref = []
  432. # val_pref = []
  433. # test_pref = []
  434. # for i in tqdm(range(NUM_TRIALS), desc='cross validation', file=sys.stdout):
  435. # o1, o2, o3 = trial_do(param_list_pre_revised, param_list, gram_matrices, y, model_type, i)
  436. # train_pref.append(o1)
  437. # val_pref.append(o2)
  438. # test_pref.append(o3)
  439. print()
  440. print('4. Getting final performance...')
  441. str_fw += '\nIII. Performance.\n\n'
  442. # averages and confidences of performances on outer trials for each combination of parameters
  443. average_train_scores = np.mean(train_pref, axis=0)
  444. average_val_scores = np.mean(val_pref, axis=0)
  445. average_perf_scores = np.mean(test_pref, axis=0)
  446. # sample std is used here
  447. std_train_scores = np.std(train_pref, axis=0, ddof=1)
  448. std_val_scores = np.std(val_pref, axis=0, ddof=1)
  449. std_perf_scores = np.std(test_pref, axis=0, ddof=1)
  450. if model_type == 'regression':
  451. best_val_perf = np.amin(average_val_scores)
  452. else:
  453. best_val_perf = np.amax(average_val_scores)
  454. best_params_index = np.where(average_val_scores == best_val_perf)
  455. # find smallest val std with best val perf.
  456. best_val_stds = [
  457. std_val_scores[value][best_params_index[1][idx]]
  458. for idx, value in enumerate(best_params_index[0])
  459. ]
  460. min_val_std = np.amin(best_val_stds)
  461. best_params_index = np.where(std_val_scores == min_val_std)
  462. best_params_out = [
  463. param_list_pre_revised[i] for i in best_params_index[0]
  464. ]
  465. best_params_in = [param_list[i] for i in best_params_index[1]]
  466. print('best_params_out: ', best_params_out)
  467. print('best_params_in: ', best_params_in)
  468. print()
  469. print('best_val_perf: ', best_val_perf)
  470. print('best_val_std: ', min_val_std)
  471. str_fw += 'best settings of hyper-params to build gram matrix: %s\n' % best_params_out
  472. str_fw += 'best settings of other hyper-params: %s\n\n' % best_params_in
  473. str_fw += 'best_val_perf: %s\n' % best_val_perf
  474. str_fw += 'best_val_std: %s\n' % min_val_std
  475. final_performance = [
  476. average_perf_scores[value][best_params_index[1][idx]]
  477. for idx, value in enumerate(best_params_index[0])
  478. ]
  479. final_confidence = [
  480. std_perf_scores[value][best_params_index[1][idx]]
  481. for idx, value in enumerate(best_params_index[0])
  482. ]
  483. print('final_performance: ', final_performance)
  484. print('final_confidence: ', final_confidence)
  485. str_fw += 'final_performance: %s\n' % final_performance
  486. str_fw += 'final_confidence: %s\n' % final_confidence
  487. train_performance = [
  488. average_train_scores[value][best_params_index[1][idx]]
  489. for idx, value in enumerate(best_params_index[0])
  490. ]
  491. train_std = [
  492. std_train_scores[value][best_params_index[1][idx]]
  493. for idx, value in enumerate(best_params_index[0])
  494. ]
  495. print('train_performance: %s' % train_performance)
  496. print('train_std: ', train_std)
  497. str_fw += 'train_performance: %s\n' % train_performance
  498. str_fw += 'train_std: %s\n\n' % train_std
  499. print()
  500. tt_poster = time.time() - tts # training time with hyper-param choices who did not participate in calculation of gram matrices
  501. # average_gram_matrix_time = np.mean(gram_matrix_time)
  502. # std_gram_matrix_time = np.std(gram_matrix_time, ddof=1)
  503. # best_gram_matrix_time = [
  504. # gram_matrix_time[i] for i in best_params_index[0]
  505. # ]
  506. # ave_bgmt = np.mean(best_gram_matrix_time)
  507. # std_bgmt = np.std(best_gram_matrix_time, ddof=1)
  508. # print(
  509. # 'time to calculate gram matrix with different hyper-params: {:.2f}±{:.2f}s'
  510. # .format(average_gram_matrix_time, std_gram_matrix_time))
  511. # print('time to calculate best gram matrix: {:.2f}±{:.2f}s'.format(
  512. # ave_bgmt, std_bgmt))
  513. print(
  514. 'training time with hyper-param choices who did not participate in calculation of gram matrices: {:.2f}s'.format(
  515. tt_poster))
  516. # str_fw += 'time to calculate gram matrix with different hyper-params: {:.2f}±{:.2f}s\n'.format(average_gram_matrix_time, std_gram_matrix_time)
  517. # str_fw += 'time to calculate best gram matrix: {:.2f}±{:.2f}s\n'.format(ave_bgmt, std_bgmt)
  518. str_fw += 'training time with hyper-param choices who did not participate in calculation of gram matrices: {:.2f}s\n\n'.format(tt_poster)
  519. # print out as table.
  520. from collections import OrderedDict
  521. from tabulate import tabulate
  522. table_dict = {}
  523. if model_type == 'regression':
  524. for param_in in param_list:
  525. param_in['alpha'] = '{:.2e}'.format(param_in['alpha'])
  526. else:
  527. for param_in in param_list:
  528. param_in['C'] = '{:.2e}'.format(param_in['C'])
  529. table_dict['params'] = [{**param_out, **param_in}
  530. for param_in in param_list for param_out in param_list_pre_revised]
  531. # table_dict['gram_matrix_time'] = [
  532. # '{:.2f}'.format(gram_matrix_time[index_out])
  533. # for param_in in param_list
  534. # for index_out, _ in enumerate(param_list_pre_revised)
  535. # ]
  536. table_dict['valid_perf'] = [
  537. '{:.2f}±{:.2f}'.format(average_val_scores[index_out][index_in],
  538. std_val_scores[index_out][index_in])
  539. for index_in, _ in enumerate(param_list)
  540. for index_out, _ in enumerate(param_list_pre_revised)
  541. ]
  542. table_dict['test_perf'] = [
  543. '{:.2f}±{:.2f}'.format(average_perf_scores[index_out][index_in],
  544. std_perf_scores[index_out][index_in])
  545. for index_in, _ in enumerate(param_list)
  546. for index_out, _ in enumerate(param_list_pre_revised)
  547. ]
  548. table_dict['train_perf'] = [
  549. '{:.2f}±{:.2f}'.format(average_train_scores[index_out][index_in],
  550. std_train_scores[index_out][index_in])
  551. for index_in, _ in enumerate(param_list)
  552. for index_out, _ in enumerate(param_list_pre_revised)
  553. ]
  554. keyorder = [
  555. 'params', 'train_perf', 'valid_perf', 'test_perf'
  556. ]
  557. print()
  558. tb_print = tabulate(
  559. OrderedDict(
  560. sorted(table_dict.items(),
  561. key=lambda i: keyorder.index(i[0]))),
  562. headers='keys')
  563. print(tb_print)
  564. str_fw += 'table of performance v.s. hyper-params:\n\n%s\n\n' % tb_print
  565. # open file to save all results for this dataset.
  566. if not os.path.exists(results_dir):
  567. os.makedirs(results_dir)
  568. # open file to save all results for this dataset.
  569. if not os.path.exists(results_dir + '/' + ds_name + '.output.txt'):
  570. with open(results_dir + '/' + ds_name + '.output.txt', 'w') as f:
  571. f.write(str_fw)
  572. else:
  573. with open(results_dir + '/' + ds_name + '.output.txt', 'r+') as f:
  574. content = f.read()
  575. f.seek(0, 0)
  576. f.write(str_fw + '\n\n\n' + content)
  577. def trial_do(param_list_pre_revised, param_list, gram_matrices, y, model_type, trial): # Test set level
  578. # Arrays to store scores
  579. train_pref = np.zeros((len(param_list_pre_revised), len(param_list)))
  580. val_pref = np.zeros((len(param_list_pre_revised), len(param_list)))
  581. test_pref = np.zeros((len(param_list_pre_revised), len(param_list)))
  582. # randomness added to seeds of split function below. "high" is "size" times
  583. # 10 so that at least 10 different random output will be yielded. Remove
  584. # these lines if identical outputs is required.
  585. rdm_out = np.random.RandomState(seed=None)
  586. rdm_seed_out_l = rdm_out.uniform(high=len(param_list_pre_revised) * 10,
  587. size=len(param_list_pre_revised))
  588. # print(trial, rdm_seed_out_l)
  589. # print()
  590. # loop for each outer param tuple
  591. for index_out, params_out in enumerate(param_list_pre_revised):
  592. # split gram matrix and y to app and test sets.
  593. indices = range(len(y))
  594. # The argument "random_state" in function "train_test_split" can not be
  595. # set to None, because it will use RandomState instance used by
  596. # np.random, which is possible for multiple subprocesses to inherit the
  597. # same seed if they forked at the same time, leading to identical
  598. # random variates for different subprocesses. Instead, we use "trial"
  599. # and "index_out" parameters to generate different seeds for different
  600. # trials/subprocesses and outer loops. "rdm_seed_out_l" is used to add
  601. # randomness into seeds, so that it yields a different output every
  602. # time the program is run. To yield identical outputs every time,
  603. # remove the second line below. Same method is used to the "KFold"
  604. # function in the inner loop.
  605. rdm_seed_out = (trial + 1) * (index_out + 1)
  606. rdm_seed_out = (rdm_seed_out + int(rdm_seed_out_l[index_out])) % (2 ** 32 - 1)
  607. # print(trial, rdm_seed_out)
  608. X_app, X_test, y_app, y_test, idx_app, idx_test = train_test_split(
  609. gram_matrices[index_out], y, indices, test_size=0.1,
  610. random_state=rdm_seed_out, shuffle=True)
  611. # print(trial, idx_app, idx_test)
  612. # print()
  613. X_app = X_app[:, idx_app]
  614. X_test = X_test[:, idx_app]
  615. y_app = np.array(y_app)
  616. y_test = np.array(y_test)
  617. rdm_seed_in_l = rdm_out.uniform(high=len(param_list) * 10,
  618. size=len(param_list))
  619. # loop for each inner param tuple
  620. for index_in, params_in in enumerate(param_list):
  621. # if trial == 0:
  622. # print(index_out, index_in)
  623. # print('params_in: ', params_in)
  624. # st = time.time()
  625. rdm_seed_in = (trial + 1) * (index_out + 1) * (index_in + 1)
  626. # print("rdm_seed_in1: ", trial, index_in, rdm_seed_in)
  627. rdm_seed_in = (rdm_seed_in + int(rdm_seed_in_l[index_in])) % (2 ** 32 - 1)
  628. # print("rdm_seed_in2: ", trial, index_in, rdm_seed_in)
  629. inner_cv = KFold(n_splits=10, shuffle=True, random_state=rdm_seed_in)
  630. current_train_perf = []
  631. current_valid_perf = []
  632. current_test_perf = []
  633. # For regression use the Kernel Ridge method
  634. # try:
  635. if model_type == 'regression':
  636. kr = KernelRidge(kernel='precomputed', **params_in)
  637. # loop for each split on validation set level
  638. # validation set level
  639. for train_index, valid_index in inner_cv.split(X_app):
  640. # print("train_index, valid_index: ", trial, index_in, train_index, valid_index)
  641. # if trial == 0:
  642. # print('train_index: ', train_index)
  643. # print('valid_index: ', valid_index)
  644. # print('idx_test: ', idx_test)
  645. # print('y_app[train_index]: ', y_app[train_index])
  646. # print('X_app[train_index, :][:, train_index]: ', X_app[train_index, :][:, train_index])
  647. # print('X_app[valid_index, :][:, train_index]: ', X_app[valid_index, :][:, train_index])
  648. kr.fit(X_app[train_index, :][:, train_index],
  649. y_app[train_index])
  650. # predict on the train, validation and test set
  651. y_pred_train = kr.predict(
  652. X_app[train_index, :][:, train_index])
  653. y_pred_valid = kr.predict(
  654. X_app[valid_index, :][:, train_index])
  655. # if trial == 0:
  656. # print('y_pred_valid: ', y_pred_valid)
  657. # print()
  658. y_pred_test = kr.predict(
  659. X_test[:, train_index])
  660. # root mean squared errors
  661. current_train_perf.append(
  662. np.sqrt(
  663. mean_squared_error(
  664. y_app[train_index], y_pred_train)))
  665. current_valid_perf.append(
  666. np.sqrt(
  667. mean_squared_error(
  668. y_app[valid_index], y_pred_valid)))
  669. # if trial == 0:
  670. # print(mean_squared_error(
  671. # y_app[valid_index], y_pred_valid))
  672. current_test_perf.append(
  673. np.sqrt(
  674. mean_squared_error(
  675. y_test, y_pred_test)))
  676. # For clcassification use SVM
  677. else:
  678. svc = SVC(kernel='precomputed', cache_size=200,
  679. verbose=False, **params_in)
  680. # loop for each split on validation set level
  681. # validation set level
  682. for train_index, valid_index in inner_cv.split(X_app):
  683. # np.savez("bug.npy",X_app[train_index, :][:, train_index],y_app[train_index])
  684. # if trial == 0:
  685. # print('train_index: ', train_index)
  686. # print('valid_index: ', valid_index)
  687. # print('idx_test: ', idx_test)
  688. # print('y_app[train_index]: ', y_app[train_index])
  689. # print('X_app[train_index, :][:, train_index]: ', X_app[train_index, :][:, train_index])
  690. # print('X_app[valid_index, :][:, train_index]: ', X_app[valid_index, :][:, train_index])
  691. svc.fit(X_app[train_index, :][:, train_index],
  692. y_app[train_index])
  693. # predict on the train, validation and test set
  694. y_pred_train = svc.predict(
  695. X_app[train_index, :][:, train_index])
  696. y_pred_valid = svc.predict(
  697. X_app[valid_index, :][:, train_index])
  698. y_pred_test = svc.predict(
  699. X_test[:, train_index])
  700. # root mean squared errors
  701. current_train_perf.append(
  702. accuracy_score(y_app[train_index],
  703. y_pred_train))
  704. current_valid_perf.append(
  705. accuracy_score(y_app[valid_index],
  706. y_pred_valid))
  707. current_test_perf.append(
  708. accuracy_score(y_test, y_pred_test))
  709. # except ValueError:
  710. # print(sys.exc_info()[0])
  711. # print(params_out, params_in)
  712. # average performance on inner splits
  713. train_pref[index_out][index_in] = np.mean(
  714. current_train_perf)
  715. val_pref[index_out][index_in] = np.mean(
  716. current_valid_perf)
  717. test_pref[index_out][index_in] = np.mean(
  718. current_test_perf)
  719. # print(time.time() - st)
  720. # if trial == 0:
  721. # print('val_pref: ', val_pref)
  722. # print('test_pref: ', test_pref)
  723. return train_pref, val_pref, test_pref

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