reader.py 4.7 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 16
# 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.
"""Reader for auto dialogue evaluation"""

0
0YuanZhang0 已提交
17
import io
0
0YuanZhang0 已提交
18 19 20 21
import sys
import time
import random
import numpy as np
u010070587's avatar
u010070587 已提交
22
import os
0
0YuanZhang0 已提交
23 24 25 26 27

import paddle
import paddle.fluid as fluid


u010070587's avatar
u010070587 已提交
28 29
class DataProcessor(object):
    def __init__(self, data_path, max_seq_length, batch_size):
0
0YuanZhang0 已提交
30 31 32 33 34 35
        """init"""
        self.data_file = data_path
        self.max_seq_len = max_seq_length
        self.batch_size = batch_size
        self.num_examples = {'train': -1, 'dev': -1, 'test': -1}

u010070587's avatar
u010070587 已提交
36
    def get_examples(self):
0
0YuanZhang0 已提交
37 38
        """load examples"""
        examples = []
0
0YuanZhang0 已提交
39
        index = 0
0
0YuanZhang0 已提交
40
        fr = io.open(self.data_file, 'r', encoding="utf8")
u010070587's avatar
u010070587 已提交
41 42
        for line in fr:
            if index != 0 and index % 100 == 0:
0
0YuanZhang0 已提交
43 44 45
                print("processing data: %d" % index)
            index += 1
            examples.append(line.strip())
0
0YuanZhang0 已提交
46 47
        return examples

u010070587's avatar
u010070587 已提交
48
    def get_num_examples(self, phase):
0
0YuanZhang0 已提交
49
        """Get number of examples for train, dev or test."""
u010070587's avatar
u010070587 已提交
50
        if phase not in ['train', 'dev', 'test']:
0
0YuanZhang0 已提交
51 52
            raise ValueError(
                "Unknown phase, which should be in ['train', 'dev', 'test'].")
0
0YuanZhang0 已提交
53
        count = len(io.open(self.data_file, 'r', encoding="utf8").readlines())
0
0YuanZhang0 已提交
54 55 56
        self.num_examples[phase] = count
        return self.num_examples[phase]

u010070587's avatar
u010070587 已提交
57
    def data_generator(self, place, phase="train", shuffle=True, sample_pro=1):
0
0YuanZhang0 已提交
58 59 60 61 62 63 64 65 66
        """
        Generate data for train, dev or test.

        Args:
            phase: string. The phase for which to generate data.
            shuffle: bool. Whether to shuffle examples.
            sample_pro: sample data ratio
        """
        examples = self.get_examples()
u010070587's avatar
u010070587 已提交
67 68 69 70 71 72 73 74

        # used for ce
        if 'ce_mode' in os.environ:
            np.random.seed(0)
            random.seed(0)
            shuffle = False

        if shuffle:
0
0YuanZhang0 已提交
75
            np.random.shuffle(examples)
u010070587's avatar
u010070587 已提交
76 77

        def batch_reader():
0
0YuanZhang0 已提交
78 79
            """read batch data"""
            batch = []
u010070587's avatar
u010070587 已提交
80
            for example in examples:
0
0YuanZhang0 已提交
81 82 83 84
                if sample_pro < 1:
                    if random.random() > sample_pro:
                        continue
                tokens = example.strip().split('\t')
u010070587's avatar
u010070587 已提交
85 86

                if len(tokens) != 3:
0
0YuanZhang0 已提交
87 88 89 90
                    print("data format error: %s" % example.strip())
                    print("please input data: context \t response \t label")
                    continue

u010070587's avatar
u010070587 已提交
91 92 93 94
                context = [int(x) for x in tokens[0].split()[:self.max_seq_len]]
                response = [
                    int(x) for x in tokens[1].split()[:self.max_seq_len]
                ]
0
0YuanZhang0 已提交
95 96 97 98 99 100 101 102 103 104
                label = [int(tokens[2])]
                instance = (context, response, label)

                if len(batch) < self.batch_size:
                    batch.append(instance)
                else:
                    if len(batch) == self.batch_size:
                        yield batch
                    batch = [instance]

u010070587's avatar
u010070587 已提交
105
            if len(batch) > 0:
0
0YuanZhang0 已提交
106 107
                yield batch

u010070587's avatar
u010070587 已提交
108
        def create_lodtensor(data_ids, place):
0
0YuanZhang0 已提交
109 110 111 112
            """create LodTensor for input ids"""
            cur_len = 0
            lod = [cur_len]
            seq_lens = [len(ids) for ids in data_ids]
u010070587's avatar
u010070587 已提交
113
            for l in seq_lens:
0
0YuanZhang0 已提交
114 115 116 117 118 119 120 121 122
                cur_len += l
                lod.append(cur_len)
            flattened_data = np.concatenate(data_ids, axis=0).astype("int64")
            flattened_data = flattened_data.reshape([len(flattened_data), 1])
            res = fluid.LoDTensor()
            res.set(flattened_data, place)
            res.set_lod([lod])
            return res

u010070587's avatar
u010070587 已提交
123 124 125
        def wrapper():
            """yield batch data to network"""
            for batch_data in batch_reader():
0
0YuanZhang0 已提交
126 127 128 129 130 131 132 133 134
                context_ids = [batch[0] for batch in batch_data]
                response_ids = [batch[1] for batch in batch_data]
                label_ids = [batch[2] for batch in batch_data]
                context_res = create_lodtensor(context_ids, place)
                response_res = create_lodtensor(response_ids, place)
                label_ids = np.array(label_ids).astype("int64").reshape([-1, 1])
                input_batch = [context_res, response_res, label_ids]
                yield input_batch

u010070587's avatar
u010070587 已提交
135
        return wrapper