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_deeplabv3.py 4.5 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. """train."""
  16. import argparse
  17. import time
  18. import pytest
  19. import numpy as np
  20. from mindspore import context, Tensor
  21. from mindspore.nn.optim.momentum import Momentum
  22. from mindspore import Model
  23. from mindspore.train.callback import Callback
  24. from src.md_dataset import create_dataset
  25. from src.losses import OhemLoss
  26. from src.deeplabv3 import deeplabv3_resnet50
  27. from src.config import config
  28. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend")
  29. #--train
  30. #--eval
  31. # --Images
  32. # --2008_001135.jpg
  33. # --2008_001404.jpg
  34. # --SegmentationClassRaw
  35. # --2008_001135.png
  36. # --2008_001404.png
  37. data_url = "/home/workspace/mindspore_dataset/voc/voc2012"
  38. class LossCallBack(Callback):
  39. """
  40. Monitor the loss in training.
  41. Note:
  42. if per_print_times is 0 do not print loss.
  43. Args:
  44. per_print_times (int): Print loss every times. Default: 1.
  45. """
  46. def __init__(self, data_size, per_print_times=1):
  47. super(LossCallBack, self).__init__()
  48. if not isinstance(per_print_times, int) or per_print_times < 0:
  49. raise ValueError("print_step must be int and >= 0")
  50. self.data_size = data_size
  51. self._per_print_times = per_print_times
  52. self.time = 1000
  53. self.loss = 0
  54. def epoch_begin(self, run_context):
  55. self.epoch_time = time.time()
  56. def step_end(self, run_context):
  57. cb_params = run_context.original_args()
  58. epoch_mseconds = (time.time() - self.epoch_time) * 1000
  59. self.time = epoch_mseconds / self.data_size
  60. self.loss = cb_params.net_outputs
  61. print("epoch: {}, step: {}, outputs are {}".format(cb_params.cur_epoch_num, cb_params.cur_step_num,
  62. str(cb_params.net_outputs)))
  63. def model_fine_tune(train_net, fix_weight_layer):
  64. train_net.init_parameters_data()
  65. for para in train_net.trainable_params():
  66. para.set_data(Tensor(np.ones(para.data.shape).astype(np.float32) * 0.02))
  67. if fix_weight_layer in para.name:
  68. para.requires_grad = False
  69. @pytest.mark.level0
  70. @pytest.mark.platform_arm_ascend_training
  71. @pytest.mark.platform_x86_ascend_training
  72. @pytest.mark.env_onecard
  73. def test_deeplabv3_1p():
  74. start_time = time.time()
  75. epoch_size = 100
  76. args_opt = argparse.Namespace(base_size=513, crop_size=513, batch_size=2)
  77. args_opt.base_size = config.crop_size
  78. args_opt.crop_size = config.crop_size
  79. args_opt.batch_size = config.batch_size
  80. train_dataset = create_dataset(args_opt, data_url, 1, config.batch_size,
  81. usage="eval")
  82. dataset_size = train_dataset.get_dataset_size()
  83. callback = LossCallBack(dataset_size)
  84. net = deeplabv3_resnet50(config.seg_num_classes, [config.batch_size, 3, args_opt.crop_size, args_opt.crop_size],
  85. infer_scale_sizes=config.eval_scales, atrous_rates=config.atrous_rates,
  86. decoder_output_stride=config.decoder_output_stride, output_stride=config.output_stride,
  87. fine_tune_batch_norm=config.fine_tune_batch_norm, image_pyramid=config.image_pyramid)
  88. net.set_train()
  89. model_fine_tune(net, 'layer')
  90. loss = OhemLoss(config.seg_num_classes, config.ignore_label)
  91. opt = Momentum(filter(lambda x: 'beta' not in x.name and 'gamma' not in x.name and 'depth' not in x.name and 'bias' not in x.name, net.trainable_params()), learning_rate=config.learning_rate, momentum=config.momentum, weight_decay=config.weight_decay)
  92. model = Model(net, loss, opt)
  93. model.train(epoch_size, train_dataset, callback)
  94. print(time.time() - start_time)
  95. print("expect loss: ", callback.loss)
  96. print("expect time: ", callback.time)
  97. expect_loss = 0.92
  98. expect_time = 43
  99. assert callback.loss.asnumpy() <= expect_loss
  100. assert callback.time <= expect_time