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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. '''
  16. ##############evaluate trained models#################
  17. python eval.py
  18. '''
  19. import argparse
  20. import numpy as np
  21. import mindspore.common.dtype as mstype
  22. from mindspore import context
  23. from mindspore import Tensor
  24. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  25. from src.musictagger import MusicTaggerCNN
  26. from src.config import music_cfg as cfg
  27. from src.dataset import create_dataset
  28. def calculate_auc(labels_list, preds_list):
  29. """
  30. The AUC calculation function
  31. Input:
  32. labels_list: list of true label
  33. preds_list: list of predicted label
  34. Outputs
  35. Float, means of AUC
  36. """
  37. auc = []
  38. n_bins = labels_list.shape[0] // 2
  39. if labels_list.ndim == 1:
  40. labels_list = labels_list.reshape(-1, 1)
  41. preds_list = preds_list.reshape(-1, 1)
  42. for i in range(labels_list.shape[1]):
  43. labels = labels_list[:, i]
  44. preds = preds_list[:, i]
  45. postive_len = labels.sum()
  46. negative_len = labels.shape[0] - postive_len
  47. total_case = postive_len * negative_len
  48. positive_histogram = np.zeros((n_bins))
  49. negative_histogram = np.zeros((n_bins))
  50. bin_width = 1.0 / n_bins
  51. for j, _ in enumerate(labels):
  52. nth_bin = int(preds[j] // bin_width)
  53. if labels[j]:
  54. positive_histogram[nth_bin] = positive_histogram[nth_bin] + 1
  55. else:
  56. negative_histogram[nth_bin] = negative_histogram[nth_bin] + 1
  57. accumulated_negative = 0
  58. satisfied_pair = 0
  59. for k in range(n_bins):
  60. satisfied_pair += (
  61. positive_histogram[k] * accumulated_negative +
  62. positive_histogram[k] * negative_histogram[k] * 0.5)
  63. accumulated_negative += negative_histogram[k]
  64. auc.append(satisfied_pair / total_case)
  65. return np.mean(auc)
  66. def val(net, data_dir, filename, num_consumer=4, batch=32):
  67. """
  68. Validation function, estimate the performance of trained model
  69. Input:
  70. net: the trained neural network
  71. data_dir: path to the validation dataset
  72. filename: name of the validation dataset
  73. num_consumer: split number of validation dataset
  74. batch: validation batch size
  75. Outputs
  76. Float, AUC
  77. """
  78. data_train = create_dataset(data_dir, filename, 32, ['feature', 'label'],
  79. num_consumer)
  80. data_train = data_train.create_tuple_iterator()
  81. res_pred = []
  82. res_true = []
  83. for data, label in data_train:
  84. x = net(Tensor(data, dtype=mstype.float32))
  85. res_pred.append(x.asnumpy())
  86. res_true.append(label.asnumpy())
  87. res_pred = np.concatenate(res_pred, axis=0)
  88. res_true = np.concatenate(res_true, axis=0)
  89. auc = calculate_auc(res_true, res_pred)
  90. return auc
  91. def validation(net, model_path, data_dir, filename, num_consumer, batch):
  92. param_dict = load_checkpoint(model_path)
  93. load_param_into_net(net, param_dict)
  94. auc = val(net, data_dir, filename, num_consumer, batch)
  95. return auc
  96. if __name__ == "__main__":
  97. parser = argparse.ArgumentParser(description='Evaluate model')
  98. parser.add_argument('--device_id',
  99. type=int,
  100. help='device ID',
  101. default=None)
  102. args = parser.parse_args()
  103. if args.device_id is not None:
  104. context.set_context(device_target=cfg.device_target,
  105. mode=context.GRAPH_MODE,
  106. device_id=args.device_id)
  107. else:
  108. context.set_context(device_target=cfg.device_target,
  109. mode=context.GRAPH_MODE,
  110. device_id=cfg.device_id)
  111. network = MusicTaggerCNN(in_classes=[1, 128, 384, 768, 2048],
  112. kernel_size=[3, 3, 3, 3, 3],
  113. padding=[0] * 5,
  114. maxpool=[(2, 4), (4, 5), (3, 8), (4, 8)],
  115. has_bias=True)
  116. network.set_train(False)
  117. auc_val = validation(network, cfg.checkpoint_path + "/" + cfg.model_name, cfg.data_dir,
  118. cfg.val_filename, cfg.num_consumer, cfg.batch_size)
  119. print("=" * 10 + "Validation Performance" + "=" * 10)
  120. print("AUC: {:.5f}".format(auc_val))