save_model_result.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. # main imports
  2. import numpy as np
  3. import pandas as pd
  4. import sys, os, argparse
  5. import subprocess
  6. import time
  7. import json
  8. # models imports
  9. from sklearn.utils import shuffle
  10. from sklearn.externals import joblib
  11. from sklearn.metrics import accuracy_score, f1_score, recall_score, roc_auc_score
  12. from sklearn.model_selection import cross_val_score
  13. from sklearn.model_selection import StratifiedKFold
  14. from sklearn.model_selection import train_test_split
  15. # image processing imports
  16. from ipfml import processing
  17. from PIL import Image
  18. # modules imports
  19. sys.path.insert(0, '') # trick to enable import of main folder module
  20. import custom_config as cfg
  21. # variables and parameters
  22. threshold_map_folder = cfg.threshold_map_folder
  23. threshold_map_file_prefix = cfg.threshold_map_folder + "_"
  24. markdowns_folder = cfg.models_information_folder
  25. final_csv_model_comparisons = cfg.csv_model_comparisons_filename
  26. models_name = cfg.models_names_list
  27. zones = cfg.zones_indices
  28. current_dirpath = os.getcwd()
  29. def main():
  30. parser = argparse.ArgumentParser(description="Save data results of learned model")
  31. parser.add_argument('--data', type=str, help='Interval value to keep from svd', default='"0, 200"')
  32. parser.add_argument('--model', type=str, help='.joblib or .json file (sklearn or keras model)')
  33. parser.add_argument('--choice', type=str, help='Name of the model used', choices=cfg.models_names_list)
  34. parser.add_argument('--zones', type=int, help='Number of zones used when learning')
  35. parser.add_argument('--feature', type=str, help='feature data choice', choices=cfg.features_choices_labels)
  36. parser.add_argument('--mode', type=str, help='Kind of normalization level wished', choices=cfg.normalization_choices)
  37. args = parser.parse_args()
  38. p_data_file = args.data
  39. p_model_file = args.model
  40. p_model_name = args.choice
  41. p_zones = args.zones
  42. p_feature = args.feature
  43. p_mode = args.mode
  44. model_scores = []
  45. ########################
  46. # 1. Get and prepare data
  47. ########################
  48. dataset_train = pd.read_csv(p_data_file + '.train', header=None, sep=";")
  49. dataset_test = pd.read_csv(p_data_file + '.test', header=None, sep=";")
  50. # default first shuffle of data
  51. dataset_train = shuffle(dataset_train)
  52. dataset_test = shuffle(dataset_test)
  53. # get dataset with equal number of classes occurences
  54. noisy_df_train = dataset_train[dataset_train.ix[:, 0] == 1]
  55. not_noisy_df_train = dataset_train[dataset_train.ix[:, 0] == 0]
  56. nb_noisy_train = len(noisy_df_train.index)
  57. noisy_df_test = dataset_test[dataset_test.ix[:, 0] == 1]
  58. not_noisy_df_test = dataset_test[dataset_test.ix[:, 0] == 0]
  59. nb_noisy_test = len(noisy_df_test.index)
  60. final_df_train = pd.concat([not_noisy_df_train[0:nb_noisy_train], noisy_df_train])
  61. final_df_test = pd.concat([not_noisy_df_test[0:nb_noisy_test], noisy_df_test])
  62. # shuffle data another time
  63. final_df_train = shuffle(final_df_train)
  64. final_df_test = shuffle(final_df_test)
  65. final_df_train_size = len(final_df_train.index)
  66. final_df_test_size = len(final_df_test.index)
  67. # use of the whole data set for training
  68. x_dataset_train = final_df_train.ix[:,1:]
  69. x_dataset_test = final_df_test.ix[:,1:]
  70. y_dataset_train = final_df_train.ix[:,0]
  71. y_dataset_test = final_df_test.ix[:,0]
  72. #######################
  73. # 2. Getting model
  74. #######################
  75. model = joblib.load(p_model_file)
  76. selected_indices = [(i + 1) for i in np.arange(len(model.support_)) if model.support_[i] == True]
  77. selected_indices_displayed = [i for i in np.arange(len(model.support_)) if model.support_[i] == True]
  78. print(selected_indices)
  79. # update dataset values using specific indices
  80. x_dataset_train = x_dataset_train.loc[:, selected_indices]
  81. x_dataset_test = x_dataset_test.loc[:, selected_indices]
  82. #######################
  83. # 3. Fit model : use of cross validation to fit model
  84. #######################
  85. model.estimator_.fit(x_dataset_train, y_dataset_train)
  86. train_accuracy = cross_val_score(model.estimator_, x_dataset_train, y_dataset_train, cv=5)
  87. ######################
  88. # 4. Test : Validation and test dataset from .test dataset
  89. ######################
  90. # we need to specify validation size to 20% of whole dataset
  91. val_set_size = int(final_df_train_size/3)
  92. test_set_size = val_set_size
  93. total_validation_size = val_set_size + test_set_size
  94. if final_df_test_size > total_validation_size:
  95. x_dataset_test = x_dataset_test[0:total_validation_size]
  96. y_dataset_test = y_dataset_test[0:total_validation_size]
  97. X_test, X_val, y_test, y_val = train_test_split(x_dataset_test, y_dataset_test, test_size=0.5, random_state=1)
  98. # update dataset values using specific indices
  99. y_test_model = model.estimator_.predict(X_test)
  100. y_val_model = model.estimator_.predict(X_val)
  101. y_train_model = model.estimator_.predict(x_dataset_train)
  102. # getting all scores
  103. val_accuracy = accuracy_score(y_val, y_val_model)
  104. test_accuracy = accuracy_score(y_test, y_test_model)
  105. train_f1 = f1_score(y_dataset_train, y_train_model)
  106. train_recall = recall_score(y_dataset_train, y_train_model)
  107. train_roc_auc = roc_auc_score(y_dataset_train, y_train_model)
  108. val_f1 = f1_score(y_val, y_val_model)
  109. val_recall = recall_score(y_val, y_val_model)
  110. val_roc_auc = roc_auc_score(y_val, y_val_model)
  111. test_f1 = f1_score(y_test, y_test_model)
  112. test_recall = recall_score(y_test, y_test_model)
  113. test_roc_auc = roc_auc_score(y_test, y_test_model)
  114. all_x_data = pd.concat([x_dataset_train, X_test, X_val])
  115. all_y_data = pd.concat([y_dataset_train, y_test, y_val])
  116. all_y_model = model.estimator_.predict(all_x_data)
  117. all_accuracy = accuracy_score(all_y_data, all_y_model)
  118. all_f1_score = f1_score(all_y_data, all_y_model)
  119. all_recall_score = recall_score(all_y_data, all_y_model)
  120. all_roc_auc_score = roc_auc_score(all_y_data, all_y_model)
  121. # stats of dataset sizes
  122. total_samples = final_df_train_size + val_set_size + test_set_size
  123. model_scores.append(final_df_train_size)
  124. model_scores.append(val_set_size)
  125. model_scores.append(test_set_size)
  126. model_scores.append(final_df_train_size / total_samples)
  127. model_scores.append(val_set_size / total_samples)
  128. model_scores.append(test_set_size / total_samples)
  129. # add of scores
  130. model_scores.append(train_accuracy)
  131. model_scores.append(val_accuracy)
  132. model_scores.append(test_accuracy)
  133. model_scores.append(all_accuracy)
  134. model_scores.append(train_f1)
  135. model_scores.append(train_recall)
  136. model_scores.append(train_roc_auc)
  137. model_scores.append(val_f1)
  138. model_scores.append(val_recall)
  139. model_scores.append(val_roc_auc)
  140. model_scores.append(test_f1)
  141. model_scores.append(test_recall)
  142. model_scores.append(test_roc_auc)
  143. model_scores.append(all_f1_score)
  144. model_scores.append(all_recall_score)
  145. model_scores.append(all_roc_auc_score)
  146. # add final line into data
  147. final_file_line = p_model_name + ';' + str(selected_indices_displayed) + '; ' + str(p_zones) + '; ' + p_feature + '; ' + p_mode
  148. for s in model_scores:
  149. final_file_line += '; ' + str(s)
  150. # Prepare writing in .csv file into results folder
  151. output_final_file_path = os.path.join(cfg.results_information_folder, final_csv_model_comparisons)
  152. if not os.path.exists(cfg.results_information_folder):
  153. os.makedirs(cfg.results_information_folder)
  154. output_final_file = open(output_final_file_path, "a")
  155. output_final_file.write(final_file_line + '\n')
  156. if __name__== "__main__":
  157. main()