dataset.py 6.7 KB
Newer Older
S
Steffy-zxf 已提交
1
#coding:utf-8
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.

16 17 18 19
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

K
kinghuin 已提交
20 21 22 23 24 25
import os

import paddlehub as hub
from paddlehub.common.downloader import default_downloader
from paddlehub.common.logger import logger

26

27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
class InputExample(object):
    """
    Input data structure of BERT/ERNIE, can satisfy single sequence task like
    text classification, sequence lableing; Sequence pair task like dialog
    task.
    """

    def __init__(self, guid, text_a, text_b=None, label=None):
        """Constructs a InputExample.
    Args:
      guid: Unique id for the example.
      text_a: string. The untokenized text of the first sequence. For single
        sequence tasks, only this sequence must be specified.
      text_b: (Optional) string. The untokenized text of the second sequence.
        Only must be specified for sequence pair tasks.
      label: (Optional) string. The label of the example. This should be
        specified for train and dev examples, but not for test examples.
    """
        self.guid = guid
        self.text_a = text_a
        self.text_b = text_b
        self.label = label

Z
Zeyu Chen 已提交
50 51 52 53
    def __str__(self):
        if self.text_b is None:
            return "text={}\tlabel={}".format(self.text_a, self.label)
        else:
K
kinghuin 已提交
54
            return "text_a={}\ttext_b={},label={}".format(
W
wuzewu 已提交
55
                self.text_a, self.text_b, self.label)
Z
Zeyu Chen 已提交
56

57

K
kinghuin 已提交
58 59 60 61 62 63 64 65 66
class BaseDataset(object):
    def __init__(self,
                 base_path,
                 train_file=None,
                 dev_file=None,
                 test_file=None,
                 predict_file=None,
                 label_file=None,
                 label_list=None,
K
kinghuin 已提交
67 68 69 70
                 train_file_with_header=False,
                 dev_file_with_header=False,
                 test_file_with_header=False,
                 predict_file_with_header=False):
K
kinghuin 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
        if not (train_file or dev_file or test_file):
            raise ValueError("At least one file should be assigned")
        self.base_path = base_path
        self.train_file = train_file
        self.dev_file = dev_file
        self.test_file = test_file
        self.predict_file = predict_file
        self.label_file = label_file
        self.label_list = label_list

        self.train_examples = []
        self.dev_examples = []
        self.test_examples = []
        self.predict_examples = []

K
kinghuin 已提交
86 87 88 89 90
        self.if_file_with_header = {
            "train": train_file_with_header,
            "dev": dev_file_with_header,
            "test": test_file_with_header,
            "predict": predict_file_with_header
K
kinghuin 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        }

        if train_file:
            self._load_train_examples()
        if dev_file:
            self._load_dev_examples()
        if test_file:
            self._load_test_examples()
        if predict_file:
            self._load_predict_examples()
        if self.label_file:
            if not self.label_list:
                self.label_list = self._load_label_data()
            else:
                logger.warning(
                    "As label_list has been assigned, label_file is noneffective"
                )

K
kinghuin 已提交
109 110 111
        if self.label_list:
            self.label_index = dict(
                zip(self.label_list, range(len(self.label_list))))
K
kinghuin 已提交
112

113
    def get_train_examples(self):
K
kinghuin 已提交
114
        return self.train_examples
115 116

    def get_dev_examples(self):
K
kinghuin 已提交
117
        return self.dev_examples
118 119

    def get_test_examples(self):
K
kinghuin 已提交
120
        return self.test_examples
121 122 123 124

    def get_val_examples(self):
        return self.get_dev_examples()

K
kinghuin 已提交
125 126 127
    def get_predict_examples(self):
        return self.predict_examples

K
kinghuin 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141
    def get_examples(self, phase):
        if phase == "train":
            return self.get_train_examples()
        elif phase == "dev":
            return self.get_dev_examples()
        elif phase == "test":
            return self.get_test_examples()
        elif phase == "val":
            return self.get_val_examples()
        elif phase == "predict":
            return self.get_predict_examples()
        else:
            raise ValueError("Invalid phase: %s" % phase)

142
    def get_labels(self):
K
kinghuin 已提交
143
        return self.label_list
Z
Zeyu Chen 已提交
144

K
kinghuin 已提交
145
    @property
Z
Zeyu Chen 已提交
146
    def num_labels(self):
K
kinghuin 已提交
147 148
        return len(self.label_list)

K
kinghuin 已提交
149
    # To be compatible with ImageClassificationDataset
K
kinghuin 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
    def label_dict(self):
        return {index: key for index, key in enumerate(self.label_list)}

    def _download_dataset(self, dataset_path, url):
        if not os.path.exists(dataset_path):
            result, tips, dataset_path = default_downloader.download_file_and_uncompress(
                url=url,
                save_path=hub.common.dir.DATA_HOME,
                print_progress=True,
                replace=True)
            if not result:
                raise Exception(tips)
        else:
            logger.info("Dataset {} already cached.".format(dataset_path))
        return dataset_path

    def _load_train_examples(self):
        self.train_path = os.path.join(self.base_path, self.train_file)
        self.train_examples = self._read_file(self.train_path, phase="train")

    def _load_dev_examples(self):
        self.dev_path = os.path.join(self.base_path, self.dev_file)
        self.dev_examples = self._read_file(self.dev_path, phase="dev")

    def _load_test_examples(self):
        self.test_path = os.path.join(self.base_path, self.test_file)
        self.test_examples = self._read_file(self.test_path, phase="test")

    def _load_predict_examples(self):
        self.predict_path = os.path.join(self.base_path, self.predict_file)
        self.predict_examples = self._read_file(
            self.predict_path, phase="predict")

    def _read_file(self, path, phase=None):
        raise NotImplementedError

    def _load_label_data(self):
K
kinghuin 已提交
187 188 189
        with open(
                os.path.join(self.base_path, self.label_file), "r",
                encoding="utf8") as file:
K
kinghuin 已提交
190
            return file.read().strip().split("\n")
K
kinghuin 已提交
191 192 193 194 195 196 197 198 199

    def __str__(self):
        return "Dataset: %s with %i train examples, %i dev examples and %i test examples" % (
            self.__class__.__name__, len(self.train_examples),
            len(self.dev_examples), len(self.test_examples))


# add alias, compatible with old version
HubDataset = BaseDataset