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.

test_uncertainty.py 5.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. """ test uncertainty toolbox """
  16. import mindspore.dataset as ds
  17. import mindspore.dataset.transforms.c_transforms as C
  18. import mindspore.dataset.vision.c_transforms as CV
  19. import mindspore.nn as nn
  20. from mindspore import context, Tensor
  21. from mindspore.common import dtype as mstype
  22. from mindspore.common.initializer import TruncatedNormal
  23. from mindspore.dataset.vision import Inter
  24. from mindspore.nn.probability.toolbox.uncertainty_evaluation import UncertaintyEvaluation
  25. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  26. context.set_context(mode=context.GRAPH_MODE, device_target="GPU")
  27. def conv(in_channels, out_channels, kernel_size, stride=1, padding=0):
  28. """weight initial for conv layer"""
  29. weight = weight_variable()
  30. return nn.Conv2d(in_channels, out_channels,
  31. kernel_size=kernel_size, stride=stride, padding=padding,
  32. weight_init=weight, has_bias=False, pad_mode="valid")
  33. def fc_with_initialize(input_channels, out_channels):
  34. """weight initial for fc layer"""
  35. weight = weight_variable()
  36. bias = weight_variable()
  37. return nn.Dense(input_channels, out_channels, weight, bias)
  38. def weight_variable():
  39. """weight initial"""
  40. return TruncatedNormal(0.02)
  41. class LeNet5(nn.Cell):
  42. def __init__(self, num_class=10, channel=1):
  43. super(LeNet5, self).__init__()
  44. self.num_class = num_class
  45. self.conv1 = conv(channel, 6, 5)
  46. self.conv2 = conv(6, 16, 5)
  47. self.fc1 = fc_with_initialize(16 * 5 * 5, 120)
  48. self.fc2 = fc_with_initialize(120, 84)
  49. self.fc3 = fc_with_initialize(84, self.num_class)
  50. self.relu = nn.ReLU()
  51. self.max_pool2d = nn.MaxPool2d(kernel_size=2, stride=2)
  52. self.flatten = nn.Flatten()
  53. def construct(self, x):
  54. x = self.conv1(x)
  55. x = self.relu(x)
  56. x = self.max_pool2d(x)
  57. x = self.conv2(x)
  58. x = self.relu(x)
  59. x = self.max_pool2d(x)
  60. x = self.flatten(x)
  61. x = self.fc1(x)
  62. x = self.relu(x)
  63. x = self.fc2(x)
  64. x = self.relu(x)
  65. x = self.fc3(x)
  66. return x
  67. def create_dataset(data_path, batch_size=32, repeat_size=1,
  68. num_parallel_workers=1):
  69. """
  70. create dataset for train or test
  71. """
  72. # define dataset
  73. mnist_ds = ds.MnistDataset(data_path)
  74. resize_height, resize_width = 32, 32
  75. rescale = 1.0 / 255.0
  76. shift = 0.0
  77. rescale_nml = 1 / 0.3081
  78. shift_nml = -1 * 0.1307 / 0.3081
  79. # define map operations
  80. resize_op = CV.Resize((resize_height, resize_width), interpolation=Inter.LINEAR) # Bilinear mode
  81. rescale_nml_op = CV.Rescale(rescale_nml, shift_nml)
  82. rescale_op = CV.Rescale(rescale, shift)
  83. hwc2chw_op = CV.HWC2CHW()
  84. type_cast_op = C.TypeCast(mstype.int32)
  85. # apply map operations on images
  86. mnist_ds = mnist_ds.map(operations=type_cast_op, input_columns="label", num_parallel_workers=num_parallel_workers)
  87. mnist_ds = mnist_ds.map(operations=resize_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  88. mnist_ds = mnist_ds.map(operations=rescale_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  89. mnist_ds = mnist_ds.map(operations=rescale_nml_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  90. mnist_ds = mnist_ds.map(operations=hwc2chw_op, input_columns="image", num_parallel_workers=num_parallel_workers)
  91. # apply DatasetOps
  92. buffer_size = 10000
  93. mnist_ds = mnist_ds.shuffle(buffer_size=buffer_size) # 10000 as in LeNet train script
  94. mnist_ds = mnist_ds.batch(batch_size, drop_remainder=True)
  95. mnist_ds = mnist_ds.repeat(repeat_size)
  96. return mnist_ds
  97. if __name__ == '__main__':
  98. # get trained model
  99. network = LeNet5()
  100. param_dict = load_checkpoint('checkpoint_lenet.ckpt')
  101. load_param_into_net(network, param_dict)
  102. # get train and eval dataset
  103. ds_train = create_dataset('workspace/mnist/train')
  104. ds_eval = create_dataset('workspace/mnist/test')
  105. evaluation = UncertaintyEvaluation(model=network,
  106. train_dataset=ds_train,
  107. task_type='classification',
  108. num_classes=10,
  109. epochs=1,
  110. epi_uncer_model_path=None,
  111. ale_uncer_model_path=None,
  112. save_model=False)
  113. for eval_data in ds_eval.create_dict_iterator(output_numpy=True):
  114. eval_data = Tensor(eval_data['image'], mstype.float32)
  115. epistemic_uncertainty = evaluation.eval_epistemic_uncertainty(eval_data)
  116. aleatoric_uncertainty = evaluation.eval_aleatoric_uncertainty(eval_data)