You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

eval.py 7.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Face attribute eval."""
  16. import os
  17. import argparse
  18. import numpy as np
  19. from mindspore import context
  20. from mindspore import Tensor
  21. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  22. from mindspore.common import dtype as mstype
  23. from src.dataset_eval import data_generator_eval
  24. from src.config import config
  25. from src.FaceAttribute.resnet18 import get_resnet18
  26. devid = int(os.getenv('DEVICE_ID'))
  27. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False, device_id=devid)
  28. def softmax(x, axis=0):
  29. return np.exp(x) / np.sum(np.exp(x), axis=axis)
  30. def main(args):
  31. network = get_resnet18(args)
  32. ckpt_path = args.model_path
  33. if os.path.isfile(ckpt_path):
  34. param_dict = load_checkpoint(ckpt_path)
  35. param_dict_new = {}
  36. for key, values in param_dict.items():
  37. if key.startswith('moments.'):
  38. continue
  39. elif key.startswith('network.'):
  40. param_dict_new[key[8:]] = values
  41. else:
  42. param_dict_new[key] = values
  43. load_param_into_net(network, param_dict_new)
  44. print('-----------------------load model success-----------------------')
  45. else:
  46. print('-----------------------load model failed-----------------------')
  47. network.set_train(False)
  48. de_dataloader, steps_per_epoch, _ = data_generator_eval(args)
  49. total_data_num_age = 0
  50. total_data_num_gen = 0
  51. total_data_num_mask = 0
  52. age_num = 0
  53. gen_num = 0
  54. mask_num = 0
  55. gen_tp_num = 0
  56. mask_tp_num = 0
  57. gen_fp_num = 0
  58. mask_fp_num = 0
  59. gen_fn_num = 0
  60. mask_fn_num = 0
  61. for step_i, (data, gt_classes) in enumerate(de_dataloader):
  62. print('evaluating {}/{} ...'.format(step_i + 1, steps_per_epoch))
  63. data_tensor = Tensor(data, dtype=mstype.float32)
  64. fea = network(data_tensor)
  65. gt_age, gt_gen, gt_mask = gt_classes[0]
  66. age_result, gen_result, mask_result = fea
  67. age_result_np = age_result.asnumpy()
  68. gen_result_np = gen_result.asnumpy()
  69. mask_result_np = mask_result.asnumpy()
  70. age_prob = softmax(age_result_np[0].astype(np.float32)).tolist()
  71. gen_prob = softmax(gen_result_np[0].astype(np.float32)).tolist()
  72. mask_prob = softmax(mask_result_np[0].astype(np.float32)).tolist()
  73. age = age_prob.index(max(age_prob))
  74. gen = gen_prob.index(max(gen_prob))
  75. mask = mask_prob.index(max(mask_prob))
  76. if gt_age == age:
  77. age_num += 1
  78. if gt_gen == gen:
  79. gen_num += 1
  80. if gt_mask == mask:
  81. mask_num += 1
  82. if gt_gen == 1 and gen == 1:
  83. gen_tp_num += 1
  84. if gt_gen == 0 and gen == 1:
  85. gen_fp_num += 1
  86. if gt_gen == 1 and gen == 0:
  87. gen_fn_num += 1
  88. if gt_mask == 1 and mask == 1:
  89. mask_tp_num += 1
  90. if gt_mask == 0 and mask == 1:
  91. mask_fp_num += 1
  92. if gt_mask == 1 and mask == 0:
  93. mask_fn_num += 1
  94. if gt_age != -1:
  95. total_data_num_age += 1
  96. if gt_gen != -1:
  97. total_data_num_gen += 1
  98. if gt_mask != -1:
  99. total_data_num_mask += 1
  100. age_accuracy = float(age_num) / float(total_data_num_age)
  101. gen_precision = float(gen_tp_num) / (float(gen_tp_num) + float(gen_fp_num))
  102. gen_recall = float(gen_tp_num) / (float(gen_tp_num) + float(gen_fn_num))
  103. gen_accuracy = float(gen_num) / float(total_data_num_gen)
  104. gen_f1 = 2. * gen_precision * gen_recall / (gen_precision + gen_recall)
  105. mask_precision = float(mask_tp_num) / (float(mask_tp_num) + float(mask_fp_num))
  106. mask_recall = float(mask_tp_num) / (float(mask_tp_num) + float(mask_fn_num))
  107. mask_accuracy = float(mask_num) / float(total_data_num_mask)
  108. mask_f1 = 2. * mask_precision * mask_recall / (mask_precision + mask_recall)
  109. print('model: ', ckpt_path)
  110. print('total age num: ', total_data_num_age)
  111. print('total gen num: ', total_data_num_gen)
  112. print('total mask num: ', total_data_num_mask)
  113. print('age accuracy: ', age_accuracy)
  114. print('gen accuracy: ', gen_accuracy)
  115. print('mask accuracy: ', mask_accuracy)
  116. print('gen precision: ', gen_precision)
  117. print('gen recall: ', gen_recall)
  118. print('gen f1: ', gen_f1)
  119. print('mask precision: ', mask_precision)
  120. print('mask recall: ', mask_recall)
  121. print('mask f1: ', mask_f1)
  122. model_name = os.path.basename(ckpt_path).split('.')[0]
  123. model_dir = os.path.dirname(ckpt_path)
  124. result_txt = os.path.join(model_dir, model_name + '.txt')
  125. if os.path.exists(result_txt):
  126. os.remove(result_txt)
  127. with open(result_txt, 'a') as ft:
  128. ft.write('model: {}\n'.format(ckpt_path))
  129. ft.write('total age num: {}\n'.format(total_data_num_age))
  130. ft.write('total gen num: {}\n'.format(total_data_num_gen))
  131. ft.write('total mask num: {}\n'.format(total_data_num_mask))
  132. ft.write('age accuracy: {}\n'.format(age_accuracy))
  133. ft.write('gen accuracy: {}\n'.format(gen_accuracy))
  134. ft.write('mask accuracy: {}\n'.format(mask_accuracy))
  135. ft.write('gen precision: {}\n'.format(gen_precision))
  136. ft.write('gen recall: {}\n'.format(gen_recall))
  137. ft.write('gen f1: {}\n'.format(gen_f1))
  138. ft.write('mask precision: {}\n'.format(mask_precision))
  139. ft.write('mask recall: {}\n'.format(mask_recall))
  140. ft.write('mask f1: {}\n'.format(mask_f1))
  141. def parse_args():
  142. """parse_args"""
  143. parser = argparse.ArgumentParser(description='face attributes eval')
  144. parser.add_argument('--model_path', type=str, default='', help='pretrained model to load')
  145. parser.add_argument('--mindrecord_path', type=str, default='', help='dataset path, e.g. /home/data.mindrecord')
  146. args_opt = parser.parse_args()
  147. return args_opt
  148. if __name__ == '__main__':
  149. args_1 = parse_args()
  150. args_1.dst_h = config.dst_h
  151. args_1.dst_w = config.dst_w
  152. args_1.attri_num = config.attri_num
  153. args_1.classes = config.classes
  154. args_1.flat_dim = config.flat_dim
  155. args_1.fc_dim = config.fc_dim
  156. args_1.workers = config.workers
  157. main(args_1)