collate.py 4.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import paddle
import numbers
import numpy as np
J
Jiabin Yang 已提交
18
from ..framework import _non_static_mode
19 20
from .. import core, layers

21
from collections.abc import Sequence, Mapping
22 23 24 25 26


def default_collate_fn(batch):
    """
    Default batch collating function for :code:`paddle.io.DataLoader`,
27 28 29 30 31 32 33 34 35 36 37
    get input data as a list of sample datas, each element in list
    if the data of a sample, and sample data should composed of list,
    dictionary, string, number, numpy array and paddle.Tensor, this
    function will parse input data recursively and stack number,
    numpy array and paddle.Tensor datas as batch datas. e.g. for
    following input data:

    [{'image': np.array(shape=[3, 224, 224]), 'label': 1},
     {'image': np.array(shape=[3, 224, 224]), 'label': 3},
     {'image': np.array(shape=[3, 224, 224]), 'label': 4},
     {'image': np.array(shape=[3, 224, 224]), 'label': 5},]
38 39


40 41 42 43
    This default collate function zipped each number and numpy array
    field together and stack each field as the batch field as follows:

    {'image': np.array(shape=[4, 3, 224, 224]), 'label': np.array([1, 3, 4, 5])}
44 45


46
    Args:
47
        batch(list of sample data): batch should be a list of sample data.
48

49
    Returns:
50 51
        Batched data: batched each number, numpy array and paddle.Tensor
                      in input data.
52 53 54 55 56
    """
    sample = batch[0]
    if isinstance(sample, np.ndarray):
        batch = np.stack(batch, axis=0)
        return batch
W
wanghuancoder 已提交
57
    elif isinstance(sample, (paddle.Tensor, core.eager.Tensor)):
58
        return paddle.stack(batch, axis=0)
59 60 61 62 63 64 65
    elif isinstance(sample, numbers.Number):
        batch = np.array(batch)
        return batch
    elif isinstance(sample, (str, bytes)):
        return batch
    elif isinstance(sample, Mapping):
        return {
66
            key: default_collate_fn([d[key] for d in batch]) for key in sample
67 68 69 70 71
        }
    elif isinstance(sample, Sequence):
        sample_fields_num = len(sample)
        if not all(len(sample) == sample_fields_num for sample in iter(batch)):
            raise RuntimeError(
72 73
                "fileds number not same among samples in a batch"
            )
74 75
        return [default_collate_fn(fields) for fields in zip(*batch)]

76 77 78 79
    raise TypeError(
        "batch data con only contains: tensor, numpy.ndarray, "
        "dict, list, number, but got {}".format(type(sample))
    )
80 81 82


def default_convert_fn(batch):
83 84 85 86 87 88 89 90 91 92 93
    """
    Default batch converting function for :code:`paddle.io.DataLoader`.
    get input data as a list of sample datas, each element in list
    if the data of a sample, and sample data should composed of list,
    dictionary, string, number, numpy array and paddle.Tensor.

    .. note::
        This function is default :attr:`collate_fn` in **Distable
        automatic batching** mode, for **Distable automatic batching**
        mode, please ses :attr:`paddle.io.DataLoader`

94
    Args:
95
        batch(list of sample data): batch should be a list of sample data.
96

97 98 99 100
    Returns:
        Batched data: batched each number, numpy array and paddle.Tensor
                      in input data.
    """
W
wanghuancoder 已提交
101
    if isinstance(batch, (paddle.Tensor, np.ndarray, core.eager.Tensor)):
102 103 104 105 106 107 108 109 110
        return batch
    elif isinstance(batch, (str, bytes)):
        return batch
    elif isinstance(batch, Mapping):
        return {key: default_convert_fn(batch[key]) for key in batch}
    elif isinstance(batch, Sequence):
        return [default_convert_fn(d) for d in batch]
    else:
        return batch