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

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

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