data_converter.py 8.1 KB
Newer Older
D
dangqingqing 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2016 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 collections
D
dangqingqing 已提交
16 17
import py_paddle.swig_paddle as api
import numpy as np
D
dangqingqing 已提交
18
import paddle.trainer.PyDataProvider2 as dp2
D
dangqingqing 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

__all__ = ['DataConverter']


class IDataConverter(object):
    def __init__(self, input_type, pos):
        """
        :param input_type: data type
        :type input_type: dp2.InputType
        :param pos: which input, start from 0
        :type pos: int
        """
        self.input_type = input_type
        assert isinstance(self.input_type, dp2.InputType)
        self.pos = pos

    def convert(self, data, argument):
        """
        Conv data to paddle format.
        :param data: input data
        :param argument: paddle format
        """
        pass


class DenseConvert(IDataConverter):
    def __init__(self, input_type, pos):
        IDataConverter.__init__(self, input_type, pos)

    def convert(self, data, argument):
        """
        :param data: input data
        :type data: list | numpy array
        :param argument: the type which paddle is acceptable
D
dangqingqing 已提交
53
        :type argument: Paddle's Arguments
D
dangqingqing 已提交
54
        """
D
dangqingqing 已提交
55 56 57 58
        assert isinstance(argument, api.Arguments)
        if data.dtype != np.float32:
            data = data.astype(np.float32)
        m = api.Matrix.createDenseFromNumpy(data, True, False)
D
dangqingqing 已提交
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
        argument.setSlotValue(self.pos, m)


class SparseBinaryConvert(IDataConverter):
    def __init__(self, input_type, pos):
        IDataConverter.__init__(self, input_type, pos)
        self.__rows__ = [0]
        self.__cols__ = []
        self.__height__ = 0
        self.__nnz__ = 0
        self.__value__ = []

    def fill_csr(self, data):
        self.__height__ = len(data)
        for x in data:
            self.__rows__.append(self.__rows__[-1] + len(x))
D
dangqingqing 已提交
75
        self.__cols__ = data.flatten()
D
dangqingqing 已提交
76 77

    def convert(self, data, argument):
D
dangqingqing 已提交
78
        assert isinstance(argument, api.Arguments)
D
dangqingqing 已提交
79 80

        fill_csr(data)
D
dangqingqing 已提交
81 82 83 84
        m = api.Matrix.createSparse(self.__height__, self.input_type.dim,
                                    len(self.__cols__),
                                    len(self.__value__) == 0)
        assert isinstance(m, api.Matrix)
D
dangqingqing 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        m.sparseCopyFrom(self.__rows__, self.__cols__, self.__value__)
        argument.setSlotValue(self.pos, m)


class SparseFloatConvert(SparseBinaryConvert):
    def __init__(self, input_type, pos):
        SparseBinaryConvert.__init__(self, input_type, pos)

    def fill_csr(self, data):
        self.__height__ = len(data)
        for x in data:
            self.__rows__.append(self.__rows__[-1] + len(x))
        self.__cols__.extend((x[0] for x in data))
        self.__value__.extend((x[1] for x in data))


class IndexConvert(IDataConverter):
    def __init__(self, input_type, pos):
        IDataConverter.__init__(self, input_type, pos)
        self.__ids__ = []

    def convert(self, data, argument):
D
dangqingqing 已提交
107
        assert isinstance(argument, api.Arguments)
D
dangqingqing 已提交
108
        self.__ids__ = data.flatten()
D
dangqingqing 已提交
109
        ids = api.IVector.create(self.__ids__)
D
dangqingqing 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        argument.setSlotIds(self.pos, ids)


class SequenceConvert(IDataConverter):
    def __init__(self, input_type, pos, inner_convert, setter):
        """
        :param input_type: the type of input data
        :type input_type: dp2.InputType
        :param pos: the position of this input
        :type pos: int
        :param inner_convert: DataConvert type
        :type inner_convert: DenseConvert|SparseBinaryConvert|
                             SparseFloatConvert|IndexConvert
        :param setter:
        :type setter:
        """
        IDataConverter.__init__(self, input_type, pos)
        self.__seq__ = [0]
        self.__inner_convert__ = inner_convert
        self.__setter__ = setter

    def fill_seq(self, data):
        for each in data:
            self.__seq__.append(self.__seq__[-1] + self.get_size(each))

    def convert(self, data, argument):
        fill_seq(data)
