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

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