inference.py 3.4 KB
Newer Older
Y
Yu Yang 已提交
1
import numpy
Y
Yu Yang 已提交
2
import py_paddle.swig_paddle as api
Y
Yu Yang 已提交
3
import collections
Y
Yu Yang 已提交
4
import topology
Y
Yu Yang 已提交
5
import minibatch
Y
Yu Yang 已提交
6 7
from data_feeder import DataFeeder

8
__all__ = ['infer']
Y
Yu Yang 已提交
9 10


Y
Yu Yang 已提交
11
class Inference(object):
12 13
    def __init__(self, output_layer, parameters):
        topo = topology.Topology(output_layer)
Y
Yu Yang 已提交
14 15 16 17 18
        gm = api.GradientMachine.createFromConfigProto(
            topo.proto(), api.CREATE_MODE_TESTING, [api.PARAMETER_VALUE])
        for param in gm.getParameters():
            val = param.getBuf(api.PARAMETER_VALUE)
            name = param.getName()
Y
Yu Yang 已提交
19 20
            assert isinstance(val, api.Vector)
            val.copyFromNumpyArray(parameters.get(name).flatten())
Y
Yu Yang 已提交
21 22 23
        self.__gradient_machine__ = gm
        self.__data_types__ = topo.data_type()

Y
Yu Yang 已提交
24
    def iter_infer(self, input, feeding=None):
Y
Yu Yang 已提交
25
        feeder = DataFeeder(self.__data_types__, feeding)
Y
Yu Yang 已提交
26
        batch_size = len(input)
Y
Yu Yang 已提交
27

Y
Yu Yang 已提交
28 29 30
        def __reader_impl__():
            for each_sample in input:
                yield each_sample
Y
Yu Yang 已提交
31

Y
Yu Yang 已提交
32
        reader = minibatch.batch(__reader_impl__, batch_size=batch_size)
Y
Yu Yang 已提交
33

Y
Yu Yang 已提交
34 35
        self.__gradient_machine__.start()
        for data_batch in reader():
Y
Yu Yang 已提交
36
            yield self.__gradient_machine__.forwardTest(feeder(data_batch))
Y
Yu Yang 已提交
37 38 39 40 41 42 43
        self.__gradient_machine__.finish()

    def iter_infer_field(self, field, **kwargs):
        for result in self.iter_infer(**kwargs):
            yield [each_result[field] for each_result in result]

    def infer(self, field='value', **kwargs):
T
Tao Luo 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57
        if not isinstance(field, list) and not isinstance(field, tuple):
            field = [field]

        retv_list = []
        for each_field in field:
            retv = None
            for result in self.iter_infer_field(field=each_field, **kwargs):
                if retv is None:
                    retv = [[]] * len(result)
                for i, item in enumerate(result):
                    retv[i].append(item)
            retv = [numpy.concatenate(out) for out in retv]
            retv_list.append(retv[0] if len(retv) == 1 else retv)
        return retv_list[0] if len(retv_list) == 1 else retv_list
Y
Yu Yang 已提交
58 59


60
def infer(output_layer, parameters, input, feeding=None, field='value'):
Y
Yu Yang 已提交
61 62 63 64 65 66 67 68 69 70 71 72
    """
    Infer a neural network by given neural network output and parameters.  The
    user should pass either a batch of input data or reader method.

    Example usages:

    ..  code-block:: python

        result = paddle.infer(prediction, parameters, input=SomeData,
                              batch_size=32)
        print result

73 74
    :param output_layer: output of the neural network that would be inferred
    :type output_layer: paddle.v2.config_base.Layer
Y
Yu Yang 已提交
75 76 77 78 79
    :param parameters: parameters of the neural network.
    :type parameters: paddle.v2.parameters.Parameters
    :param input: input data batch. Should be a python iterable object, and each
                  element is the data batch.
    :type input: collections.Iterable
80
    :param feeding: Reader dictionary. Default could generate from input
Y
Yu Yang 已提交
81 82 83 84 85 86 87 88 89
                        value.
    :param field: The prediction field. It should in [`value`, `ids`]. `value`
                  means return the prediction probabilities, `ids` means return
                  the prediction labels. Default is `value`
    :type field: str
    :return: a numpy array
    :rtype: numpy.ndarray
    """

90 91
    inferer = Inference(output_layer=output_layer, parameters=parameters)
    return inferer.infer(field=field, input=input, feeding=feeding)