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

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

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