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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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. # read gram matrices from file.
  396. else:
  397. # Grid of parameters with a discrete number of values for each.
  398. # param_list_precomputed = list(ParameterGrid(param_grid_precomputed))
  399. param_list = list(ParameterGrid(param_grid))
  400. # read gram matrices from file.
  401. if verbose:
  402. print()
  403. print('2. Reading gram matrices from file...')
  404. str_fw += '\nII. Gram matrices.\n\nGram matrices are read from file, see last log for detail.\n'
  405. gmfile = np.load(results_dir + '/' + ds_name + '.gm.npz')
  406. gram_matrices = gmfile['gms'] # a list to store gram matrices for all param_grid_precomputed
  407. gram_matrix_time = gmfile['gmtime'] # time used to compute the gram matrices
  408. param_list_pre_revised = gmfile['params'] # list to store param grids precomputed ignoring the useless ones
  409. y = gmfile['y'].tolist()
  410. tts = time.time() # start training time
  411. # nb_gm_ignore = 0 # the number of gram matrices those should not be considered, as they may contain elements that are not numbers (NaN)
  412. if verbose:
  413. print(
  414. '3. Fitting and predicting using nested cross validation. This could really take a while...'
  415. )
  416. # ---- use pool.imap_unordered to parallel and track progress. ----
  417. def init_worker(gms_toshare):
  418. global G_gms
  419. G_gms = gms_toshare
  420. pool = Pool(processes=n_jobs, initializer=init_worker, initargs=(gram_matrices,))
  421. trial_do_partial = partial(parallel_trial_do, param_list_pre_revised, param_list, y, model_type)
  422. train_pref = []
  423. val_pref = []
  424. test_pref = []
  425. chunksize = 1
  426. if verbose:
  427. iterator = tqdm(pool.imap_unordered(trial_do_partial,
  428. range(NUM_TRIALS), chunksize), desc='cross validation', file=sys.stdout)
  429. else:
  430. iterator = pool.imap_unordered(trial_do_partial, range(NUM_TRIALS), chunksize)
  431. for o1, o2, o3 in iterator:
  432. train_pref.append(o1)
  433. val_pref.append(o2)
  434. test_pref.append(o3)
  435. pool.close()
  436. pool.join()
  437. # # ---- use pool.map to parallel. ----
  438. # result_perf = pool.map(trial_do_partial, range(NUM_TRIALS))
  439. # train_pref = [item[0] for item in result_perf]
  440. # val_pref = [item[1] for item in result_perf]
  441. # test_pref = [item[2] for item in result_perf]
  442. # # ---- use joblib.Parallel to parallel and track progress. ----
  443. # trial_do_partial = partial(trial_do, param_list_pre_revised, param_list, gram_matrices, y, model_type)
  444. # result_perf = Parallel(n_jobs=n_jobs, verbose=10)(delayed(trial_do_partial)(trial) for trial in range(NUM_TRIALS))
  445. # train_pref = [item[0] for item in result_perf]
  446. # val_pref = [item[1] for item in result_perf]
  447. # test_pref = [item[2] for item in result_perf]
  448. # # ---- direct running, normally use a single CPU core. ----
  449. # train_pref = []
  450. # val_pref = []
  451. # test_pref = []
  452. # for i in tqdm(range(NUM_TRIALS), desc='cross validation', file=sys.stdout):
  453. # o1, o2, o3 = trial_do(param_list_pre_revised, param_list, gram_matrices, y, model_type, i)
  454. # train_pref.append(o1)
  455. # val_pref.append(o2)
  456. # test_pref.append(o3)
  457. if verbose:
  458. print()
  459. print('4. Getting final performance...')
  460. str_fw += '\nIII. Performance.\n\n'
  461. # averages and confidences of performances on outer trials for each combination of parameters
  462. average_train_scores = np.mean(train_pref, axis=0)
  463. average_val_scores = np.mean(val_pref, axis=0)
  464. average_perf_scores = np.mean(test_pref, axis=0)
  465. # sample std is used here
  466. std_train_scores = np.std(train_pref, axis=0, ddof=1)
  467. std_val_scores = np.std(val_pref, axis=0, ddof=1)
  468. std_perf_scores = np.std(test_pref, axis=0, ddof=1)
  469. if model_type == 'regression':
  470. best_val_perf = np.amin(average_val_scores)
  471. else:
  472. best_val_perf = np.amax(average_val_scores)
  473. best_params_index = np.where(average_val_scores == best_val_perf)
  474. # find smallest val std with best val perf.
  475. best_val_stds = [
  476. std_val_scores[value][best_params_index[1][idx]]
  477. for idx, value in enumerate(best_params_index[0])
  478. ]
  479. min_val_std = np.amin(best_val_stds)
  480. best_params_index = np.where(std_val_scores == min_val_std)
  481. best_params_out = [
  482. param_list_pre_revised[i] for i in best_params_index[0]
  483. ]
  484. best_params_in = [param_list[i] for i in best_params_index[1]]
  485. if verbose:
  486. print('best_params_out: ', best_params_out)
  487. print('best_params_in: ', best_params_in)
  488. print()
  489. print('best_val_perf: ', best_val_perf)
  490. print('best_val_std: ', min_val_std)
  491. str_fw += 'best settings of hyper-params to build gram matrix: %s\n' % best_params_out
  492. str_fw += 'best settings of other hyper-params: %s\n\n' % best_params_in
  493. str_fw += 'best_val_perf: %s\n' % best_val_perf
  494. str_fw += 'best_val_std: %s\n' % min_val_std
  495. final_performance = [
  496. average_perf_scores[value][best_params_index[1][idx]]
  497. for idx, value in enumerate(best_params_index[0])
  498. ]
  499. final_confidence = [
  500. std_perf_scores[value][best_params_index[1][idx]]
  501. for idx, value in enumerate(best_params_index[0])
  502. ]
  503. if verbose:
  504. print('final_performance: ', final_performance)
  505. print('final_confidence: ', final_confidence)
  506. str_fw += 'final_performance: %s\n' % final_performance
  507. str_fw += 'final_confidence: %s\n' % final_confidence
  508. train_performance = [
  509. average_train_scores[value][best_params_index[1][idx]]
  510. for idx, value in enumerate(best_params_index[0])
  511. ]
  512. train_std = [
  513. std_train_scores[value][best_params_index[1][idx]]
  514. for idx, value in enumerate(best_params_index[0])
  515. ]
  516. if verbose:
  517. print('train_performance: %s' % train_performance)
  518. print('train_std: ', train_std)
  519. str_fw += 'train_performance: %s\n' % train_performance
  520. str_fw += 'train_std: %s\n\n' % train_std
  521. if verbose:
  522. print()
  523. average_gram_matrix_time = np.mean(gram_matrix_time)
  524. std_gram_matrix_time = np.std(gram_matrix_time, ddof=1) if len(gram_matrix_time) > 1 else 0
  525. best_gram_matrix_time = [
  526. gram_matrix_time[i] for i in best_params_index[0]
  527. ]
  528. ave_bgmt = np.mean(best_gram_matrix_time)
  529. std_bgmt = np.std(best_gram_matrix_time, ddof=1) if len(best_gram_matrix_time) > 1 else 0
  530. if verbose:
  531. print(
  532. 'time to calculate gram matrix with different hyper-params: {:.2f}±{:.2f}s'
  533. .format(average_gram_matrix_time, std_gram_matrix_time))
  534. print('time to calculate best gram matrix: {:.2f}±{:.2f}s'.format(
  535. ave_bgmt, std_bgmt))
  536. tt_poster = time.time() - tts # training time with hyper-param choices who did not participate in calculation of gram matrices
  537. if verbose:
  538. print(
  539. 'training time with hyper-param choices who did not participate in calculation of gram matrices: {:.2f}s'.format(
  540. tt_poster))
  541. print('total training time with all hyper-param choices: {:.2f}s'.format(
  542. tt_poster + np.sum(gram_matrix_time)))
  543. # str_fw += 'time to calculate gram matrix with different hyper-params: {:.2f}±{:.2f}s\n'.format(average_gram_matrix_time, std_gram_matrix_time)
  544. # str_fw += 'time to calculate best gram matrix: {:.2f}±{:.2f}s\n'.format(ave_bgmt, std_bgmt)
  545. str_fw += 'training time with hyper-param choices who did not participate in calculation of gram matrices: {:.2f}s\n\n'.format(tt_poster)
  546. # open file to save all results for this dataset.
  547. if not os.path.exists(results_dir):
  548. os.makedirs(results_dir)
  549. # print out results as table.
  550. str_fw += printResultsInTable(param_list, param_list_pre_revised, average_val_scores,
  551. std_val_scores, average_perf_scores, std_perf_scores,
  552. average_train_scores, std_train_scores, gram_matrix_time,
  553. model_type, verbose)
  554. # open file to save all results for this dataset.
  555. if not os.path.exists(results_dir + '/' + ds_name + '.output.txt'):
  556. with open(results_dir + '/' + ds_name + '.output.txt', 'w') as f:
  557. f.write(str_fw)
  558. else:
  559. with open(results_dir + '/' + ds_name + '.output.txt', 'r+') as f:
  560. content = f.read()
  561. f.seek(0, 0)
  562. f.write(str_fw + '\n\n\n' + content)
  563. def trial_do(param_list_pre_revised, param_list, gram_matrices, y, model_type, trial): # Test set level
  564. # # get gram matrices from global variables.
  565. # gram_matrices = np.reshape(G_gms.copy(), G_gms_shape, order='C')
  566. # Arrays to store scores
  567. train_pref = np.zeros((len(param_list_pre_revised), len(param_list)))
  568. val_pref = np.zeros((len(param_list_pre_revised), len(param_list)))
  569. test_pref = np.zeros((len(param_list_pre_revised), len(param_list)))
  570. # randomness added to seeds of split function below. "high" is "size" times
  571. # 10 so that at least 10 different random output will be yielded. Remove
  572. # these lines if identical outputs is required.
  573. rdm_out = np.random.RandomState(seed=None)
  574. rdm_seed_out_l = rdm_out.uniform(high=len(param_list_pre_revised) * 10,
  575. size=len(param_list_pre_revised))
  576. # print(trial, rdm_seed_out_l)
  577. # print()
  578. # loop for each outer param tuple
  579. for index_out, params_out in enumerate(param_list_pre_revised):
  580. # get gram matrices from global variables.
  581. # 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]]
  582. # gm_now = np.reshape(gm_now.copy(), (G_gms_shape[1], G_gms_shape[2]), order='C')
  583. gm_now = gram_matrices[index_out].copy()
  584. # split gram matrix and y to app and test sets.
  585. indices = range(len(y))
  586. # The argument "random_state" in function "train_test_split" can not be
  587. # set to None, because it will use RandomState instance used by
  588. # np.random, which is possible for multiple subprocesses to inherit the
  589. # same seed if they forked at the same time, leading to identical
  590. # random variates for different subprocesses. Instead, we use "trial"
  591. # and "index_out" parameters to generate different seeds for different
  592. # trials/subprocesses and outer loops. "rdm_seed_out_l" is used to add
  593. # randomness into seeds, so that it yields a different output every
  594. # time the program is run. To yield identical outputs every time,
  595. # remove the second line below. Same method is used to the "KFold"
  596. # function in the inner loop.
  597. rdm_seed_out = (trial + 1) * (index_out + 1)
  598. rdm_seed_out = (rdm_seed_out + int(rdm_seed_out_l[index_out])) % (2 ** 32 - 1)
  599. # print(trial, rdm_seed_out)
  600. X_app, X_test, y_app, y_test, idx_app, idx_test = train_test_split(
  601. gm_now, y, indices, test_size=0.1,
  602. random_state=rdm_seed_out, shuffle=True)
  603. # print(trial, idx_app, idx_test)
  604. # print()
  605. X_app = X_app[:, idx_app]
  606. X_test = X_test[:, idx_app]
  607. y_app = np.array(y_app)
  608. y_test = np.array(y_test)
  609. rdm_seed_in_l = rdm_out.uniform(high=len(param_list) * 10,
  610. size=len(param_list))
  611. # loop for each inner param tuple
  612. for index_in, params_in in enumerate(param_list):
  613. # if trial == 0:
  614. # print(index_out, index_in)
  615. # print('params_in: ', params_in)
  616. # st = time.time()
  617. rdm_seed_in = (trial + 1) * (index_out + 1) * (index_in + 1)
  618. # print("rdm_seed_in1: ", trial, index_in, rdm_seed_in)
  619. rdm_seed_in = (rdm_seed_in + int(rdm_seed_in_l[index_in])) % (2 ** 32 - 1)
  620. # print("rdm_seed_in2: ", trial, index_in, rdm_seed_in)
  621. inner_cv = KFold(n_splits=10, shuffle=True, random_state=rdm_seed_in)
  622. current_train_perf = []
  623. current_valid_perf = []
  624. current_test_perf = []
  625. # For regression use the Kernel Ridge method
  626. # try:
  627. if model_type == 'regression':
  628. kr = KernelRidge(kernel='precomputed', **params_in)
  629. # loop for each split on validation set level
  630. # validation set level
  631. for train_index, valid_index in inner_cv.split(X_app):
  632. # print("train_index, valid_index: ", trial, index_in, train_index, valid_index)
  633. # if trial == 0:
  634. # print('train_index: ', train_index)
  635. # print('valid_index: ', valid_index)
  636. # print('idx_test: ', idx_test)
  637. # print('y_app[train_index]: ', y_app[train_index])
  638. # print('X_app[train_index, :][:, train_index]: ', X_app[train_index, :][:, train_index])
  639. # print('X_app[valid_index, :][:, train_index]: ', X_app[valid_index, :][:, train_index])
  640. kr.fit(X_app[train_index, :][:, train_index],
  641. y_app[train_index])
  642. # predict on the train, validation and test set
  643. y_pred_train = kr.predict(
  644. X_app[train_index, :][:, train_index])
  645. y_pred_valid = kr.predict(
  646. X_app[valid_index, :][:, train_index])
  647. # if trial == 0:
  648. # print('y_pred_valid: ', y_pred_valid)
  649. # print()
  650. y_pred_test = kr.predict(
  651. X_test[:, train_index])
  652. # root mean squared errors
  653. current_train_perf.append(
  654. np.sqrt(
  655. mean_squared_error(
  656. y_app[train_index], y_pred_train)))
  657. current_valid_perf.append(
  658. np.sqrt(
  659. mean_squared_error(
  660. y_app[valid_index], y_pred_valid)))
  661. # if trial == 0:
  662. # print(mean_squared_error(
  663. # y_app[valid_index], y_pred_valid))
  664. current_test_perf.append(
  665. np.sqrt(
  666. mean_squared_error(
  667. y_test, y_pred_test)))
  668. # For clcassification use SVM
  669. else:
  670. svc = SVC(kernel='precomputed', cache_size=200,
  671. verbose=False, **params_in)
  672. # loop for each split on validation set level
  673. # validation set level
  674. for train_index, valid_index in inner_cv.split(X_app):
  675. # np.savez("bug.npy",X_app[train_index, :][:, train_index],y_app[train_index])
  676. # if trial == 0:
  677. # print('train_index: ', train_index)
  678. # print('valid_index: ', valid_index)
  679. # print('idx_test: ', idx_test)
  680. # print('y_app[train_index]: ', y_app[train_index])
  681. # print('X_app[train_index, :][:, train_index]: ', X_app[train_index, :][:, train_index])
  682. # print('X_app[valid_index, :][:, train_index]: ', X_app[valid_index, :][:, train_index])
  683. svc.fit(X_app[train_index, :][:, train_index],
  684. y_app[train_index])
  685. # predict on the train, validation and test set
  686. y_pred_train = svc.predict(
  687. X_app[train_index, :][:, train_index])
  688. y_pred_valid = svc.predict(
  689. X_app[valid_index, :][:, train_index])
  690. y_pred_test = svc.predict(
  691. X_test[:, train_index])
  692. # root mean squared errors
  693. current_train_perf.append(
  694. accuracy_score(y_app[train_index],
  695. y_pred_train))
  696. current_valid_perf.append(
  697. accuracy_score(y_app[valid_index],
  698. y_pred_valid))
  699. current_test_perf.append(
  700. accuracy_score(y_test, y_pred_test))
  701. # except ValueError:
  702. # print(sys.exc_info()[0])
  703. # print(params_out, params_in)
  704. # average performance on inner splits
  705. train_pref[index_out][index_in] = np.mean(
  706. current_train_perf)
  707. val_pref[index_out][index_in] = np.mean(
  708. current_valid_perf)
  709. test_pref[index_out][index_in] = np.mean(
  710. current_test_perf)
  711. # print(time.time() - st)
  712. # if trial == 0:
  713. # print('val_pref: ', val_pref)
  714. # print('test_pref: ', test_pref)
  715. return train_pref, val_pref, test_pref
  716. def parallel_trial_do(param_list_pre_revised, param_list, y, model_type, trial):
  717. train_pref, val_pref, test_pref = trial_do(param_list_pre_revised,
  718. param_list, G_gms, y,
  719. model_type, trial)
  720. return train_pref, val_pref, test_pref
  721. def compute_gram_matrices(dataset, y, estimator, param_list_precomputed,
  722. results_dir, ds_name,
  723. n_jobs=1, str_fw='', verbose=True):
  724. gram_matrices = [
  725. ] # a list to store gram matrices for all param_grid_precomputed
  726. gram_matrix_time = [
  727. ] # a list to store time to calculate gram matrices
  728. param_list_pre_revised = [
  729. ] # list to store param grids precomputed ignoring the useless ones
  730. nb_gm_ignore = 0 # the number of gram matrices those should not be considered, as they may contain elements that are not numbers (NaN)
  731. for idx, params_out in enumerate(param_list_precomputed):
  732. params_out['n_jobs'] = n_jobs
  733. # print(dataset)
  734. # import networkx as nx
  735. # nx.draw_networkx(dataset[1])
  736. # plt.show()
  737. rtn_data = estimator(dataset[:], **params_out)
  738. Kmatrix = rtn_data[0]
  739. current_run_time = rtn_data[1]
  740. # for some kernels, some graphs in datasets may not meet the
  741. # kernels' requirements for graph structure. These graphs are trimmed.
  742. if len(rtn_data) == 3:
  743. idx_trim = rtn_data[2] # the index of trimmed graph list
  744. y = [y[idxt] for idxt in idx_trim] # trim y accordingly
  745. Kmatrix_diag = Kmatrix.diagonal().copy()
  746. # remove graphs whose kernels with themselves are zeros
  747. nb_g_ignore = 0
  748. for idxk, diag in enumerate(Kmatrix_diag):
  749. if diag == 0:
  750. Kmatrix = np.delete(Kmatrix, (idxk - nb_g_ignore), axis=0)
  751. Kmatrix = np.delete(Kmatrix, (idxk - nb_g_ignore), axis=1)
  752. nb_g_ignore += 1
  753. # normalization
  754. for i in range(len(Kmatrix)):
  755. for j in range(i, len(Kmatrix)):
  756. Kmatrix[i][j] /= np.sqrt(Kmatrix_diag[i] * Kmatrix_diag[j])
  757. Kmatrix[j][i] = Kmatrix[i][j]
  758. if verbose:
  759. print()
  760. if params_out == {}:
  761. if verbose:
  762. print('the gram matrix is: ')
  763. str_fw += 'the gram matrix is:\n\n'
  764. else:
  765. if verbose:
  766. print('the gram matrix with parameters', params_out, 'is: ')
  767. str_fw += 'the gram matrix with parameters %s is:\n\n' % params_out
  768. if len(Kmatrix) < 2:
  769. nb_gm_ignore += 1
  770. if verbose:
  771. print('ignored, as at most only one of all its diagonal value is non-zero.')
  772. str_fw += 'ignored, as at most only one of all its diagonal value is non-zero.\n\n'
  773. else:
  774. if np.isnan(Kmatrix).any(
  775. ): # if the matrix contains elements that are not numbers
  776. nb_gm_ignore += 1
  777. if verbose:
  778. print('ignored, as it contains elements that are not numbers.')
  779. str_fw += 'ignored, as it contains elements that are not numbers.\n\n'
  780. else:
  781. # print(Kmatrix)
  782. str_fw += np.array2string(
  783. Kmatrix,
  784. separator=',') + '\n\n'
  785. # separator=',',
  786. # threshold=np.inf,
  787. # floatmode='unique') + '\n\n'
  788. fig_file_name = results_dir + '/GM[ds]' + ds_name
  789. if params_out != {}:
  790. fig_file_name += '[params]' + str(idx)
  791. plt.imshow(Kmatrix)
  792. plt.colorbar()
  793. plt.savefig(fig_file_name + '.eps', format='eps', dpi=300)
  794. # plt.show()
  795. plt.clf()
  796. gram_matrices.append(Kmatrix)
  797. gram_matrix_time.append(current_run_time)
  798. param_list_pre_revised.append(params_out)
  799. if nb_g_ignore > 0:
  800. if verbose:
  801. print(', where %d graphs are ignored as their graph kernels with themselves are zeros.' % nb_g_ignore)
  802. str_fw += ', where %d graphs are ignored as their graph kernels with themselves are zeros.' % nb_g_ignore
  803. if verbose:
  804. print()
  805. print(
  806. '{} gram matrices are calculated, {} of which are ignored.'.format(
  807. len(param_list_precomputed), nb_gm_ignore))
  808. str_fw += '{} gram matrices are calculated, {} of which are ignored.\n\n'.format(len(param_list_precomputed), nb_gm_ignore)
  809. str_fw += 'serial numbers of gram matrix figures and their corresponding parameters settings:\n\n'
  810. str_fw += ''.join([
  811. '{}: {}\n'.format(idx, params_out)
  812. for idx, params_out in enumerate(param_list_precomputed)
  813. ])
  814. return gram_matrices, gram_matrix_time, param_list_pre_revised, y, str_fw
  815. def read_gram_matrices_from_file(results_dir, ds_name):
  816. gmfile = np.load(results_dir + '/' + ds_name + '.gm.npz')
  817. gram_matrices = gmfile['gms'] # a list to store gram matrices for all param_grid_precomputed
  818. param_list_pre_revised = gmfile['params'] # list to store param grids precomputed ignoring the useless ones
  819. y = gmfile['y'].tolist()
  820. return gram_matrices, param_list_pre_revised, y
  821. def printResultsInTable(param_list, param_list_pre_revised, average_val_scores,
  822. std_val_scores, average_perf_scores, std_perf_scores,
  823. average_train_scores, std_train_scores, gram_matrix_time,
  824. model_type, verbose):
  825. from collections import OrderedDict
  826. from tabulate import tabulate
  827. table_dict = {}
  828. if model_type == 'regression':
  829. for param_in in param_list:
  830. param_in['alpha'] = '{:.2e}'.format(param_in['alpha'])
  831. else:
  832. for param_in in param_list:
  833. param_in['C'] = '{:.2e}'.format(param_in['C'])
  834. table_dict['params'] = [{**param_out, **param_in}
  835. for param_in in param_list for param_out in param_list_pre_revised]
  836. table_dict['gram_matrix_time'] = [
  837. '{:.2f}'.format(gram_matrix_time[index_out])
  838. for param_in in param_list
  839. for index_out, _ in enumerate(param_list_pre_revised)
  840. ]
  841. table_dict['valid_perf'] = [
  842. '{:.2f}±{:.2f}'.format(average_val_scores[index_out][index_in],
  843. std_val_scores[index_out][index_in])
  844. for index_in, _ in enumerate(param_list)
  845. for index_out, _ in enumerate(param_list_pre_revised)
  846. ]
  847. table_dict['test_perf'] = [
  848. '{:.2f}±{:.2f}'.format(average_perf_scores[index_out][index_in],
  849. std_perf_scores[index_out][index_in])
  850. for index_in, _ in enumerate(param_list)
  851. for index_out, _ in enumerate(param_list_pre_revised)
  852. ]
  853. table_dict['train_perf'] = [
  854. '{:.2f}±{:.2f}'.format(average_train_scores[index_out][index_in],
  855. std_train_scores[index_out][index_in])
  856. for index_in, _ in enumerate(param_list)
  857. for index_out, _ in enumerate(param_list_pre_revised)
  858. ]
  859. keyorder = [
  860. 'params', 'train_perf', 'valid_perf', 'test_perf',
  861. 'gram_matrix_time'
  862. ]
  863. if verbose:
  864. print()
  865. tb_print = tabulate(OrderedDict(sorted(table_dict.items(),
  866. key=lambda i: keyorder.index(i[0]))), headers='keys')
  867. # print(tb_print)
  868. return 'table of performance v.s. hyper-params:\n\n%s\n\n' % tb_print

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