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

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