generate_data_model_random_split.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Fri Sep 14 21:02:42 2018
  5. @author: jbuisine
  6. """
  7. from __future__ import print_function
  8. import sys, os, argparse
  9. import numpy as np
  10. import random
  11. import time
  12. import json
  13. from PIL import Image
  14. from ipfml import processing, metrics, utils
  15. from modules.utils import config as cfg
  16. from modules.utils import data as dt
  17. # getting configuration information
  18. config_filename = cfg.config_filename
  19. learned_folder = cfg.learned_zones_folder
  20. min_max_filename = cfg.min_max_filename_extension
  21. # define all scenes values
  22. all_scenes_list = cfg.scenes_names
  23. all_scenes_indices = cfg.scenes_indices
  24. normalization_choices = cfg.normalization_choices
  25. path = cfg.dataset_path
  26. zones = cfg.zones_indices
  27. seuil_expe_filename = cfg.seuil_expe_filename
  28. renderer_choices = cfg.renderer_choices
  29. metric_choices = cfg.metric_choices_labels
  30. output_data_folder = cfg.output_data_folder
  31. custom_min_max_folder = cfg.min_max_custom_folder
  32. min_max_ext = cfg.min_max_filename_extension
  33. generic_output_file_svd = '_random.csv'
  34. min_value_interval = sys.maxsize
  35. max_value_interval = 0
  36. abs_gap_data = 100
  37. def construct_new_line(seuil_learned, interval, line, choice, each, norm):
  38. begin, end = interval
  39. line_data = line.split(';')
  40. seuil = line_data[0]
  41. metrics = line_data[begin+1:end+1]
  42. # keep only if modulo result is 0 (keep only each wanted values)
  43. metrics = [float(m) for id, m in enumerate(metrics) if id % each == 0]
  44. # TODO : check if it's always necessary to do that (loss of information for svd)
  45. if norm:
  46. if choice == 'svdne':
  47. metrics = utils.normalize_arr_with_range(metrics, min_value_interval, max_value_interval)
  48. if choice == 'svdn':
  49. metrics = utils.normalize_arr(metrics)
  50. if seuil_learned > int(seuil):
  51. line = '1'
  52. else:
  53. line = '0'
  54. for idx, val in enumerate(metrics):
  55. line += ';'
  56. line += str(val)
  57. line += '\n'
  58. return line
  59. def get_min_max_value_interval(_scenes_list, _interval, _metric):
  60. global min_value_interval, max_value_interval
  61. scenes = os.listdir(path)
  62. # remove min max file from scenes folder
  63. scenes = [s for s in scenes if min_max_filename not in s]
  64. for id_scene, folder_scene in enumerate(scenes):
  65. # only take care of maxwell scenes
  66. if folder_scene in _scenes_list:
  67. scene_path = os.path.join(path, folder_scene)
  68. zones_folder = []
  69. # create zones list
  70. for index in zones:
  71. index_str = str(index)
  72. if len(index_str) < 2:
  73. index_str = "0" + index_str
  74. zones_folder.append("zone"+index_str)
  75. for id_zone, zone_folder in enumerate(zones_folder):
  76. zone_path = os.path.join(scene_path, zone_folder)
  77. # if custom normalization choices then we use svd values not already normalized
  78. data_filename = _metric + "_svd"+ generic_output_file_svd
  79. data_file_path = os.path.join(zone_path, data_filename)
  80. # getting number of line and read randomly lines
  81. f = open(data_file_path)
  82. lines = f.readlines()
  83. # check if user select current scene and zone to be part of training data set
  84. for line in lines:
  85. begin, end = _interval
  86. line_data = line.split(';')
  87. metrics = line_data[begin+1:end+1]
  88. metrics = [float(m) for m in metrics]
  89. min_value = min(metrics)
  90. max_value = max(metrics)
  91. if min_value < min_value_interval:
  92. min_value_interval = min_value
  93. if max_value > max_value_interval:
  94. max_value_interval = max_value
  95. def generate_data_model(_scenes_list, _filename, _interval, _choice, _metric, _scenes, _nb_zones = 4, _percent = 1, _random=0, _step=1, _each=1, _custom = False):
  96. output_train_filename = _filename + ".train"
  97. output_test_filename = _filename + ".test"
  98. if not '/' in output_train_filename:
  99. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  100. # create path if not exists
  101. if not os.path.exists(output_data_folder):
  102. os.makedirs(output_data_folder)
  103. train_file_data = []
  104. test_file_data = []
  105. for id_scene, folder_scene in enumerate(_scenes_list):
  106. scene_path = os.path.join(path, folder_scene)
  107. zones_indices = zones
  108. # shuffle list of zones (=> randomly choose zones)
  109. # only in random mode
  110. if _random:
  111. random.shuffle(zones_indices)
  112. # store zones learned
  113. learned_zones_indices = zones_indices[:_nb_zones]
  114. # write into file
  115. folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
  116. if not os.path.exists(folder_learned_path):
  117. os.makedirs(folder_learned_path)
  118. file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
  119. with open(file_learned_path, 'w') as f:
  120. for i in learned_zones_indices:
  121. f.write(str(i) + ';')
  122. for id_zone, index_folder in enumerate(zones_indices):
  123. index_str = str(index_folder)
  124. if len(index_str) < 2:
  125. index_str = "0" + index_str
  126. current_zone_folder = "zone" + index_str
  127. zone_path = os.path.join(scene_path, current_zone_folder)
  128. # if custom normalization choices then we use svd values not already normalized
  129. if _custom:
  130. data_filename = _metric + "_svd"+ generic_output_file_svd
  131. else:
  132. data_filename = _metric + "_" + _choice + generic_output_file_svd
  133. data_file_path = os.path.join(zone_path, data_filename)
  134. # getting number of line and read randomly lines
  135. f = open(data_file_path)
  136. lines = f.readlines()
  137. num_lines = len(lines)
  138. # randomly shuffle image
  139. if _random:
  140. random.shuffle(lines)
  141. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  142. with open(path_seuil, "r") as seuil_file:
  143. seuil_learned = int(seuil_file.readline().strip())
  144. counter = 0
  145. # check if user select current scene and zone to be part of training data set
  146. for data in lines:
  147. percent = counter / num_lines
  148. image_index = int(data.split(';')[0])
  149. if image_index % _step == 0:
  150. with open(path_seuil, "r") as seuil_file:
  151. seuil_learned = int(seuil_file.readline().strip())
  152. gap_threshold = abs(seuil_learned - image_index)
  153. if gap_threshold > abs_gap_data:
  154. line = construct_new_line(seuil_learned, _interval, data, _choice, _each, _custom)
  155. if id_zone < _nb_zones and folder_scene in _scenes and percent <= _percent:
  156. train_file_data.append(line)
  157. else:
  158. test_file_data.append(line)
  159. counter += 1
  160. f.close()
  161. train_file = open(output_train_filename, 'w')
  162. test_file = open(output_test_filename, 'w')
  163. for line in train_file_data:
  164. train_file.write(line)
  165. for line in test_file_data:
  166. test_file.write(line)
  167. train_file.close()
  168. test_file.close()
  169. def main():
  170. # getting all params
  171. parser = argparse.ArgumentParser(description="Generate data for model using correlation matrix information from data")
  172. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  173. parser.add_argument('--interval', type=str, help='Interval value to keep from svd', default='"0, 200"')
  174. parser.add_argument('--kind', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  175. parser.add_argument('--metric', type=str, help='Metric data choice', choices=metric_choices)
  176. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  177. parser.add_argument('--nb_zones', type=int, help='Number of zones to use for training data set')
  178. parser.add_argument('--random', type=int, help='Data will be randomly filled or not', choices=[0, 1])
  179. parser.add_argument('--percent', type=float, help='Percent of data use for train and test dataset (by default 1)')
  180. parser.add_argument('--step', type=int, help='Photo step to keep for build datasets', default=1)
  181. parser.add_argument('--each', type=int, help='Each features to keep from interval', default=1)
  182. parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=renderer_choices, default='all')
  183. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  184. args = parser.parse_args()
  185. p_filename = args.output
  186. p_interval = list(map(int, args.interval.split(',')))
  187. p_kind = args.kind
  188. p_metric = args.metric
  189. p_scenes = args.scenes.split(',')
  190. p_nb_zones = args.nb_zones
  191. p_random = args.random
  192. p_percent = args.percent
  193. p_step = args.step
  194. p_each = args.each
  195. p_renderer = args.renderer
  196. p_custom = args.custom
  197. # list all possibles choices of renderer
  198. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  199. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  200. # getting scenes from indexes user selection
  201. scenes_selected = []
  202. for scene_id in p_scenes:
  203. index = scenes_indices.index(scene_id.strip())
  204. scenes_selected.append(scenes_list[index])
  205. # find min max value if necessary to renormalize data
  206. if p_custom:
  207. get_min_max_value_interval(scenes_list, p_interval, p_metric)
  208. # write new file to save
  209. if not os.path.exists(custom_min_max_folder):
  210. os.makedirs(custom_min_max_folder)
  211. min_max_folder_path = os.path.join(os.path.dirname(__file__), custom_min_max_folder)
  212. min_max_filename_path = os.path.join(min_max_folder_path, p_custom)
  213. with open(min_max_filename_path, 'w') as f:
  214. f.write(str(min_value_interval) + '\n')
  215. f.write(str(max_value_interval) + '\n')
  216. # create database using img folder (generate first time only)
  217. generate_data_model(scenes_list, p_filename, p_interval, p_kind, p_metric, scenes_selected, p_nb_zones, p_percent, p_random, p_step, p_each, p_custom)
  218. if __name__== "__main__":
  219. main()