find_best_attributes_surrogate.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # main imports
  2. import os
  3. import sys
  4. import argparse
  5. import pandas as pd
  6. import numpy as np
  7. import logging
  8. import datetime
  9. import random
  10. # model imports
  11. from sklearn.model_selection import train_test_split
  12. from sklearn.model_selection import GridSearchCV
  13. from sklearn.linear_model import LogisticRegression
  14. from sklearn.ensemble import RandomForestClassifier, VotingClassifier
  15. import joblib
  16. import sklearn.svm as svm
  17. from sklearn.utils import shuffle
  18. from sklearn.metrics import roc_auc_score
  19. from sklearn.model_selection import cross_val_score
  20. # modules and config imports
  21. sys.path.insert(0, '') # trick to enable import of main folder module
  22. import custom_config as cfg
  23. import models as mdl
  24. from optimization.ILSSurrogate import ILSSurrogate
  25. from macop.solutions.BinarySolution import BinarySolution
  26. from macop.operators.mutators.SimpleMutation import SimpleMutation
  27. from macop.operators.mutators.SimpleBinaryMutation import SimpleBinaryMutation
  28. from macop.operators.crossovers.SimpleCrossover import SimpleCrossover
  29. from macop.operators.crossovers.RandomSplitCrossover import RandomSplitCrossover
  30. from macop.operators.policies.UCBPolicy import UCBPolicy
  31. from macop.callbacks.BasicCheckpoint import BasicCheckpoint
  32. from macop.callbacks.UCBCheckpoint import UCBCheckpoint
  33. from sklearn.ensemble import RandomForestClassifier
  34. # variables and parameters
  35. models_list = cfg.models_names_list
  36. # default validator
  37. def validator(solution):
  38. # at least 5 attributes
  39. if list(solution.data).count(1) < 5:
  40. return False
  41. return True
  42. def loadDataset(filename):
  43. ########################
  44. # 1. Get and prepare data
  45. ########################
  46. dataset_train = pd.read_csv(filename + '.train', header=None, sep=";")
  47. dataset_test = pd.read_csv(filename + '.test', header=None, sep=";")
  48. # default first shuffle of data
  49. dataset_train = shuffle(dataset_train)
  50. dataset_test = shuffle(dataset_test)
  51. # get dataset with equal number of classes occurences
  52. noisy_df_train = dataset_train[dataset_train.iloc[:, 0] == 1]
  53. not_noisy_df_train = dataset_train[dataset_train.iloc[:, 0] == 0]
  54. #nb_noisy_train = len(noisy_df_train.index)
  55. noisy_df_test = dataset_test[dataset_test.iloc[:, 0] == 1]
  56. not_noisy_df_test = dataset_test[dataset_test.iloc[:, 0] == 0]
  57. #nb_noisy_test = len(noisy_df_test.index)
  58. # use of all data
  59. final_df_train = pd.concat([not_noisy_df_train, noisy_df_train])
  60. final_df_test = pd.concat([not_noisy_df_test, noisy_df_test])
  61. # shuffle data another time
  62. final_df_train = shuffle(final_df_train)
  63. final_df_test = shuffle(final_df_test)
  64. # use of the whole data set for training
  65. x_dataset_train = final_df_train.iloc[:,1:]
  66. x_dataset_test = final_df_test.iloc[:,1:]
  67. y_dataset_train = final_df_train.iloc[:,0]
  68. y_dataset_test = final_df_test.iloc[:,0]
  69. return x_dataset_train, y_dataset_train, x_dataset_test, y_dataset_test
  70. def main():
  71. parser = argparse.ArgumentParser(description="Train and find best filters to use for model")
  72. parser.add_argument('--data', type=str, help='dataset filename prefix (without .train and .test)', required=True)
  73. parser.add_argument('--choice', type=str, help='model choice from list of choices', choices=models_list, default=models_list[0], required=False)
  74. parser.add_argument('--start_surrogate', type=int, help='number of evalution before starting surrogare model', default=1000)
  75. parser.add_argument('--length', type=int, help='max data length (need to be specify for evaluator)', required=True)
  76. parser.add_argument('--ils', type=int, help='number of total iteration for ils algorithm', required=True)
  77. parser.add_argument('--ls', type=int, help='number of iteration for Local Search algorithm', required=True)
  78. parser.add_argument('--output', type=str, help='output surrogate model name')
  79. args = parser.parse_args()
  80. p_data_file = args.data
  81. p_choice = args.choice
  82. p_length = args.length
  83. p_start = args.start_surrogate
  84. p_ils_iteration = args.ils
  85. p_ls_iteration = args.ls
  86. p_output = args.output
  87. print(p_data_file)
  88. # load data from file
  89. x_train, y_train, x_test, y_test = loadDataset(p_data_file)
  90. # create `logs` folder if necessary
  91. if not os.path.exists(cfg.output_logs_folder):
  92. os.makedirs(cfg.output_logs_folder)
  93. logging.basicConfig(format='%(asctime)s %(message)s', filename='data/logs/{0}.log'.format(p_output), level=logging.DEBUG)
  94. # init solution (`n` attributes)
  95. def init():
  96. return BinarySolution([], p_length
  97. ).random(validator)
  98. # define evaluate function here (need of data information)
  99. def evaluate(solution):
  100. start = datetime.datetime.now()
  101. # get indices of filters data to use (filters selection from solution)
  102. indices = []
  103. for index, value in enumerate(solution.data):
  104. if value == 1:
  105. indices.append(index)
  106. # keep only selected filters from solution
  107. x_train_filters = x_train.iloc[:, indices]
  108. y_train_filters = y_train
  109. x_test_filters = x_test.iloc[:, indices]
  110. # TODO : use of GPU implementation of SVM
  111. # model = mdl.get_trained_model(p_choice, x_train_filters, y_train_filters)
  112. model = RandomForestClassifier(n_estimators=10)
  113. model = model.fit(x_train_filters, y_train_filters)
  114. y_test_model = model.predict(x_test_filters)
  115. test_roc_auc = roc_auc_score(y_test, y_test_model)
  116. end = datetime.datetime.now()
  117. diff = end - start
  118. print("Real evaluation took: {}, score found: {}".format(divmod(diff.days * 86400 + diff.seconds, 60), test_roc_auc))
  119. return test_roc_auc
  120. # build all output folder and files based on `output` name
  121. backup_model_folder = os.path.join(cfg.output_backup_folder, p_output)
  122. surrogate_output_model = os.path.join(cfg.output_surrogates_model_folder, p_output)
  123. surrogate_output_data = os.path.join(cfg.output_surrogates_data_folder, p_output)
  124. if not os.path.exists(backup_model_folder):
  125. os.makedirs(backup_model_folder)
  126. if not os.path.exists(cfg.output_surrogates_model_folder):
  127. os.makedirs(cfg.output_surrogates_model_folder)
  128. if not os.path.exists(cfg.output_surrogates_data_folder):
  129. os.makedirs(cfg.output_surrogates_data_folder)
  130. backup_file_path = os.path.join(backup_model_folder, p_output + '.csv')
  131. ucb_backup_file_path = os.path.join(backup_model_folder, p_output + '_ucbPolicy.csv')
  132. # prepare optimization algorithm (only use of mutation as only ILS are used here, and local search need only local permutation)
  133. operators = [SimpleBinaryMutation(), SimpleMutation()]
  134. policy = UCBPolicy(operators)
  135. # define first line if necessary
  136. if not os.path.exists(surrogate_output_data):
  137. with open(surrogate_output_data) as f:
  138. f.write('x;y\n')
  139. # custom ILS for surrogate use
  140. algo = ILSSurrogate(_initalizer=init,
  141. _evaluator=evaluate, # same evaluator by defadefaultult, as we will use the surrogate function
  142. _operators=operators,
  143. _policy=policy,
  144. _validator=validator,
  145. _surrogate_file_path=surrogate_output_model,
  146. _start_train_surrogate=p_start, # start learning and using surrogate after 1000 real evaluation
  147. _solutions_file=surrogate_output_data,
  148. _ls_train_surrogate=1,
  149. _maximise=True)
  150. algo.addCallback(BasicCheckpoint(_every=1, _filepath=backup_file_path))
  151. algo.addCallback(UCBCheckpoint(_every=1, _filepath=ucb_backup_file_path))
  152. bestSol = algo.run(p_ils_iteration, p_ls_iteration)
  153. # print best solution found
  154. print("Found ", bestSol)
  155. # save model information into .csv file
  156. if not os.path.exists(cfg.results_information_folder):
  157. os.makedirs(cfg.results_information_folder)
  158. filename_path = os.path.join(cfg.results_information_folder, cfg.optimization_attributes_result_filename)
  159. filters_counter = 0
  160. # count number of filters
  161. for index, item in enumerate(bestSol.data):
  162. if index != 0 and index % 2 == 1:
  163. # if two attributes are used
  164. if item == 1 or bestSol.data[index - 1] == 1:
  165. filters_counter += 1
  166. line_info = p_data_file + ';' + str(p_ils_iteration) + ';' + str(p_ls_iteration) + ';' + str(bestSol.data) + ';' + str(list(bestSol.data).count(1)) + ';' + str(filters_counter) + ';' + str(bestSol.fitness())
  167. with open(filename_path, 'a') as f:
  168. f.write(line_info + '\n')
  169. print('Result saved into %s' % filename_path)
  170. if __name__ == "__main__":
  171. main()