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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. # less 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
  26. from src.unet import UNet
  27. from src.config import cfg_unet
  28. from scipy.special import softmax
  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 CrossEntropyWithLogits(_Loss):
  32. def __init__(self):
  33. super(CrossEntropyWithLogits, self).__init__()
  34. self.transpose_fn = F.Transpose()
  35. self.reshape_fn = F.Reshape()
  36. self.softmax_cross_entropy_loss = nn.SoftmaxCrossEntropyWithLogits()
  37. self.cast = F.Cast()
  38. def construct(self, logits, label):
  39. # NCHW->NHWC
  40. logits = self.transpose_fn(logits, (0, 2, 3, 1))
  41. logits = self.cast(logits, mindspore.float32)
  42. label = self.transpose_fn(label, (0, 2, 3, 1))
  43. loss = self.reduce_mean(self.softmax_cross_entropy_loss(self.reshape_fn(logits, (-1, 2)),
  44. self.reshape_fn(label, (-1, 2))))
  45. return self.get_loss(loss)
  46. class dice_coeff(nn.Metric):
  47. def __init__(self):
  48. super(dice_coeff, self).__init__()
  49. self.clear()
  50. def clear(self):
  51. self._dice_coeff_sum = 0
  52. self._samples_num = 0
  53. def update(self, *inputs):
  54. if len(inputs) != 2:
  55. raise ValueError('Mean dice coeffcient need 2 inputs (y_pred, y), but got {}'.format(len(inputs)))
  56. y_pred = self._convert_data(inputs[0])
  57. y = self._convert_data(inputs[1])
  58. self._samples_num += y.shape[0]
  59. y_pred = y_pred.transpose(0, 2, 3, 1)
  60. y = y.transpose(0, 2, 3, 1)
  61. y_pred = softmax(y_pred, axis=3)
  62. inter = np.dot(y_pred.flatten(), y.flatten())
  63. union = np.dot(y_pred.flatten(), y_pred.flatten()) + np.dot(y.flatten(), y.flatten())
  64. single_dice_coeff = 2*float(inter)/float(union+1e-6)
  65. print("single dice coeff is:", single_dice_coeff)
  66. self._dice_coeff_sum += single_dice_coeff
  67. def eval(self):
  68. if self._samples_num == 0:
  69. raise RuntimeError('Total samples num must not be 0.')
  70. return self._dice_coeff_sum / float(self._samples_num)
  71. def test_net(data_dir,
  72. ckpt_path,
  73. cross_valid_ind=1,
  74. cfg=None):
  75. net = UNet(n_channels=cfg['num_channels'], n_classes=cfg['num_classes'])
  76. param_dict = load_checkpoint(ckpt_path)
  77. load_param_into_net(net, param_dict)
  78. criterion = CrossEntropyWithLogits()
  79. _, valid_dataset = create_dataset(data_dir, 1, 1, False, cross_valid_ind, False)
  80. model = Model(net, loss_fn=criterion, metrics={"dice_coeff": dice_coeff()})
  81. print("============== Starting Evaluating ============")
  82. dice_score = model.eval(valid_dataset, dataset_sink_mode=False)
  83. print("============== Cross valid dice coeff is:", dice_score)
  84. def get_args():
  85. parser = argparse.ArgumentParser(description='Test the UNet on images and target masks',
  86. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  87. parser.add_argument('-d', '--data_url', dest='data_url', type=str, default='data/',
  88. help='data directory')
  89. parser.add_argument('-p', '--ckpt_path', dest='ckpt_path', type=str, default='ckpt_unet_medical_adam-1_600.ckpt',
  90. help='checkpoint path')
  91. return parser.parse_args()
  92. if __name__ == '__main__':
  93. logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
  94. args = get_args()
  95. print("Testing setting:", args)
  96. test_net(data_dir=args.data_url,
  97. ckpt_path=args.ckpt_path,
  98. cross_valid_ind=cfg_unet['cross_valid_ind'],
  99. cfg=cfg_unet)