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.

train_dataset.py 2.4 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright 2021 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. """
  16. create train or eval dataset.
  17. """
  18. import mindspore.common.dtype as mstype
  19. import mindspore.dataset.engine as de
  20. import mindspore.dataset.vision.c_transforms as CV
  21. import mindspore.dataset.transforms.c_transforms as C
  22. from config import config
  23. from dataset.MGDataset import DistributedPKSampler, MGDataset
  24. def create_dataset(data_dir, p=16, k=8):
  25. """
  26. create a train or eval dataset
  27. Args:
  28. dataset_path(string): the path of dataset.
  29. p(int): randomly choose p classes from all classes.
  30. k(int): randomly choose k images from each of the chosen p classes.
  31. p * k is the batchsize.
  32. Returns:
  33. dataset
  34. """
  35. dataset = MGDataset(data_dir)
  36. sampler = DistributedPKSampler(dataset, p=p, k=k)
  37. de_dataset = de.GeneratorDataset(dataset, ["image", "label1", "label2"], sampler=sampler)
  38. resize_height = config.image_height
  39. resize_width = config.image_width
  40. rescale = 1.0 / 255.0
  41. shift = 0.0
  42. resize_op = CV.Resize((resize_height, resize_width))
  43. rescale_op = CV.Rescale(rescale, shift)
  44. normalize_op = CV.Normalize([0.486, 0.459, 0.408], [0.229, 0.224, 0.225])
  45. change_swap_op = CV.HWC2CHW()
  46. trans = []
  47. trans += [resize_op, rescale_op, normalize_op, change_swap_op]
  48. type_cast_op_label1 = C.TypeCast(mstype.int32)
  49. type_cast_op_label2 = C.TypeCast(mstype.float32)
  50. de_dataset = de_dataset.map(input_columns="label1", operations=type_cast_op_label1)
  51. de_dataset = de_dataset.map(input_columns="label2", operations=type_cast_op_label2)
  52. de_dataset = de_dataset.map(input_columns="image", operations=trans)
  53. de_dataset = de_dataset.batch(p*k, drop_remainder=True)
  54. return de_dataset