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 4.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. """DSCNN eval."""
  16. import os
  17. import datetime
  18. import glob
  19. import argparse
  20. import numpy as np
  21. from mindspore import context
  22. from mindspore import Tensor, Model
  23. from mindspore.common import dtype as mstype
  24. from src.config import eval_config
  25. from src.log import get_logger
  26. from src.dataset import audio_dataset
  27. from src.ds_cnn import DSCNN
  28. from src.models import load_ckpt
  29. def get_top5_acc(top5_arg, gt_class):
  30. sub_count = 0
  31. for top5, gt in zip(top5_arg, gt_class):
  32. if gt in top5:
  33. sub_count += 1
  34. return sub_count
  35. def val(args, model, test_de):
  36. '''Eval.'''
  37. eval_dataloader = test_de.create_tuple_iterator()
  38. img_tot = 0
  39. top1_correct = 0
  40. top5_correct = 0
  41. for data, gt_classes in eval_dataloader:
  42. output = model.predict(Tensor(data, mstype.float32))
  43. output = output.asnumpy()
  44. top1_output = np.argmax(output, (-1))
  45. top5_output = np.argsort(output)[:, -5:]
  46. gt_classes = gt_classes.asnumpy()
  47. t1_correct = np.equal(top1_output, gt_classes).sum()
  48. top1_correct += t1_correct
  49. top5_correct += get_top5_acc(top5_output, gt_classes)
  50. img_tot += output.shape[0]
  51. results = [[top1_correct], [top5_correct], [img_tot]]
  52. results = np.array(results)
  53. top1_correct = results[0, 0]
  54. top5_correct = results[1, 0]
  55. img_tot = results[2, 0]
  56. acc1 = 100.0 * top1_correct / img_tot
  57. acc5 = 100.0 * top5_correct / img_tot
  58. if acc1 > args.best_acc:
  59. args.best_acc = acc1
  60. args.best_index = args.index
  61. args.logger.info('Eval: top1_cor:{}, top5_cor:{}, tot:{}, acc@1={:.2f}%, acc@5={:.2f}%' \
  62. .format(top1_correct, top5_correct, img_tot, acc1, acc5))
  63. def main():
  64. parser = argparse.ArgumentParser()
  65. parser.add_argument('--device_id', type=int, default=1, help='which device the model will be trained on')
  66. args, model_settings = eval_config(parser)
  67. context.set_context(mode=context.GRAPH_MODE, device_target="Davinci", device_id=args.device_id)
  68. # Logger
  69. args.outputs_dir = os.path.join(args.log_path, datetime.datetime.now().strftime('%Y-%m-%d_time_%H_%M_%S'))
  70. args.logger = get_logger(args.outputs_dir)
  71. # show args
  72. args.logger.save_args(args)
  73. # find model path
  74. if os.path.isdir(args.model_dir):
  75. models = list(glob.glob(os.path.join(args.model_dir, '*.ckpt')))
  76. print(models)
  77. f = lambda x: -1 * int(os.path.splitext(os.path.split(x)[-1])[0].split('-')[0].split('epoch')[-1])
  78. args.models = sorted(models, key=f)
  79. else:
  80. args.models = [args.model_dir]
  81. args.best_acc = 0
  82. args.index = 0
  83. args.best_index = 0
  84. for model_path in args.models:
  85. test_de = audio_dataset(args.feat_dir, 'testing', model_settings['spectrogram_length'],
  86. model_settings['dct_coefficient_count'], args.per_batch_size)
  87. network = DSCNN(model_settings, args.model_size_info)
  88. load_ckpt(network, model_path, False)
  89. network.set_train(False)
  90. model = Model(network)
  91. args.logger.info('load model {} success'.format(model_path))
  92. val(args, model, test_de)
  93. args.index += 1
  94. args.logger.info('Best model:{} acc:{:.2f}%'.format(args.models[args.best_index], args.best_acc))
  95. if __name__ == "__main__":
  96. main()