model_to_txt.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. import os
  2. import keras
  3. import psutil
  4. import configparser
  5. import os
  6. import sys
  7. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  8. import scripts.tools.utils as tools_utils
  9. import argparse
  10. import json
  11. class LossHistory(keras.callbacks.Callback):
  12. def on_train_begin(self, logs=None):
  13. self.losses = []
  14. self.acc = []
  15. self.mem_info_list = []
  16. def on_batch_end(self, batch, logs=None):
  17. process = psutil.Process()
  18. self.losses.append(logs.get('loss'))
  19. self.acc.append(logs.get('acc'))
  20. self.mem_info_list.append(process.memory_info().rss / (1024**3))
  21. def save_log_txt(model, path, name, bk, x_train, y_train):
  22. history_loss = LossHistory()
  23. model.fit(x_train, y_train, epochs=2, batch_size=1024, validation_split=0.2, verbose=1, callbacks=[history_loss])
  24. model_name = name.split("/")[-1].split("_")[0]
  25. method_name = name.split("/")[-1].split("_")[1]
  26. valid_acc = [acc for acc in history_loss.acc if acc is not None]
  27. result_data = {
  28. "model": model_name,
  29. "method": method_name,
  30. "result": {
  31. "Losses": sum(history_loss.losses)/len(history_loss.losses),
  32. "Accuracy": sum(valid_acc)/len(valid_acc),
  33. "MemoryInfoList": sum(history_loss.mem_info_list)/len(history_loss.mem_info_list)
  34. }
  35. }
  36. iterations_data = []
  37. for i in range(len(history_loss.losses)):
  38. iterations_data.append({
  39. "Iterations": i + 1,
  40. "result": {
  41. "Losses": float(history_loss.losses[i]),
  42. "Accuracy": float(history_loss.acc[i]),
  43. "MemoryInfoList": float(history_loss.mem_info_list[i])
  44. }
  45. })
  46. iterations_data_path = path.replace(".json","_train.json")
  47. with open(iterations_data_path, 'w') as json_file:
  48. json.dump(iterations_data, json_file, indent=4)
  49. if os.path.exists(path):
  50. with open(path, 'r') as json_file:
  51. data = json.load(json_file)
  52. else:
  53. data = []
  54. data.append(result_data)
  55. with open(path, 'w') as json_file:
  56. json.dump(data, json_file, indent=4)
  57. def custom_objects():
  58. def no_activation(x):
  59. return x
  60. def leakyrelu(x):
  61. import keras.backend as K
  62. return K.relu(x, alpha=0.01)
  63. objects = {}
  64. objects['no_activation'] = no_activation
  65. objects['leakyrelu'] = leakyrelu
  66. return objects
  67. def model_to_txt1(model_path, bk):
  68. cur_model = keras.models.load_model(model_path, custom_objects=custom_objects())
  69. cur_model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
  70. data = tools_utils.DataUtils
  71. if 'svhn' in model_path or 'fashion2' in model_path:
  72. txt_path = model_path.split("\\")[-1][:-5].split("mut_model")[0]+bk+".json"
  73. else:
  74. txt_path = model_path.split("\\")[-1][:-3].split("mut_model")[0]+bk+".json"
  75. if 'svhn' in model_path or 'fashion2' in model_path:
  76. model_path = model_path.split("\\")[-1][:-5]
  77. else:
  78. model_path = model_path.split("\\")[-1][:-3]
  79. data_path = model_path.split("/")[-1]
  80. x_test, y_test = data.get_data_by_exp(data_path)
  81. save_log_txt(cur_model,txt_path,model_path,bk,x_test, y_test)
  82. if __name__ == "__main__":
  83. """Parser of command args"""
  84. parse = argparse.ArgumentParser()
  85. parse.add_argument("--backend", type=str, help="name of backends")
  86. parse.add_argument("--model_path", type=str, help="redis db port")
  87. parse.add_argument("--root_dir", type=str, help="redis db port")
  88. flags, unparsed = parse.parse_known_args(sys.argv[1:])
  89. """Load Configuration"""
  90. lemon_cfg = configparser.ConfigParser()
  91. # lemon_cfg.read(f"./config/{flags.config_name}")
  92. conf_path = os.path.join(os.path.dirname(os.getcwd()), "config", "demo.conf")
  93. lemon_cfg.read(conf_path)
  94. parameters = lemon_cfg['parameters']
  95. gpu_ids = parameters['gpu_ids']
  96. gpu_list = parameters['gpu_ids'].split(",")
  97. """Init cuda"""
  98. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  99. os.environ["CUDA_VISIBLE_DEVICES"] = gpu_ids
  100. """Switch backend"""
  101. bk_list = ['tensorflow', 'theano', 'cntk', 'mxnet']
  102. bk = flags.backend
  103. print('.........................',type(bk))
  104. os.environ['KERAS_BACKEND'] = bk
  105. os.environ['PYTHONHASHSEED'] = '0'
  106. if bk == 'tensorflow':
  107. os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2' # 只显示 warning 和 Error
  108. import tensorflow as tf
  109. if bk == 'theano':
  110. if len(gpu_list) == 2:
  111. os.environ[
  112. 'THEANO_FLAGS'] = f"device=cuda,contexts=dev{gpu_list[0]}->cuda{gpu_list[0]};dev{gpu_list[1]}->cuda{gpu_list[1]}," \
  113. f"force_device=True,floatX=float32,lib.cnmem=1"
  114. else:
  115. os.environ['THEANO_FLAGS'] = f"device=cuda,contexts=dev{gpu_list[0]}->cuda{gpu_list[0]}," \
  116. f"force_device=True,floatX=float32,lib.cnmem=1"
  117. batch_size = 32
  118. import theano as th
  119. mylogger.info(th.__version__)
  120. if bk == "cntk":
  121. batch_size = 32
  122. from cntk.device import try_set_default_device, gpu
  123. try_set_default_device(gpu(int(gpu_list[0])))
  124. import cntk as ck
  125. if bk == "mxnet":
  126. batch_size = 32
  127. import mxnet as mxnet
  128. from keras import backend as K
  129. import keras
  130. print("Using {} as backend for states extraction| {} is wanted".format(K.backend(),bk))
  131. """Get model hidden output on selected_index data on specific backend"""
  132. model_to_txt1(flags.model_path, bk)