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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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 cv2
  19. import numpy as np
  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 src.data_loader import create_dataset, create_cell_nuclei_dataset
  25. from src.unet_medical import UNetMedical
  26. from src.unet_nested import NestedUNet, UNet
  27. from src.config import cfg_unet
  28. from src.utils import UnetEval
  29. device_id = int(os.getenv('DEVICE_ID'))
  30. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False, device_id=device_id)
  31. class TempLoss(nn.Cell):
  32. """A temp loss cell."""
  33. def __init__(self):
  34. super(TempLoss, self).__init__()
  35. self.identity = F.identity()
  36. def construct(self, logits, label):
  37. return self.identity(logits)
  38. class dice_coeff(nn.Metric):
  39. def __init__(self):
  40. super(dice_coeff, self).__init__()
  41. self.clear()
  42. def clear(self):
  43. self._dice_coeff_sum = 0
  44. self._iou_sum = 0
  45. self._samples_num = 0
  46. def update(self, *inputs):
  47. if len(inputs) != 2:
  48. raise ValueError('Need 2 inputs ((y_softmax, y_argmax), y), but got {}'.format(len(inputs)))
  49. y = self._convert_data(inputs[1])
  50. self._samples_num += y.shape[0]
  51. y = y.transpose(0, 2, 3, 1)
  52. b, h, w, c = y.shape
  53. if b != 1:
  54. raise ValueError('Batch size should be 1 when in evaluation.')
  55. y = y.reshape((h, w, c))
  56. if cfg_unet["eval_activate"].lower() == "softmax":
  57. y_softmax = np.squeeze(self._convert_data(inputs[0][0]), axis=0)
  58. if cfg_unet["eval_resize"]:
  59. y_pred = []
  60. for i in range(cfg_unet["num_classes"]):
  61. y_pred.append(cv2.resize(np.uint8(y_softmax[:, :, i] * 255), (w, h)) / 255)
  62. y_pred = np.stack(y_pred, axis=-1)
  63. else:
  64. y_pred = y_softmax
  65. elif cfg_unet["eval_activate"].lower() == "argmax":
  66. y_argmax = np.squeeze(self._convert_data(inputs[0][1]), axis=0)
  67. y_pred = []
  68. for i in range(cfg_unet["num_classes"]):
  69. if cfg_unet["eval_resize"]:
  70. y_pred.append(cv2.resize(np.uint8(y_argmax == i), (w, h), interpolation=cv2.INTER_NEAREST))
  71. else:
  72. y_pred.append(np.float32(y_argmax == i))
  73. y_pred = np.stack(y_pred, axis=-1)
  74. else:
  75. raise ValueError('config eval_activate should be softmax or argmax.')
  76. y_pred = y_pred.astype(np.float32)
  77. inter = np.dot(y_pred.flatten(), y.flatten())
  78. union = np.dot(y_pred.flatten(), y_pred.flatten()) + np.dot(y.flatten(), y.flatten())
  79. single_dice_coeff = 2*float(inter)/float(union+1e-6)
  80. single_iou = single_dice_coeff / (2 - single_dice_coeff)
  81. print("single dice coeff is: {}, IOU is: {}".format(single_dice_coeff, single_iou))
  82. self._dice_coeff_sum += single_dice_coeff
  83. self._iou_sum += single_iou
  84. def eval(self):
  85. if self._samples_num == 0:
  86. raise RuntimeError('Total samples num must not be 0.')
  87. return (self._dice_coeff_sum / float(self._samples_num), self._iou_sum / float(self._samples_num))
  88. def test_net(data_dir,
  89. ckpt_path,
  90. cross_valid_ind=1,
  91. cfg=None):
  92. if cfg['model'] == 'unet_medical':
  93. net = UNetMedical(n_channels=cfg['num_channels'], n_classes=cfg['num_classes'])
  94. elif cfg['model'] == 'unet_nested':
  95. net = NestedUNet(in_channel=cfg['num_channels'], n_class=cfg['num_classes'], use_deconv=cfg['use_deconv'],
  96. use_bn=cfg['use_bn'], use_ds=False)
  97. elif cfg['model'] == 'unet_simple':
  98. net = UNet(in_channel=cfg['num_channels'], n_class=cfg['num_classes'])
  99. else:
  100. raise ValueError("Unsupported model: {}".format(cfg['model']))
  101. param_dict = load_checkpoint(ckpt_path)
  102. load_param_into_net(net, param_dict)
  103. net = UnetEval(net)
  104. if 'dataset' in cfg and cfg['dataset'] == "Cell_nuclei":
  105. valid_dataset = create_cell_nuclei_dataset(data_dir, cfg['img_size'], 1, 1, is_train=False,
  106. eval_resize=cfg["eval_resize"], split=0.8)
  107. else:
  108. _, valid_dataset = create_dataset(data_dir, 1, 1, False, cross_valid_ind, False,
  109. do_crop=cfg['crop'], img_size=cfg['img_size'])
  110. model = Model(net, loss_fn=TempLoss(), metrics={"dice_coeff": dice_coeff()})
  111. print("============== Starting Evaluating ============")
  112. eval_score = model.eval(valid_dataset, dataset_sink_mode=False)["dice_coeff"]
  113. print("============== Cross valid dice coeff is:", eval_score[0])
  114. print("============== Cross valid IOU is:", eval_score[1])
  115. def get_args():
  116. parser = argparse.ArgumentParser(description='Test the UNet on images and target masks',
  117. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  118. parser.add_argument('-d', '--data_url', dest='data_url', type=str, default='data/',
  119. help='data directory')
  120. parser.add_argument('-p', '--ckpt_path', dest='ckpt_path', type=str, default='ckpt_unet_medical_adam-1_600.ckpt',
  121. help='checkpoint path')
  122. return parser.parse_args()
  123. if __name__ == '__main__':
  124. logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
  125. args = get_args()
  126. print("Testing setting:", args)
  127. test_net(data_dir=args.data_url,
  128. ckpt_path=args.ckpt_path,
  129. cross_valid_ind=cfg_unet['cross_valid_ind'],
  130. cfg=cfg_unet)