save_model_result_in_md_maxwell.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. output_final_file_path = os.path.join(markdowns_folder, final_csv_model_comparisons)
  79. output_final_file = open(output_final_file_path, "a")
  80. print(current_model_name)
  81. # reconstruct data filename
  82. for name in models_name:
  83. if name in current_model_name:
  84. current_data_file_path = os.path.join('data', current_model_name.replace(name, 'data_maxwell'))
  85. data_filenames = [current_data_file_path + '.train', current_data_file_path + '.test', 'all']
  86. accuracy_scores = []
  87. # go ahead each file
  88. for data_file in data_filenames:
  89. if data_file == 'all':
  90. dataset_train = pd.read_csv(data_filenames[0], header=None, sep=";")
  91. dataset_test = pd.read_csv(data_filenames[1], header=None, sep=";")
  92. dataset = pd.concat([dataset_train, dataset_test])
  93. else:
  94. dataset = pd.read_csv(data_file, header=None, sep=";")
  95. y_dataset = dataset.ix[:,0]
  96. x_dataset = dataset.ix[:,1:]
  97. model = joblib.load(p_model_file)
  98. y_pred = model.predict(x_dataset)
  99. # add of score obtained
  100. accuracy_scores.append(accuracy_score(y_dataset, y_pred))
  101. # TODO : improve...
  102. # check if it's always the case...
  103. nb_zones = data_filenames[0].split('_')[7]
  104. final_file_line = current_model_name + '; ' + str(end - begin) + '; ' + str(begin) + '; ' + str(end) + '; ' + str(nb_zones) + '; ' + p_metric + '; ' + p_mode
  105. for s in accuracy_scores:
  106. final_file_line += '; ' + str(s)
  107. output_final_file.write(final_file_line + '\n')
  108. if __name__== "__main__":
  109. main()