D
dangqingqing 已提交
137
        seq = api.IVector.create(self.__seq__, False)
D
dangqingqing 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        self.__setter__(argument, self.pos, seq)

        dat = []
        for each in data:
            dat.append(each)
        self.__inner_scanner__.convert(dat, argument)

    def get_size(self, data):
        if isinstance(self.__inner_scanner__, SequenceConvert):
            return sum(self.__inner_scanner__.get_size(item) for item in dat)
        else:
            return len(data)


class DataConverter(object):
D
dangqingqing 已提交
153
    def __init__(self, input):
D
dangqingqing 已提交
154 155 156 157 158 159
        """
        Usege:

        .. code-block:: python
            inputs = [('image', dense_vector), ('label', integer_value)]
            cvt = DataConverter(inputs)
D
dangqingqing 已提交
160
            arg = cvt(minibatch_data, {'image':0, 'label':1})
D
dangqingqing 已提交
161 162 163 164 165 166

        :param input_mapper: list of (input_name, input_type)
        :type input_mapper: list
        """
        self.input_names = []
        self.input_types = []
D
dangqingqing 已提交
167
        for each in input:
D
dangqingqing 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
            self.input_names.append(each[0])
            self.input_types.append(each[1])
            assert isinstance(each[1], dp2.InputType)

    def convert(self, data, input_dict=None, argument=None):
        """
        Convert minibatch data to Paddle's argument. The data is numpy array
        or list.

        :param data: input samples, for example, [column0, column1, ...] or
                     (column0, column1, ...) each column is one minibatch
                     feature. Note, if only one column featrue, data also
                     shuld be a list or tupe, [column0] or (column0).
        :type data: list|tuple
        :param input_dict: a dictionary to specify the correspondence
                           of data_layer and input data. If None,
                           the feature order in argument and data is the same.
        :type input_dict: dict, like {string:integer, string, integer, ...}|None
        :param argument: converted data will be saved in this argument. If None,
D
dangqingqing 已提交
187
                         it will create a Paddle's Arguments firstly.
D
dangqingqing 已提交
188 189 190
        :param type: swig_paddle.Arguments|None
        """
        if argument is None:
D
dangqingqing 已提交
191 192
            argument = api.Arguments.createArguments(0)
        assert isinstance(argument, api.Arguments)
D
dangqingqing 已提交
193 194 195
        argument.resize(len(self.input_types))

        converts = [
D
dangqingqing 已提交
196
            DataConverter.create_converter(i, each_type)
D
dangqingqing 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
            for i, each_type in enumerate(self.input_types)
        ]

        for i, cvt in enumerate(converts):
            if input_dict is not None:
                dat = data[input_dict[self.input_names[i]]]
            else:
                dat = data[i]
            cvt.convert(dat, argument)

        return argument

    def __call__(self, dat, argument=None):
        return self.convert(dat, argument)

    @staticmethod
D
dangqingqing 已提交
213
    def create_converter(pos, each):
D
dangqingqing 已提交
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        assert isinstance(each, dp2.InputType)
        retv = None
        if each.type == dp2.DataType.Dense:
            retv = DenseConvert(each, pos)
        elif each.type == dp2.DataType.Index:
            retv = IndexConvert(each, pos)
        elif each.type == dp2.DataType.SparseNonValue:
            retv = SparseBinaryConvert(each, pos)
        elif each.type == dp2.DataType.SparseValue:
            retv = SparseFloatConvert(each, pos)
        assert retv is not None

        if each.seq_type == dp2.SequenceType.SUB_SEQUENCE:
            retv = SequenceConvert(
                each, pos, retv,
                lambda arg, pos, seq: arg.setSlotSubSequenceStartPositions(pos, seq)
            )

        if each.seq_type in [
                dp2.SequenceType.SUB_SEQUENCE, dp2.SequenceType.SEQUENCE
        ]:
            retv = SequenceConvert(
                each, pos, retv,
                lambda arg, pos, seq: arg.setSlotSequenceStartPositions(pos, seq)
            )
        return retv