infer.py 1.4 KB
Newer Older
G
gmcather 已提交
1 2 3 4 5 6 7 8 9 10
import paddle.fluid as fluid
import paddle.v2 as paddle
import numpy as np
import sys
import time
import unittest
import contextlib
import utils


G
gmcather 已提交
11
def infer(test_reader, use_cuda, model_path=None):
G
gmcather 已提交
12 13 14
    """
    inference function
    """
G
gmcather 已提交
15 16
    if model_path is None:
        print(str(model_path) + " cannot be found")
G
gmcather 已提交
17 18 19 20 21 22 23 24
        return

    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)
    
    inference_scope = fluid.core.Scope()
    with fluid.scope_guard(inference_scope):
        [inference_program, feed_target_names,
G
gmcather 已提交
25
         fetch_targets] = fluid.io.load_inference_model(model_path, exe)
G
gmcather 已提交
26 27 28 29 30

        total_acc = 0.0
        total_count = 0
        for data in test_reader():
            acc = exe.run(inference_program,
G
gmcather 已提交
31 32 33
                          feed=utils.data2tensor(data, place),
                          fetch_list=fetch_targets,
                          return_numpy=True)
G
gmcather 已提交
34 35
            total_acc += acc[0] * len(data)
            total_count += len(data)
G
gmcather 已提交
36

G
gmcather 已提交
37 38
        avg_acc = total_acc / total_count
        print("model_path: %s, avg_acc: %f" % (model_path, avg_acc))
G
gmcather 已提交
39 40 41 42


if __name__ == "__main__":
    word_dict, train_reader, test_reader = utils.prepare_data(
G
gmcather 已提交
43
        "imdb", self_dict = False, batch_size = 128, buf_size = 50000)
G
gmcather 已提交
44 45

    model_path = sys.argv[1]
G
gmcather 已提交
46 47
    for i in range(30):
        epoch_path = model_path + "/" + "epoch" + str(i)
G
gmcather 已提交
48
        infer(test_reader, use_cuda=False, model_path=epoch_path)
G
gmcather 已提交
49