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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. from mindspore import context, Model
  19. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  20. from src.data_loader import create_dataset, create_cell_nuclei_dataset
  21. from src.unet_medical import UNetMedical
  22. from src.unet_nested import NestedUNet, UNet
  23. from src.config import cfg_unet
  24. from src.utils import UnetEval, TempLoss, dice_coeff
  25. device_id = int(os.getenv('DEVICE_ID'))
  26. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", save_graphs=False, device_id=device_id)
  27. def test_net(data_dir,
  28. ckpt_path,
  29. cross_valid_ind=1,
  30. cfg=None):
  31. if cfg['model'] == 'unet_medical':
  32. net = UNetMedical(n_channels=cfg['num_channels'], n_classes=cfg['num_classes'])
  33. elif cfg['model'] == 'unet_nested':
  34. net = NestedUNet(in_channel=cfg['num_channels'], n_class=cfg['num_classes'], use_deconv=cfg['use_deconv'],
  35. use_bn=cfg['use_bn'], use_ds=False)
  36. elif cfg['model'] == 'unet_simple':
  37. net = UNet(in_channel=cfg['num_channels'], n_class=cfg['num_classes'])
  38. else:
  39. raise ValueError("Unsupported model: {}".format(cfg['model']))
  40. param_dict = load_checkpoint(ckpt_path)
  41. load_param_into_net(net, param_dict)
  42. net = UnetEval(net)
  43. if 'dataset' in cfg and cfg['dataset'] == "Cell_nuclei":
  44. valid_dataset = create_cell_nuclei_dataset(data_dir, cfg['img_size'], 1, 1, is_train=False,
  45. eval_resize=cfg["eval_resize"], split=0.8)
  46. else:
  47. _, valid_dataset = create_dataset(data_dir, 1, 1, False, cross_valid_ind, False,
  48. do_crop=cfg['crop'], img_size=cfg['img_size'])
  49. model = Model(net, loss_fn=TempLoss(), metrics={"dice_coeff": dice_coeff(cfg_unet)})
  50. print("============== Starting Evaluating ============")
  51. eval_score = model.eval(valid_dataset, dataset_sink_mode=False)["dice_coeff"]
  52. print("============== Cross valid dice coeff is:", eval_score[0])
  53. print("============== Cross valid IOU is:", eval_score[1])
  54. def get_args():
  55. parser = argparse.ArgumentParser(description='Test the UNet on images and target masks',
  56. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  57. parser.add_argument('-d', '--data_url', dest='data_url', type=str, default='data/',
  58. help='data directory')
  59. parser.add_argument('-p', '--ckpt_path', dest='ckpt_path', type=str, default='ckpt_unet_medical_adam-1_600.ckpt',
  60. help='checkpoint path')
  61. return parser.parse_args()
  62. if __name__ == '__main__':
  63. logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
  64. args = get_args()
  65. print("Testing setting:", args)
  66. test_net(data_dir=args.data_url,
  67. ckpt_path=args.ckpt_path,
  68. cross_valid_ind=cfg_unet['cross_valid_ind'],
  69. cfg=cfg_unet)