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

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