multi_run.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # mlflow utilization
  2. import numpy as np
  3. import scipy.sparse as sps
  4. import argparse
  5. import time
  6. from sklearn.model_selection import train_test_split
  7. import copy
  8. import os
  9. import math
  10. import sys
  11. import matplotlib.pyplot as plt
  12. from util.graph_manager import GraphManager
  13. from util.runs_util import *
  14. import mlflow
  15. from util.mlflow_util import *
  16. ACQ_MODELS = ['vopt--mgr', 'sopt--mgr', 'mc--mgr', 'mc--ce', \
  17. 'rand--ce', 'rand--mgr', 'uncertainty--mgr', 'uncertainty--ce']
  18. GRAPH_PARAMS = {
  19. 'knn' :10,
  20. 'sigma' : 3.,
  21. 'normalized' : True,
  22. 'zp_k' : 5
  23. }
  24. if __name__ == "__main__":
  25. parser = argparse.ArgumentParser(description = 'Run Active Learning experiment on Multiclass dataset located at --data_root.')
  26. parser.add_argument('--data-root', default='./data/multi/', dest='data_root', type=str, help='Location of data X with labels in X_labels.npz')
  27. parser.add_argument('--num-eigs', default=50, dest='M', type=int, help='Number of eigenvalues for spectral truncation')
  28. parser.add_argument('--tau-gr', default=0.005, dest='tau_gr', type=float, help='value of diagonal perturbation and scaling of MGR')
  29. parser.add_argument('--gamma-gr', default=0.1, dest='gamma_gr', type=float, help='value of noise parameter of MGR')
  30. parser.add_argument('--tau-ce', default=0.005, dest='tau_ce', type=float, help='value of diagonal perturbation and scaling of CE model')
  31. parser.add_argument('--gamma-ce', default=0.5, dest='gamma_ce', type=float, help='value of noise parameter of CE model')
  32. parser.add_argument('--B', default=5, type=int, help='batch size for AL iterations')
  33. parser.add_argument('--al-iters', default=100, type=int, dest='al_iters',help='number of active learning iterations to perform.')
  34. parser.add_argument('--candidate-method', default='rand', type=str, dest='cand', help='candidate set selection method name ["rand", "full"]')
  35. parser.add_argument('--candidate-percent', default=0.1, type=float, dest='cand_perc', help='if --candidate-method == "rand", then this is the percentage of unlabeled data to consider')
  36. parser.add_argument('--select-method', default='top', type=str, dest='select_method', help='how to select which points to query from the acquisition values. in ["top", "prop"]')
  37. parser.add_argument('--lab-start', default=3, type=int, dest='lab_start', help='size of initially labeled set.')
  38. parser.add_argument('--runs', default=5, type=int, help='Number of trials to run')
  39. parser.add_argument('--metric', default='euclidean', type=str, help='metric name ("euclidean" or "cosine") for graph construction')
  40. parser.add_argument('--name', default='multi', dest='experiment_name', help='Name for this dataset/experiment run ')
  41. args = parser.parse_args()
  42. GRAPH_PARAMS['n_eigs'] = args.M
  43. GRAPH_PARAMS['metric'] = args.metric
  44. if args.metric == 'cosine': # HYPERSPECTRAL DATA
  45. GRAPH_PARAMS['sigma'] = None
  46. GRAPH_PARAMS['zp_k'] = None
  47. GRAPH_PARAMS['knn'] = 15
  48. if not os.path.exists('tmp/'):
  49. os.makedirs('tmp/')
  50. # Load in the Dataset
  51. if not os.path.exists(args.data_root + 'X_labels.npz'):
  52. raise ValueError("Cannot find previously saved data at {}".format(args.data_root + 'X_labels.npz'))
  53. print("Loading data at {}".format(args.data_root + 'X_labels.npz'))
  54. data = np.load(args.data_root + 'X_labels.npz', allow_pickle=True)
  55. X, labels = data['X'], data['labels'].flatten()
  56. N = X.shape[0]
  57. nc = len(np.unique(labels))
  58. if args.lab_start < nc:
  59. args.lab_start = 2*nc
  60. # Load in or calculate eigenvectors, using mlflow IN Graph_manager
  61. gm = GraphManager()
  62. evals, evecs = gm.from_features(X, knn=GRAPH_PARAMS['knn'], sigma=GRAPH_PARAMS['sigma'],
  63. normalized=GRAPH_PARAMS['normalized'], n_eigs=GRAPH_PARAMS['n_eigs'],
  64. zp_k=GRAPH_PARAMS['zp_k'], metric=GRAPH_PARAMS['metric']) # runs mlflow logging in this function call
  65. # Run the experiments
  66. print("--------------- Parameters for the Run of Experiments -----------------------")
  67. print("\tacq_models = %s" % str(ACQ_MODELS))
  68. print("\tal_iters = %d, B = %d, M = %d" % (args.al_iters, args.B, args.M))
  69. print("\tcand=%s, select_method=%s" % (args.cand, args.select_method))
  70. print("\tnum_init_labeled = %d" % (args.lab_start))
  71. print("\ttau = %1.6f, gamma = %1.6f, tau_ce = %1.6f, gamma_ce = %1.6f" % (args.tau_gr, args.gamma_gr, args.tau_ce, args.gamma_ce))
  72. print("\tnumber of runs = {}".format(args.runs))
  73. print("\n\n")
  74. ans = input("Do you want to proceed with this test?? [y/n] ")
  75. while ans not in ['y','n']:
  76. ans = input("Sorry, please input either 'y' or 'n'")
  77. if ans == 'n':
  78. print("Not running test, exiting...")
  79. else:
  80. client = mlflow.tracking.MlflowClient()
  81. mlflow.set_experiment(args.experiment_name)
  82. experiment = client.get_experiment_by_name(args.experiment_name)
  83. for i, seed in enumerate(j**2 + 3 for j in range(args.runs)):
  84. print("=======================================")
  85. print("============= Run {}/{} ===============".format(i+1, args.runs))
  86. print("=======================================")
  87. np.random.seed(seed)
  88. init_labeled, unlabeled = train_test_split(np.arange(N), train_size=args.lab_start, stratify=labels)#list(np.random.choice(range(N), 10, replace=False))
  89. init_labeled, unlabeled = list(init_labeled), list(unlabeled)
  90. params_shared = {
  91. 'init_labeled': init_labeled,
  92. 'run': i,
  93. 'al_iters' : args.al_iters,
  94. 'B' : args.B,
  95. 'cand' : args.cand,
  96. 'select' : args.select_method
  97. }
  98. query = 'attributes.status = "FINISHED"'
  99. for key, val in params_shared.items():
  100. query += ' and params.{} = "{}"'.format(key, val)
  101. already_completed = [run.data.tags['mlflow.runName'] for run in client.search_runs([experiment.experiment_id], filter_string=query)]
  102. if len(already_completed) > 0:
  103. print("Run {} already completed:".format(i+1))
  104. for thing in sorted(already_completed, key= lambda x : x[0]):
  105. print("\t", thing)
  106. print()
  107. np.save('tmp/init_labeled', init_labeled)
  108. for acq, model in (am.split('--') for am in ACQ_MODELS):
  109. if model == 'ce':
  110. run_name = "{}-{}-{:.3f}-{:.3f}-{}-{}".format(acq, model, args.tau_ce, args.gamma_ce, args.M, i)
  111. else:
  112. run_name = "{}-{}-{:.3f}-{:.3f}-{}-{}".format(acq, model, args.tau_gr, args.gamma_gr, args.M, i)
  113. if run_name not in already_completed:
  114. labeled = copy.deepcopy(init_labeled)
  115. with mlflow.start_run(run_name=run_name) as run:
  116. # run AL test
  117. mlflow.log_params(params_shared)
  118. mlflow.log_artifact('tmp/init_labeled.npy')
  119. if model == 'ce':
  120. mlflow.log_params({
  121. 'tau' : args.tau_ce,
  122. 'gamma' : args.gamma_ce,
  123. 'M' : args.M
  124. })
  125. run_multi(evals, evecs, args.tau_ce, args.gamma_ce, labels, labeled, args.al_iters, args.B,
  126. modelname=model, acq=acq, cand=args.cand, select_method=args.select_method, verbose=False)
  127. elif model == 'mgr':
  128. mlflow.log_params({
  129. 'tau' : args.tau_gr,
  130. 'gamma' : args.gamma_gr,
  131. 'M' : args.M
  132. })
  133. run_multi(evals, evecs, args.tau_gr, args.gamma_gr, labels, labeled, args.al_iters, args.B,
  134. modelname=model, acq=acq, cand=args.cand, select_method=args.select_method, verbose=False)
  135. else:
  136. raise ValueError("{} is not a valid multiclass model".format(model))
  137. # Clean up tmp file
  138. print("Cleaning up files in ./tmp/")
  139. if os.path.exists('tmp/init_labeled.npy'):
  140. os.remove('tmp/init_labeled.npy')
  141. if os.path.exists('tmp/iter_stats.npz'):
  142. os.remove('tmp/iter_stats.npz')