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.8 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  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. import os
  16. import argparse
  17. import logging
  18. import numpy as np
  19. import mindspore
  20. import mindspore.nn as nn
  21. import mindspore.ops.operations as F
  22. from mindspore import context, Model
  23. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  24. from mindspore.nn.loss.loss import _Loss
  25. from src.data_loader import create_dataset, create_cell_nuclei_dataset
  26. from src.unet_medical import UNetMedical
  27. from src.unet_nested import NestedUNet, UNet
  28. from src.config import cfg_unet
  29. from scipy.special import softmax
  30. device_id = int(os.getenv('DEVICE_ID'))
  31. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False, device_id=device_id)
  32. class CrossEntropyWithLogits(_Loss):
  33. def __init__(self):
  34. super(CrossEntropyWithLogits, self).__init__()
  35. self.transpose_fn = F.Transpose()
  36. self.reshape_fn = F.Reshape()
  37. self.softmax_cross_entropy_loss = nn.SoftmaxCrossEntropyWithLogits()
  38. self.cast = F.Cast()
  39. def construct(self, logits, label):
  40. # NCHW->NHWC
  41. logits = self.transpose_fn(logits, (0, 2, 3, 1))
  42. logits = self.cast(logits, mindspore.float32)
  43. label = self.transpose_fn(label, (0, 2, 3, 1))
  44. loss = self.reduce_mean(self.softmax_cross_entropy_loss(self.reshape_fn(logits, (-1, 2)),
  45. self.reshape_fn(label, (-1, 2))))
  46. return self.get_loss(loss)
  47. class dice_coeff(nn.Metric):
  48. def __init__(self):
  49. super(dice_coeff, self).__init__()
  50. self.clear()
  51. def clear(self):
  52. self._dice_coeff_sum = 0
  53. self._iou_sum = 0
  54. self._samples_num = 0
  55. def update(self, *inputs):
  56. if len(inputs) != 2:
  57. raise ValueError('Mean dice coefficient need 2 inputs (y_pred, y), but got {}'.format(len(inputs)))
  58. y_pred = self._convert_data(inputs[0])
  59. y = self._convert_data(inputs[1])
  60. self._samples_num += y.shape[0]
  61. y_pred = y_pred.transpose(0, 2, 3, 1)
  62. y = y.transpose(0, 2, 3, 1)
  63. y_pred = softmax(y_pred, axis=3)
  64. inter = np.dot(y_pred.flatten(), y.flatten())
  65. union = np.dot(y_pred.flatten(), y_pred.flatten()) + np.dot(y.flatten(), y.flatten())
  66. single_dice_coeff = 2*float(inter)/float(union+1e-6)
  67. single_iou = single_dice_coeff / (2 - single_dice_coeff)
  68. print("single dice coeff is: {}, IOU is: {}".format(single_dice_coeff, single_iou))
  69. self._dice_coeff_sum += single_dice_coeff
  70. self._iou_sum += single_iou
  71. def eval(self):
  72. if self._samples_num == 0:
  73. raise RuntimeError('Total samples num must not be 0.')
  74. return (self._dice_coeff_sum / float(self._samples_num), self._iou_sum / float(self._samples_num))
  75. def test_net(data_dir,
  76. ckpt_path,
  77. cross_valid_ind=1,
  78. cfg=None):
  79. if cfg['model'] == 'unet_medical':
  80. net = UNetMedical(n_channels=cfg['num_channels'], n_classes=cfg['num_classes'])
  81. elif cfg['model'] == 'unet_nested':
  82. net = NestedUNet(in_channel=cfg['num_channels'], n_class=cfg['num_classes'], use_deconv=cfg['use_deconv'],
  83. use_bn=cfg['use_bn'], use_ds=False)
  84. elif cfg['model'] == 'unet_simple':
  85. net = UNet(in_channel=cfg['num_channels'], n_class=cfg['num_classes'])
  86. else:
  87. raise ValueError("Unsupported model: {}".format(cfg['model']))
  88. param_dict = load_checkpoint(ckpt_path)
  89. load_param_into_net(net, param_dict)
  90. criterion = CrossEntropyWithLogits()
  91. if 'dataset' in cfg and cfg['dataset'] == "Cell_nuclei":
  92. valid_dataset = create_cell_nuclei_dataset(data_dir, cfg['img_size'], 1, 1, is_train=False, split=0.8)
  93. else:
  94. _, valid_dataset = create_dataset(data_dir, 1, 1, False, cross_valid_ind, False,
  95. do_crop=cfg['crop'], img_size=cfg['img_size'])
  96. model = Model(net, loss_fn=criterion, metrics={"dice_coeff": dice_coeff()})
  97. print("============== Starting Evaluating ============")
  98. eval_score = model.eval(valid_dataset, dataset_sink_mode=False)["dice_coeff"]
  99. print("============== Cross valid dice coeff is:", eval_score[0])
  100. print("============== Cross valid IOU is:", eval_score[1])
  101. def get_args():
  102. parser = argparse.ArgumentParser(description='Test the UNet on images and target masks',
  103. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  104. parser.add_argument('-d', '--data_url', dest='data_url', type=str, default='data/',
  105. help='data directory')
  106. parser.add_argument('-p', '--ckpt_path', dest='ckpt_path', type=str, default='ckpt_unet_medical_adam-1_600.ckpt',
  107. help='checkpoint path')
  108. return parser.parse_args()
  109. if __name__ == '__main__':
  110. logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
  111. args = get_args()
  112. print("Testing setting:", args)
  113. test_net(data_dir=args.data_url,
  114. ckpt_path=args.ckpt_path,
  115. cross_valid_ind=cfg_unet['cross_valid_ind'],
  116. cfg=cfg_unet)