generate_data_model_corr_random.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. # main imports
  2. import sys, os, argparse
  3. import numpy as np
  4. import pandas as pd
  5. import subprocess
  6. import random
  7. # image processing imports
  8. from PIL import Image
  9. from ipfml import utils
  10. # modules imports
  11. sys.path.insert(0, '') # trick to enable import of main folder module
  12. import custom_config as cfg
  13. from modules.utils import data as dt
  14. from data_attributes import get_svd_data
  15. # getting configuration information
  16. learned_folder = cfg.learned_zones_folder
  17. min_max_filename = cfg.min_max_filename_extension
  18. # define all scenes variables
  19. all_scenes_list = cfg.scenes_names
  20. all_scenes_indices = cfg.scenes_indices
  21. renderer_choices = cfg.renderer_choices
  22. normalization_choices = cfg.normalization_choices
  23. path = cfg.dataset_path
  24. zones = cfg.zones_indices
  25. seuil_expe_filename = cfg.seuil_expe_filename
  26. features_choices = cfg.features_choices_labels
  27. output_data_folder = cfg.output_data_folder
  28. custom_min_max_folder = cfg.min_max_custom_folder
  29. min_max_ext = cfg.min_max_filename_extension
  30. generic_output_file_svd = '_random.csv'
  31. min_value_interval = sys.maxsize
  32. max_value_interval = 0
  33. def construct_new_line(path_seuil, indices, line, choice, norm):
  34. # increase indices values by one to avoid label
  35. f = lambda x : x + 1
  36. indices = f(indices)
  37. line_data = np.array(line.split(';'))
  38. seuil = line_data[0]
  39. features = line_data[indices]
  40. features = features.astype('float32')
  41. # TODO : check if it's always necessary to do that (loss of information for svd)
  42. if norm:
  43. if choice == 'svdne':
  44. features = utils.normalize_arr_with_range(features, min_value_interval, max_value_interval)
  45. if choice == 'svdn':
  46. features = utils.normalize_arr(features)
  47. with open(path_seuil, "r") as seuil_file:
  48. seuil_learned = int(seuil_file.readline().strip())
  49. if seuil_learned > int(seuil):
  50. line = '1'
  51. else:
  52. line = '0'
  53. for val in features:
  54. line += ';'
  55. line += str(val)
  56. line += '\n'
  57. return line
  58. def get_min_max_value_interval(_scenes_list, _indices, _feature):
  59. global min_value_interval, max_value_interval
  60. # increase indices values by one to avoid label
  61. f = lambda x : x + 1
  62. _indices = f(_indices)
  63. scenes = os.listdir(path)
  64. # remove min max file from scenes folder
  65. scenes = [s for s in scenes if min_max_filename not in s]
  66. for folder_scene in scenes:
  67. # only take care of maxwell scenes
  68. if folder_scene in _scenes_list:
  69. scene_path = os.path.join(path, folder_scene)
  70. zones_folder = []
  71. # create zones list
  72. for index in zones:
  73. index_str = str(index)
  74. if len(index_str) < 2:
  75. index_str = "0" + index_str
  76. zones_folder.append("zone"+index_str)
  77. for zone_folder in zones_folder:
  78. zone_path = os.path.join(scene_path, zone_folder)
  79. # if custom normalization choices then we use svd values not already normalized
  80. data_filename = _feature + "_svd"+ generic_output_file_svd
  81. data_file_path = os.path.join(zone_path, data_filename)
  82. # getting number of line and read randomly lines
  83. f = open(data_file_path)
  84. lines = f.readlines()
  85. # check if user select current scene and zone to be part of training data set
  86. for line in lines:
  87. line_data = np.array(line.split(';'))
  88. features = line_data[[_indices]]
  89. features = [float(m) for m in features]
  90. min_value = min(features)
  91. max_value = max(features)
  92. if min_value < min_value_interval:
  93. min_value_interval = min_value
  94. if max_value > max_value_interval:
  95. max_value_interval = max_value
  96. def generate_data_model(_scenes_list, _filename, _interval, _choice, _feature, _scenes, _nb_zones = 4, _percent = 1, _random=0, _step=1, _custom = False):
  97. output_train_filename = _filename + ".train"
  98. output_test_filename = _filename + ".test"
  99. if not '/' in output_train_filename:
  100. raise Exception("Please select filename with directory path to save data. Example : data/dataset")
  101. # create path if not exists
  102. if not os.path.exists(output_data_folder):
  103. os.makedirs(output_data_folder)
  104. train_file_data = []
  105. test_file_data = []
  106. for folder_scene in _scenes_list:
  107. scene_path = os.path.join(path, folder_scene)
  108. zones_indices = zones
  109. # shuffle list of zones (=> randomly choose zones)
  110. # only in random mode
  111. if _random:
  112. random.shuffle(zones_indices)
  113. # store zones learned
  114. learned_zones_indices = zones_indices[:_nb_zones]
  115. # write into file
  116. folder_learned_path = os.path.join(learned_folder, _filename.split('/')[1])
  117. if not os.path.exists(folder_learned_path):
  118. os.makedirs(folder_learned_path)
  119. file_learned_path = os.path.join(folder_learned_path, folder_scene + '.csv')
  120. with open(file_learned_path, 'w') as f:
  121. for i in learned_zones_indices:
  122. f.write(str(i) + ';')
  123. for id_zone, index_folder in enumerate(zones_indices):
  124. index_str = str(index_folder)
  125. if len(index_str) < 2:
  126. index_str = "0" + index_str
  127. current_zone_folder = "zone" + index_str
  128. zone_path = os.path.join(scene_path, current_zone_folder)
  129. # if custom normalization choices then we use svd values not already normalized
  130. if _custom:
  131. data_filename = _feature + "_svd"+ generic_output_file_svd
  132. else:
  133. data_filename = _feature + "_" + _choice + generic_output_file_svd
  134. data_file_path = os.path.join(zone_path, data_filename)
  135. # getting number of line and read randomly lines
  136. f = open(data_file_path)
  137. lines = f.readlines()
  138. num_lines = len(lines)
  139. # randomly shuffle image
  140. if _random:
  141. random.shuffle(lines)
  142. path_seuil = os.path.join(zone_path, seuil_expe_filename)
  143. counter = 0
  144. # check if user select current scene and zone to be part of training data set
  145. for data in lines:
  146. percent = counter / num_lines
  147. image_index = int(data.split(';')[0])
  148. if image_index % _step == 0:
  149. line = construct_new_line(path_seuil, _interval, data, _choice, _custom)
  150. if id_zone < _nb_zones and folder_scene in _scenes and percent <= _percent:
  151. train_file_data.append(line)
  152. else:
  153. test_file_data.append(line)
  154. counter += 1
  155. f.close()
  156. train_file = open(output_train_filename, 'w')
  157. test_file = open(output_test_filename, 'w')
  158. for line in train_file_data:
  159. train_file.write(line)
  160. for line in test_file_data:
  161. test_file.write(line)
  162. train_file.close()
  163. test_file.close()
  164. def main():
  165. # getting all params
  166. parser = argparse.ArgumentParser(description="Generate data for model using correlation matrix information from data")
  167. parser.add_argument('--output', type=str, help='output file name desired (.train and .test)')
  168. parser.add_argument('--n', type=int, help='Number of features wanted')
  169. parser.add_argument('--highest', type=int, help='Specify if highest or lowest values are wishes', choices=[0, 1])
  170. parser.add_argument('--label', type=int, help='Specify if label correlation is used or not', choices=[0, 1])
  171. parser.add_argument('--kind', type=str, help='Kind of normalization level wished', choices=normalization_choices)
  172. parser.add_argument('--feature', type=str, help='feature data choice', choices=features_choices)
  173. parser.add_argument('--scenes', type=str, help='List of scenes to use for training data')
  174. parser.add_argument('--nb_zones', type=int, help='Number of zones to use for training data set')
  175. parser.add_argument('--random', type=int, help='Data will be randomly filled or not', choices=[0, 1])
  176. parser.add_argument('--percent', type=float, help='Percent of data use for train and test dataset (by default 1)')
  177. parser.add_argument('--step', type=int, help='Photo step to keep for build datasets', default=1)
  178. parser.add_argument('--renderer', type=str, help='Renderer choice in order to limit scenes used', choices=renderer_choices, default='all')
  179. parser.add_argument('--custom', type=str, help='Name of custom min max file if use of renormalization of data', default=False)
  180. args = parser.parse_args()
  181. p_filename = args.output
  182. p_n = args.n
  183. p_highest = args.highest
  184. p_label = args.label
  185. p_kind = args.kind
  186. p_feature = args.feature
  187. p_scenes = args.scenes.split(',')
  188. p_nb_zones = args.nb_zones
  189. p_random = args.random
  190. p_percent = args.percent
  191. p_step = args.step
  192. p_renderer = args.renderer
  193. p_custom = args.custom
  194. # list all possibles choices of renderer
  195. scenes_list = dt.get_renderer_scenes_names(p_renderer)
  196. scenes_indices = dt.get_renderer_scenes_indices(p_renderer)
  197. # getting scenes from indexes user selection
  198. scenes_selected = []
  199. for scene_id in p_scenes:
  200. index = scenes_indices.index(scene_id.strip())
  201. scenes_selected.append(scenes_list[index])
  202. # Get indices to keep from correlation information
  203. # compute temp data file to get correlation information
  204. temp_filename = 'temp'
  205. temp_filename_path = os.path.join(cfg.output_data_folder, temp_filename)
  206. cmd = ['python', 'generate_data_model_random.py',
  207. '--output', temp_filename_path,
  208. '--interval', '0, 200',
  209. '--kind', p_kind,
  210. '--feature', p_feature,
  211. '--scenes', args.scenes,
  212. '--nb_zones', str(16),
  213. '--random', str(int(p_random)),
  214. '--percent', str(p_percent),
  215. '--step', str(p_step),
  216. '--each', str(1),
  217. '--renderer', p_renderer,
  218. '--custom', temp_filename + min_max_ext]
  219. subprocess.Popen(cmd).wait()
  220. temp_data_file_path = temp_filename_path + '.train'
  221. df = pd.read_csv(temp_data_file_path, sep=';', header=None)
  222. indices = []
  223. # compute correlation matrix from whole data scenes of renderer (using or not label column)
  224. if p_label:
  225. # compute pearson correlation between features and label
  226. corr = df.corr()
  227. features_corr = []
  228. for id_row, row in enumerate(corr):
  229. for id_col, val in enumerate(corr[row]):
  230. if id_col == 0 and id_row != 0:
  231. features_corr.append(abs(val))
  232. else:
  233. df = df.drop(df.columns[[0]], axis=1)
  234. # compute pearson correlation between features using only features
  235. corr = df[1:200].corr()
  236. features_corr = []
  237. for id_row, row in enumerate(corr):
  238. correlation_score = 0
  239. for id_col, val in enumerate(corr[row]):
  240. if id_col != id_row:
  241. correlation_score += abs(val)
  242. features_corr.append(correlation_score)
  243. # find `n` min or max indices to keep
  244. if p_highest:
  245. indices = utils.get_indices_of_highest_values(features_corr, p_n)
  246. else:
  247. indices = utils.get_indices_of_lowest_values(features_corr, p_n)
  248. indices = np.sort(indices)
  249. # save indices found
  250. if not os.path.exists(cfg.correlation_indices_folder):
  251. os.makedirs(cfg.correlation_indices_folder)
  252. indices_file_path = os.path.join(cfg.correlation_indices_folder, p_filename.replace(cfg.output_data_folder + '/', '') + '.csv')
  253. with open(indices_file_path, 'w') as f:
  254. for i in indices:
  255. f.write(str(i) + ';')
  256. # find min max value if necessary to renormalize data from `n` indices found
  257. if p_custom:
  258. get_min_max_value_interval(scenes_list, indices, p_feature)
  259. # write new file to save
  260. if not os.path.exists(custom_min_max_folder):
  261. os.makedirs(custom_min_max_folder)
  262. min_max_current_filename = p_filename.replace(cfg.output_data_folder + '/', '').replace('deep_keras_', '') + min_max_filename
  263. min_max_filename_path = os.path.join(custom_min_max_folder, min_max_current_filename)
  264. print(min_max_filename_path)
  265. with open(min_max_filename_path, 'w') as f:
  266. f.write(str(min_value_interval) + '\n')
  267. f.write(str(max_value_interval) + '\n')
  268. # create database using img folder (generate first time only)
  269. generate_data_model(scenes_list, p_filename, indices, p_kind, p_feature, scenes_selected, p_nb_zones, p_percent, p_random, p_step, p_custom)
  270. if __name__== "__main__":
  271. main()