predict.py 4.1 KB
Newer Older
0
0YuanZhang0 已提交
1
# -*- coding: utf-8 -*-
0
0YuanZhang0 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2019 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.
"""predict auto dialogue evaluation task"""
0
0YuanZhang0 已提交
16
import io
0
0YuanZhang0 已提交
17 18 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
import os
import sys
import six
import time
import numpy as np

import paddle
import paddle.fluid as fluid

import ade.reader as reader
from ade_net import create_net

from ade.utils.configure import PDConfig
from ade.utils.input_field import InputField
from ade.utils.model_check import check_cuda
import ade.utils.save_load_io as save_load_io


def do_predict(args): 
    """
    predict function
    """
    test_prog = fluid.default_main_program()
    startup_prog = fluid.default_startup_program()

    with fluid.program_guard(test_prog, startup_prog):
        test_prog.random_seed = args.random_seed
        startup_prog.random_seed = args.random_seed

        with fluid.unique_name.guard():

0
0YuanZhang0 已提交
48 49 50 51 52 53
            context_wordseq = fluid.data(
                    name='context_wordseq', shape=[-1, 1], dtype='int64', lod_level=1)
            response_wordseq = fluid.data(
                    name='response_wordseq', shape=[-1, 1], dtype='int64', lod_level=1)
            labels = fluid.data(
                    name='labels', shape=[-1, 1], dtype='int64')
0
0YuanZhang0 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

            input_inst = [context_wordseq, response_wordseq, labels]
            input_field = InputField(input_inst)
            data_reader = fluid.io.PyReader(feed_list=input_inst, 
                        capacity=4, iterable=False)

            logits = create_net(
                    is_training=False,
                    model_input=input_field, 
                    args=args
                )
            logits.persistable = True

            fetch_list = [logits.name]
    #for_test is True if change the is_test attribute of operators to True
    test_prog = test_prog.clone(for_test=True)
    if args.use_cuda: 
        place = fluid.CUDAPlace(int(os.getenv('FLAGS_selected_gpus', '0')))
    else: 
        place = fluid.CPUPlace()

    exe = fluid.Executor(place)
    exe.run(startup_prog)

    assert (args.init_from_params) or (args.init_from_pretrain_model)
    if args.init_from_params:
        save_load_io.init_from_params(args, exe, test_prog)
    if args.init_from_pretrain_model:
        save_load_io.init_from_pretrain_model(args, exe, test_prog)

    compiled_test_prog = fluid.CompiledProgram(test_prog)

    processor = reader.DataProcessor(
        data_path=args.predict_file,
        max_seq_length=args.max_seq_len, 
        batch_size=args.batch_size)

    batch_generator = processor.data_generator(
        place=place,
        phase="test",
        shuffle=False, 
        sample_pro=1)
    num_test_examples = processor.get_num_examples(phase='test')

    data_reader.decorate_batch_generator(batch_generator)
    data_reader.start()

    scores = []
    while True: 
        try: 
            results = exe.run(compiled_test_prog, fetch_list=fetch_list)
            scores.extend(results[0])
        except fluid.core.EOFException:
            data_reader.reset()
            break

    scores = scores[: num_test_examples]
0
0YuanZhang0 已提交
111
    print("Write the predicted results into the output_prediction_file")
0
0YuanZhang0 已提交
112 113 114
    fw = io.open(args.output_prediction_file, 'w', encoding="utf8")
    for index, score in enumerate(scores): 
        fw.write("%s\t%s\n" % (index, score))
0
0YuanZhang0 已提交
115
    print("finish........................................")
0
0YuanZhang0 已提交
116 117 118 119 120 121 122 123 124 125 126


if __name__ == "__main__": 
    
    args = PDConfig(yaml_file="./data/config/ade.yaml")
    args.build()
    args.Print()

    check_cuda(args.use_cuda)

    do_predict(args)