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.

dataset.py 5.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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. """
  16. Data operations, will be used in train.py and eval.py
  17. """
  18. import os
  19. import mindspore.common.dtype as mstype
  20. import mindspore.dataset as ds
  21. import mindspore.dataset.transforms.c_transforms as C
  22. import mindspore.dataset.vision.c_transforms as vision
  23. from src.config import cifar_cfg, imagenet_cfg
  24. def create_dataset_cifar10(data_home, repeat_num=1, training=True):
  25. """Data operations."""
  26. data_dir = os.path.join(data_home, "cifar-10-batches-bin")
  27. if not training:
  28. data_dir = os.path.join(data_home, "cifar-10-verify-bin")
  29. rank_size, rank_id = _get_rank_info()
  30. if training:
  31. data_set = ds.Cifar10Dataset(data_dir, num_shards=rank_size, shard_id=rank_id, shuffle=True)
  32. else:
  33. data_set = ds.Cifar10Dataset(data_dir, num_shards=rank_size, shard_id=rank_id, shuffle=False)
  34. resize_height = cifar_cfg.image_height
  35. resize_width = cifar_cfg.image_width
  36. # define map operations
  37. random_crop_op = vision.RandomCrop((32, 32), (4, 4, 4, 4)) # padding_mode default CONSTANT
  38. random_horizontal_op = vision.RandomHorizontalFlip()
  39. resize_op = vision.Resize((resize_height, resize_width)) # interpolation default BILINEAR
  40. rescale_op = vision.Rescale(1.0 / 255.0, 0.0)
  41. normalize_op = vision.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010))
  42. changeswap_op = vision.HWC2CHW()
  43. type_cast_op = C.TypeCast(mstype.int32)
  44. c_trans = []
  45. if training:
  46. c_trans = [random_crop_op, random_horizontal_op]
  47. c_trans += [resize_op, rescale_op, normalize_op, changeswap_op]
  48. # apply map operations on images
  49. data_set = data_set.map(operations=type_cast_op, input_columns="label")
  50. data_set = data_set.map(operations=c_trans, input_columns="image")
  51. # apply batch operations
  52. data_set = data_set.batch(batch_size=cifar_cfg.batch_size, drop_remainder=True)
  53. # apply repeat operations
  54. data_set = data_set.repeat(repeat_num)
  55. return data_set
  56. def create_dataset_imagenet(dataset_path, repeat_num=1, training=True,
  57. num_parallel_workers=None, shuffle=None):
  58. """
  59. create a train or eval imagenet2012 dataset for resnet50
  60. Args:
  61. dataset_path(string): the path of dataset.
  62. do_train(bool): whether dataset is used for train or eval.
  63. repeat_num(int): the repeat times of dataset. Default: 1
  64. batch_size(int): the batch size of dataset. Default: 32
  65. target(str): the device target. Default: Ascend
  66. Returns:
  67. dataset
  68. """
  69. device_num, rank_id = _get_rank_info()
  70. if device_num == 1:
  71. data_set = ds.ImageFolderDataset(dataset_path, num_parallel_workers=num_parallel_workers, shuffle=shuffle)
  72. else:
  73. data_set = ds.ImageFolderDataset(dataset_path, num_parallel_workers=num_parallel_workers, shuffle=shuffle,
  74. num_shards=device_num, shard_id=rank_id)
  75. assert imagenet_cfg.image_height == imagenet_cfg.image_width, "image_height not equal image_width"
  76. image_size = imagenet_cfg.image_height
  77. mean = [0.485 * 255, 0.456 * 255, 0.406 * 255]
  78. std = [0.229 * 255, 0.224 * 255, 0.225 * 255]
  79. # define map operations
  80. if training:
  81. transform_img = [
  82. vision.RandomCropDecodeResize(image_size, scale=(0.08, 1.0), ratio=(0.75, 1.333)),
  83. vision.RandomHorizontalFlip(prob=0.5),
  84. vision.RandomColorAdjust(0.4, 0.4, 0.4, 0.1),
  85. vision.Normalize(mean=mean, std=std),
  86. vision.HWC2CHW()
  87. ]
  88. else:
  89. transform_img = [
  90. vision.Decode(),
  91. vision.Resize(256),
  92. vision.CenterCrop(image_size),
  93. vision.Normalize(mean=mean, std=std),
  94. vision.HWC2CHW()
  95. ]
  96. transform_label = [C.TypeCast(mstype.int32)]
  97. data_set = data_set.map(input_columns="image", num_parallel_workers=12, operations=transform_img)
  98. data_set = data_set.map(input_columns="label", num_parallel_workers=4, operations=transform_label)
  99. # apply batch operations
  100. data_set = data_set.batch(imagenet_cfg.batch_size, drop_remainder=True)
  101. # apply dataset repeat operation
  102. data_set = data_set.repeat(repeat_num)
  103. return data_set
  104. def _get_rank_info():
  105. """
  106. get rank size and rank id
  107. """
  108. rank_size = int(os.environ.get("RANK_SIZE", 1))
  109. if rank_size > 1:
  110. from mindspore.communication.management import get_rank, get_group_size
  111. rank_size = get_group_size()
  112. rank_id = get_rank()
  113. else:
  114. rank_size = rank_id = None
  115. return rank_size, rank_id