find_best_attributes.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. # model imports
  9. from sklearn.model_selection import train_test_split
  10. from sklearn.model_selection import GridSearchCV
  11. from sklearn.linear_model import LogisticRegression
  12. from sklearn.ensemble import RandomForestClassifier, VotingClassifier
  13. import sklearn.svm as svm
  14. from sklearn.utils import shuffle
  15. from sklearn.externals import joblib
  16. from sklearn.metrics import roc_auc_score
  17. from sklearn.model_selection import cross_val_score
  18. # modules and config imports
  19. sys.path.insert(0, '') # trick to enable import of main folder module
  20. import custom_config as cfg
  21. import models as mdl
  22. from optimization.algorithms.IteratedLocalSearch import IteratedLocalSearch as ILS
  23. from optimization.solutions.BinarySolution import BinarySolution
  24. from optimization.operators.mutators.SimpleMutation import SimpleMutation
  25. from optimization.operators.mutators.SimpleBinaryMutation import SimpleBinaryMutation
  26. from optimization.operators.crossovers.SimpleCrossover import SimpleCrossover
  27. from optimization.operators.policies.RandomPolicy import RandomPolicy
  28. # variables and parameters
  29. models_list = cfg.models_names_list
  30. number_of_values = 26
  31. # default validator
  32. def validator(solution):
  33. if list(solution.data).count(1) < 5:
  34. return False
  35. return True
  36. # init solution (13 filters)
  37. def init():
  38. return BinarySolution([], 13).random(validator)
  39. def loadDataset(filename):
  40. ########################
  41. # 1. Get and prepare data
  42. ########################
  43. dataset_train = pd.read_csv(filename + '.train', header=None, sep=";")
  44. dataset_test = pd.read_csv(filename + '.test', header=None, sep=";")
  45. # default first shuffle of data
  46. dataset_train = shuffle(dataset_train)
  47. dataset_test = shuffle(dataset_test)
  48. # get dataset with equal number of classes occurences
  49. noisy_df_train = dataset_train[dataset_train.iloc[:, 0] == 1]
  50. not_noisy_df_train = dataset_train[dataset_train.iloc[:, 0] == 0]
  51. nb_noisy_train = len(noisy_df_train.index)
  52. noisy_df_test = dataset_test[dataset_test.iloc[:, 0] == 1]
  53. not_noisy_df_test = dataset_test[dataset_test.iloc[:, 0] == 0]
  54. nb_noisy_test = len(noisy_df_test.index)
  55. final_df_train = pd.concat([not_noisy_df_train[0:nb_noisy_train], noisy_df_train])
  56. final_df_test = pd.concat([not_noisy_df_test[0:nb_noisy_test], noisy_df_test])
  57. # shuffle data another time
  58. final_df_train = shuffle(final_df_train)
  59. final_df_test = shuffle(final_df_test)
  60. # use of the whole data set for training
  61. x_dataset_train = final_df_train.iloc[:,1:]
  62. x_dataset_test = final_df_test.iloc[:,1:]
  63. y_dataset_train = final_df_train.iloc[:,0]
  64. y_dataset_test = final_df_test.iloc[:,0]
  65. return x_dataset_train, y_dataset_train, x_dataset_test, y_dataset_test
  66. def main():
  67. parser = argparse.ArgumentParser(description="Train and find best filters to use for model")
  68. parser.add_argument('--data', type=str, help='dataset filename prefix (without .train and .test)')
  69. parser.add_argument('--choice', type=str, help='model choice from list of choices', choices=models_list)
  70. args = parser.parse_args()
  71. p_data_file = args.data
  72. p_choice = args.choice
  73. # load data from file
  74. x_train, y_train, x_test, y_test = loadDataset(p_data_file)
  75. # create `logs` folder if necessary
  76. if not os.path.exists(cfg.logs_folder):
  77. os.makedirs(cfg.logs_folder)
  78. logging.basicConfig(format='%(asctime)s %(message)s', filename='logs/%s.log' % p_data_file.split('/')[-1], level=logging.DEBUG)
  79. # define evaluate function here (need of data information)
  80. def evaluate(solution):
  81. # get indices of filters data to use (filters selection from solution)
  82. indices = []
  83. for index, value in enumerate(solution.data):
  84. if value == 1:
  85. indices.append(index*2)
  86. indices.append(index*2+1)
  87. # keep only selected filters from solution
  88. x_train_filters = x_train.iloc[:, indices]
  89. y_train_filters = y_train
  90. x_test_filters = x_test.iloc[:, indices]
  91. model = mdl.get_trained_model(p_choice, x_train_filters, y_train_filters)
  92. y_test_model = model.predict(x_test_filters)
  93. test_roc_auc = roc_auc_score(y_test, y_test_model)
  94. return test_roc_auc
  95. # prepare optimization algorithm
  96. updators = [SimpleBinaryMutation(), SimpleMutation(), SimpleCrossover()]
  97. policy = RandomPolicy(updators)
  98. algo = ILS(init, evaluate, updators, policy, validator, True)
  99. bestSol = algo.run(100, 10)
  100. # print best solution found
  101. print("Found ", bestSol)
  102. if __name__ == "__main__":
  103. main()