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

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