inferencer.py 2.1 KB
Newer Older
H
Helin Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 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.

H
Helin Wang 已提交
15
import core
J
Jeff Wang 已提交
16 17 18
import framework
import executor
import io
Q
Qiao Longfei 已提交
19 20
from trainer import check_and_get_place

H
Helin Wang 已提交
21
__all__ = ['Inferencer', ]
H
Helin Wang 已提交
22 23 24


class Inferencer(object):
Q
Qiao Longfei 已提交
25 26 27 28 29 30
    def __init__(self, param_path, place=None):
        """
        :param param_path: the path where the inference model is saved by fluid.io.save_inference_model
        :param place: place to do the inference
        """
        self.param_path = param_path
H
Helin Wang 已提交
31
        self.scope = core.Scope()
J
Jeff Wang 已提交
32

Q
Qiao Longfei 已提交
33 34
        self.exe = executor.Executor(check_and_get_place(place))
        with executor.scope_guard(self.scope):
J
Jeff Wang 已提交
35
            # load params from param_path into scope
Q
Qiao Longfei 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
            [self.inference_program, _,
             self.fetch_targets] = io.load_inference_model(
                 executor=self.exe, dirname=param_path)

    def infer(self, inputs, return_numpy=True):
        """
        :param inputs: a map of {"input_name": input_var} that will be feed into the inference program
        to get the predict value
        :param return_numpy: if return numpy value for row tensor
        :return: the predict value of the inference model
        """
        if not isinstance(inputs, dict):
            raise ValueError(
                "inputs should be a map of {'input_name': input_var}")

        with executor.scope_guard(self.scope):
            results = self.exe.run(self.inference_program,
                                   feed=inputs,
                                   fetch_list=self.fetch_targets,
                                   return_numpy=return_numpy)

        return results