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 2.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. Produce the dataset
  17. """
  18. import mindspore.dataset as ds
  19. import mindspore.dataset.transforms.vision.c_transforms as CV
  20. import mindspore.dataset.transforms.c_transforms as C
  21. from mindspore.dataset.transforms.vision import Inter
  22. from mindspore.common import dtype as mstype
  23. def create_dataset(data_path, batch_size=32, repeat_size=1,
  24. num_parallel_workers=1):
  25. """
  26. create dataset for train or test
  27. """
  28. # define dataset
  29. mnist_ds = ds.MnistDataset(data_path)
  30. resize_height, resize_width = 32, 32
  31. rescale = 1.0 / 255.0
  32. shift = 0.0
  33. rescale_nml = 1 / 0.3081
  34. shift_nml = -1 * 0.1307 / 0.3081
  35. # define map operations
  36. resize_op = CV.Resize((resize_height, resize_width), interpolation=Inter.LINEAR) # Bilinear mode
  37. rescale_nml_op = CV.Rescale(rescale_nml, shift_nml)
  38. rescale_op = CV.Rescale(rescale, shift)
  39. hwc2chw_op = CV.HWC2CHW()
  40. type_cast_op = C.TypeCast(mstype.int32)
  41. # apply map operations on images
  42. mnist_ds = mnist_ds.map(input_columns="label", operations=type_cast_op, num_parallel_workers=num_parallel_workers)
  43. mnist_ds = mnist_ds.map(input_columns="image", operations=resize_op, num_parallel_workers=num_parallel_workers)
  44. mnist_ds = mnist_ds.map(input_columns="image", operations=rescale_op, num_parallel_workers=num_parallel_workers)
  45. mnist_ds = mnist_ds.map(input_columns="image", operations=rescale_nml_op, num_parallel_workers=num_parallel_workers)
  46. mnist_ds = mnist_ds.map(input_columns="image", operations=hwc2chw_op, num_parallel_workers=num_parallel_workers)
  47. # apply DatasetOps
  48. buffer_size = 10000
  49. mnist_ds = mnist_ds.shuffle(buffer_size=buffer_size) # 10000 as in LeNet train script
  50. mnist_ds = mnist_ds.batch(batch_size, drop_remainder=True)
  51. mnist_ds = mnist_ds.repeat(repeat_size)
  52. return mnist_ds