save_model_result_in_md_maxwell.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. from sklearn.externals import joblib
  2. from sklearn.metrics import accuracy_score
  3. import numpy as np
  4. import pandas as pd
  5. from ipfml import image_processing
  6. from PIL import Image
  7. import sys, os, getopt
  8. import subprocess
  9. import time
  10. current_dirpath = os.getcwd()
  11. threshold_map_folder = "threshold_map"
  12. threshold_map_file_prefix = "treshold_map_"
  13. markdowns_folder = "models_info"
  14. final_csv_model_comparisons = "models_comparisons.csv"
  15. models_name = ["svm_model","ensemble_model","ensemble_model_v2"]
  16. zones = np.arange(16)
  17. def main():
  18. if len(sys.argv) <= 1:
  19. print('Run with default parameters...')
  20. print('python save_model_result_in_md.py --interval "0,20" --model path/to/xxxx.joblib --mode ["svd", "svdn", "svdne"] --metric ["lab", "mscn"]')
  21. sys.exit(2)
  22. try:
  23. opts, args = getopt.getopt(sys.argv[1:], "ht:m:o:l", ["help=", "interval=", "model=", "mode=", "metric="])
  24. except getopt.GetoptError:
  25. # print help information and exit:
  26. print('python save_model_result_in_md.py --interval "xx,xx" --model path/to/xxxx.joblib --mode ["svd", "svdn", "svdne"] --metric ["lab", "mscn"]')
  27. sys.exit(2)
  28. for o, a in opts:
  29. if o == "-h":
  30. print('python save_model_result_in_md.py --interval "xx,xx" --model path/to/xxxx.joblib --mode ["svd", "svdn", "svdne"] --metric ["lab", "mscn"]')
  31. sys.exit()
  32. elif o in ("-t", "--interval"):
  33. p_interval = list(map(int, a.split(',')))
  34. elif o in ("-m", "--model"):
  35. p_model_file = a
  36. elif o in ("-o", "--mode"):
  37. p_mode = a
  38. if p_mode != 'svdn' and p_mode != 'svdne' and p_mode != 'svd':
  39. assert False, "Mode not recognized"
  40. elif o in ("-c", "--metric"):
  41. p_metric = a
  42. else:
  43. assert False, "unhandled option"
  44. # call model and get global result in scenes
  45. begin, end = p_interval
  46. bash_cmd = "bash testModelByScene_maxwell.sh '" + str(begin) + "' '" + str(end) + "' '" + p_model_file + "' '" + p_mode + "' '" + p_metric + "'"
  47. print(bash_cmd)
  48. ## call command ##
  49. p = subprocess.Popen(bash_cmd, stdout=subprocess.PIPE, shell=True)
  50. (output, err) = p.communicate()
  51. ## Wait for result ##
  52. p_status = p.wait()
  53. if not os.path.exists(markdowns_folder):
  54. os.makedirs(markdowns_folder)
  55. # get model name to construct model
  56. md_model_path = os.path.join(markdowns_folder, p_model_file.split('/')[-1].replace('.joblib', '.md'))
  57. with open(md_model_path, 'w') as f:
  58. f.write(output.decode("utf-8"))
  59. # read each threshold_map information if exists
  60. model_map_info_path = os.path.join(threshold_map_folder, p_model_file.replace('saved_models/', ''))
  61. if not os.path.exists(model_map_info_path):
  62. f.write('\n\n No threshold map information')
  63. else:
  64. maps_files = os.listdir(model_map_info_path)
  65. # get all map information
  66. for t_map_file in maps_files:
  67. file_path = os.path.join(model_map_info_path, t_map_file)
  68. with open(file_path, 'r') as map_file:
  69. title_scene = t_map_file.replace(threshold_map_file_prefix, '')
  70. f.write('\n\n## ' + title_scene + '\n')
  71. content = map_file.readlines()
  72. # getting each map line information
  73. for line in content:
  74. f.write(line)
  75. f.close()
  76. # Keep model information to compare
  77. current_model_name = p_model_file.split('/')[-1].replace('.joblib', '')
  78. # Prepare writing in .csv file
  79. output_final_file_path = os.path.join(markdowns_folder, final_csv_model_comparisons)
  80. output_final_file = open(output_final_file_path, "a")
  81. print(current_model_name)
  82. # reconstruct data filename
  83. for name in models_name:
  84. if name in current_model_name:
  85. current_data_file_path = os.path.join('data', current_model_name.replace(name, 'data_maxwell'))
  86. model_scores = []
  87. ########################
  88. # 1. Get and prepare data
  89. ########################
  90. dataset_train = pd.read_csv(current_data_file_path + '.train', header=None, sep=";")
  91. dataset_test = pd.read_csv(current_data_file_path + '.test', header=None, sep=";")
  92. # default first shuffle of data
  93. dataset_train = shuffle(dataset_train)
  94. dataset_test = shuffle(dataset_test)
  95. # get dataset with equal number of classes occurences
  96. noisy_df_train = dataset_train[dataset_train.ix[:, 0] == 1]
  97. not_noisy_df_train = dataset_train[dataset_train.ix[:, 0] == 0]
  98. nb_noisy_train = len(noisy_df_train.index)
  99. noisy_df_test = dataset_test[dataset_test.ix[:, 0] == 1]
  100. not_noisy_df_test = dataset_test[dataset_test.ix[:, 0] == 0]
  101. nb_noisy_test = len(noisy_df_test.index)
  102. final_df_train = pd.concat([not_noisy_df_train[0:nb_noisy_train], noisy_df_train])
  103. final_df_test = pd.concat([not_noisy_df_test[0:nb_noisy_test], noisy_df_test])
  104. # shuffle data another time
  105. final_df_train = shuffle(final_df_train)
  106. final_df_test = shuffle(final_df_test)
  107. final_df_train_size = len(final_df_train.index)
  108. final_df_test_size = len(final_df_test.index)
  109. # use of the whole data set for training
  110. x_dataset_train = final_df_train.ix[:,1:]
  111. x_dataset_test = final_df_test.ix[:,1:]
  112. y_dataset_train = final_df_train.ix[:,0]
  113. y_dataset_test = final_df_test.ix[:,0]
  114. #######################
  115. # 2. Getting model
  116. #######################
  117. model = joblib.load(p_model_file)
  118. #######################
  119. # 3. Fit model : use of cross validation to fit model
  120. #######################
  121. model.fit(x_dataset_train, y_dataset_train)
  122. val_scores = cross_val_score(model, x_dataset_train, y_dataset_train, cv=5)
  123. ######################
  124. # 4. Test : Validation and test dataset from .test dataset
  125. ######################
  126. # we need to specify validation size to 20% of whole dataset
  127. val_set_size = int(final_df_train_size/3)
  128. test_set_size = val_set_size
  129. total_validation_size = val_set_size + test_set_size
  130. if final_df_test_size > total_validation_size:
  131. x_dataset_test = x_dataset_test[0:total_validation_size]
  132. y_dataset_test = y_dataset_test[0:total_validation_size]
  133. X_test, X_val, y_test, y_val = train_test_split(x_dataset_test, y_dataset_test, test_size=0.5, random_state=1)
  134. y_test_model = ensemble_model.predict(X_test)
  135. y_val_model = ensemble_model.predict(X_val)
  136. val_accuracy = accuracy_score(y_val, y_val_model)
  137. test_accuracy = accuracy_score(y_test, y_test_model)
  138. y_train_model = model.predict(x_dataset_train)
  139. train_f1 = f1_score(y_dataset_train, y_train_model)
  140. val_f1 = f1_score(y_val, y_val_model)
  141. test_f1 = f1_score(y_test, y_test_model)
  142. # add of scores
  143. model_scores.append(val_scores.mean())
  144. model_scores.append(val_accuracy)
  145. model_scores.append(test_accuracy)
  146. model_scores.append(train_f1)
  147. model_scores.append(val_f1)
  148. model_scores.append(test_f1)
  149. # TODO : improve...
  150. # check if it's always the case...
  151. nb_zones = data_filenames[0].split('_')[7]
  152. final_file_line = current_model_name + '; ' + str(end - begin) + '; ' + str(begin) + '; ' + str(end) + '; ' + str(nb_zones) + '; ' + p_metric + '; ' + p_mode
  153. for s in model_scores:
  154. final_file_line += '; ' + str(s)
  155. output_final_file.write(final_file_line + '\n')
  156. if __name__== "__main__":
  157. main()