utils.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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. import paddle
  15. import numbers
  16. import numpy as np
  17. try:
  18. from collections.abc import Sequence, Mapping
  19. except:
  20. from collections import Sequence, Mapping
  21. def default_collate_fn(batch):
  22. """
  23. Default batch collating function for :code:`paddle.io.DataLoader`,
  24. get input data as a list of sample datas, each element in list
  25. if the data of a sample, and sample data should composed of list,
  26. dictionary, string, number, numpy array, this
  27. function will parse input data recursively and stack number,
  28. numpy array and paddle.Tensor datas as batch datas. e.g. for
  29. following input data:
  30. [{'image': np.array(shape=[3, 224, 224]), 'label': 1},
  31. {'image': np.array(shape=[3, 224, 224]), 'label': 3},
  32. {'image': np.array(shape=[3, 224, 224]), 'label': 4},
  33. {'image': np.array(shape=[3, 224, 224]), 'label': 5},]
  34. This default collate function zipped each number and numpy array
  35. field together and stack each field as the batch field as follows:
  36. {'image': np.array(shape=[4, 3, 224, 224]), 'label': np.array([1, 3, 4, 5])}
  37. Args:
  38. batch(list of sample data): batch should be a list of sample data.
  39. Returns:
  40. Batched data: batched each number, numpy array and paddle.Tensor
  41. in input data.
  42. """
  43. sample = batch[0]
  44. if isinstance(sample, np.ndarray):
  45. batch = np.stack(batch, axis=0)
  46. return batch
  47. elif isinstance(sample, numbers.Number):
  48. batch = np.array(batch)
  49. return batch
  50. elif isinstance(sample, (str, bytes)):
  51. return batch
  52. elif isinstance(sample, Mapping):
  53. return {
  54. key: default_collate_fn([d[key] for d in batch])
  55. for key in sample
  56. }
  57. elif isinstance(sample, Sequence):
  58. sample_fields_num = len(sample)
  59. if not all(len(sample) == sample_fields_num for sample in iter(batch)):
  60. raise RuntimeError(
  61. "fileds number not same among samples in a batch")
  62. return [default_collate_fn(fields) for fields in zip(*batch)]
  63. raise TypeError("batch data con only contains: tensor, numpy.ndarray, "
  64. "dict, list, number, but got {}".format(type(sample)))