collate.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. # Copyright (c) 2021 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 numbers
  15. from collections.abc import Mapping, Sequence
  16. import numpy as np
  17. import paddle
  18. from ...framework import core
  19. def default_collate_fn(batch):
  20. """
  21. Default batch collating function for :code:`paddle.io.DataLoader`,
  22. get input data as a list of sample datas, each element in list
  23. if the data of a sample, and sample data should composed of list,
  24. dictionary, string, number, numpy array and paddle.Tensor, this
  25. function will parse input data recursively and stack number,
  26. numpy array and paddle.Tensor datas as batch datas. e.g. for
  27. following input data:
  28. [{'image': np.array(shape=[3, 224, 224]), 'label': 1},
  29. {'image': np.array(shape=[3, 224, 224]), 'label': 3},
  30. {'image': np.array(shape=[3, 224, 224]), 'label': 4},
  31. {'image': np.array(shape=[3, 224, 224]), 'label': 5},]
  32. This default collate function zipped each number and numpy array
  33. field together and stack each field as the batch field as follows:
  34. {'image': np.array(shape=[4, 3, 224, 224]), 'label': np.array([1, 3, 4, 5])}
  35. Args:
  36. batch(list of sample data): batch should be a list of sample data.
  37. Returns:
  38. Batched data: batched each number, numpy array and paddle.Tensor
  39. in input data.
  40. """
  41. sample = batch[0]
  42. if isinstance(sample, np.ndarray):
  43. batch = np.stack(batch, axis=0)
  44. return batch
  45. elif isinstance(sample, (paddle.Tensor, core.eager.Tensor)):
  46. return paddle.stack(batch, axis=0)
  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]) for key in sample
  55. }
  56. elif isinstance(sample, Sequence):
  57. sample_fields_num = len(sample)
  58. if not all(len(sample) == sample_fields_num for sample in iter(batch)):
  59. raise RuntimeError(
  60. "fields number not same among samples in a batch"
  61. )
  62. return [default_collate_fn(fields) for fields in zip(*batch)]
  63. raise TypeError(
  64. "batch data con only contains: tensor, numpy.ndarray, "
  65. f"dict, list, number, but got {type(sample)}"
  66. )
  67. def default_convert_fn(batch):
  68. """
  69. Default batch converting function for :code:`paddle.io.DataLoader`.
  70. get input data as a list of sample datas, each element in list
  71. if the data of a sample, and sample data should composed of list,
  72. dictionary, string, number, numpy array and paddle.Tensor.
  73. .. note::
  74. This function is default :attr:`collate_fn` in **Disable
  75. automatic batching** mode, for **Disable automatic batching**
  76. mode, please ses :attr:`paddle.io.DataLoader`
  77. Args:
  78. batch(list of sample data): batch should be a list of sample data.
  79. Returns:
  80. Batched data: batched each number, numpy array and paddle.Tensor
  81. in input data.
  82. """
  83. if isinstance(batch, (paddle.Tensor, np.ndarray, core.eager.Tensor)):
  84. return batch
  85. elif isinstance(batch, (str, bytes)):
  86. return batch
  87. elif isinstance(batch, Mapping):
  88. return {key: default_convert_fn(batch[key]) for key in batch}
  89. elif isinstance(batch, Sequence):
  90. return [default_convert_fn(d) for d in batch]
  91. else:
  92. return batch