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.

callbacks.py 1.8 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. from mindspore.train.callback import Callback
  17. from mindspore.train.serialization import save_checkpoint
  18. class SaveCallback(Callback):
  19. """
  20. Evaluating on eval_dataset after each epoch.
  21. And it will save the parameters if the accuracy is better.
  22. """
  23. def __init__(self, model, eval_dataset, ckpt_path):
  24. super(SaveCallback, self).__init__()
  25. self.model = model
  26. self.eval_dataset = eval_dataset
  27. self.acc = 0.2
  28. self.ckpt_path = ckpt_path
  29. def step_end(self, run_context):
  30. cb_params = run_context.original_args()
  31. epoch_num = cb_params.cur_epoch_num
  32. result = self.model.eval(self.eval_dataset)
  33. print("epoch", epoch_num, " top_1_accuracy:", result['top_1_accuracy'])
  34. if result['top_1_accuracy'] > self.acc:
  35. self.acc = result['top_1_accuracy']
  36. file_name = "max.ckpt"
  37. file_name = os.path.join(self.ckpt_path, file_name)
  38. save_checkpoint(save_obj=cb_params.train_network, ckpt_file_name=file_name)
  39. print("Save the maximum accuracy checkpoint,the accuracy is", self.acc)