base_nlp_dataset.py 20.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2020 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.
import csv
import io
import os
17
from typing import Dict, List, Optional, Union, Tuple
18 19

import numpy as np
20
import paddle
21 22
import paddlenlp
from packaging.version import Version
23 24

from paddlehub.env import DATA_HOME
K
KP 已提交
25 26
from paddlenlp.transformers import PretrainedTokenizer
from paddlenlp.data import JiebaTokenizer
27
from paddlehub.utils.log import logger
K
KP 已提交
28
from paddlehub.utils.utils import download, reseg_token_label, pad_sequence, trunc_sequence
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
from paddlehub.utils.xarfile import is_xarfile, unarchive


class InputExample(object):
    """
    The input data structure of Transformer modules (BERT, ERNIE and so on).
    """

    def __init__(self, guid: int, text_a: str, text_b: Optional[str] = None, label: Optional[str] = None):
        """
        The input data structure.
        Args:
          guid (:obj:`int`):
              Unique id for the input data.
          text_a (:obj:`str`, `optional`, defaults to :obj:`None`):
              The first sequence. For single sequence tasks, only this sequence must be specified.
          text_b (:obj:`str`, `optional`, defaults to :obj:`None`):
              The second sequence if sentence-pair.
          label (:obj:`str`, `optional`, defaults to :obj:`None`):
              The label of the example.
        Examples:
            .. code-block:: python
                from paddlehub.datasets.base_nlp_dataset import InputExample
                example = InputExample(guid=0,
                                text_a='15.4寸笔记本的键盘确实爽,基本跟台式机差不多了',
                                text_b='蛮喜欢数字小键盘,输数字特方便,样子也很美观,做工也相当不错',
                                label='1')
        """
        self.guid = guid
        self.text_a = text_a
        self.text_b = text_b
        self.label = label

    def __str__(self):
        if self.text_b is None:
            return "text={}\tlabel={}".format(self.text_a, self.label)
        else:
            return "text_a={}\ttext_b={},label={}".format(self.text_a, self.text_b, self.label)


class BaseNLPDataset(object):
    """
    The virtual base class for nlp datasets, such TextClassificationDataset, SeqLabelingDataset, and so on.
    The base class must be supered and re-implemented the method _read_file.
    """

    def __init__(self,
                 base_path: str,
K
KP 已提交
77
                 tokenizer: Union[PretrainedTokenizer, JiebaTokenizer],
78 79 80 81 82 83 84 85
                 max_seq_len: Optional[int] = 128,
                 mode: Optional[str] = "train",
                 data_file: Optional[str] = None,
                 label_file: Optional[str] = None,
                 label_list: Optional[List[str]] = None):
        """
        Ags:
            base_path (:obj:`str`): The directory to the whole dataset.
K
KP 已提交
86
            tokenizer (:obj:`PretrainedTokenizer` or :obj:`JiebaTokenizer`):
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
                It tokenizes the text and encodes the data as model needed.
            max_seq_len (:obj:`int`, `optional`, defaults to :128):
                If set to a number, will limit the total sequence returned so that it has a maximum length.
            mode (:obj:`str`, `optional`, defaults to `train`):
                It identifies the dataset mode (train, test or dev).
            data_file(:obj:`str`, `optional`, defaults to :obj:`None`):
                The data file name, which is relative to the base_path.
            label_file(:obj:`str`, `optional`, defaults to :obj:`None`):
                The label file name, which is relative to the base_path.
                It is all labels of the dataset, one line one label.
            label_list(:obj:`List[str]`, `optional`, defaults to :obj:`None`):
                The list of all labels of the dataset
        """
        self.data_file = os.path.join(base_path, data_file)
        self.label_list = label_list

        self.mode = mode
        self.tokenizer = tokenizer
        self.max_seq_len = max_seq_len

        if label_file:
            self.label_file = os.path.join(base_path, 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")
        if self.label_list:
            self.label_map = {item: index for index, item in enumerate(self.label_list)}

    def _load_label_data(self):
        """
        Loads labels from label file.
        """
        if os.path.exists(self.label_file):
            with open(self.label_file, "r", encoding="utf8") as f:
                return f.read().strip().split("\n")
        else:
            raise RuntimeError("The file {} is not found.".format(self.label_file))

    def _download_and_uncompress_dataset(self, destination: str, url: str):
        """
        Downloads dataset and uncompresses it.
        Args:
           destination (:obj:`str`): The dataset cached directory.
           url (:obj: str): The link to be downloaded a dataset.
        """
        if not os.path.exists(destination):
            dataset_package = download(url=url, path=DATA_HOME)
            if is_xarfile(dataset_package):
                unarchive(dataset_package, DATA_HOME)
        else:
            logger.info("Dataset {} already cached.".format(destination))

    def _read_file(self, input_file: str, is_file_with_header: bool = False):
        """
        Reads the files.
        Args:
            input_file (:obj:str) : The file to be read.
            is_file_with_header(:obj:bool, `optional`, default to :obj: False) :
                Whether or not the file is with the header introduction.
        """
        raise NotImplementedError

    def get_labels(self):
        """
        Gets all labels.
        """
        return self.label_list


157
class TextClassificationDataset(BaseNLPDataset, paddle.io.Dataset):
158 159 160 161 162 163
    """
    The dataset class which is fit for all datatset of text classification.
    """

    def __init__(self,
                 base_path: str,
K
KP 已提交
164
                 tokenizer: Union[PretrainedTokenizer, JiebaTokenizer],
165 166 167 168 169 170 171 172 173
                 max_seq_len: int = 128,
                 mode: str = "train",
                 data_file: str = None,
                 label_file: str = None,
                 label_list: list = None,
                 is_file_with_header: bool = False):
        """
        Ags:
            base_path (:obj:`str`): The directory to the whole dataset.
K
KP 已提交
174
            tokenizer (:obj:`PretrainedTokenizer` or :obj:`JiebaTokenizer`):
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
                It tokenizes the text and encodes the data as model needed.
            max_seq_len (:obj:`int`, `optional`, defaults to :128):
                If set to a number, will limit the total sequence returned so that it has a maximum length.
            mode (:obj:`str`, `optional`, defaults to `train`):
                It identifies the dataset mode (train, test or dev).
            data_file(:obj:`str`, `optional`, defaults to :obj:`None`):
                The data file name, which is relative to the base_path.
            label_file(:obj:`str`, `optional`, defaults to :obj:`None`):
                The label file name, which is relative to the base_path.
                It is all labels of the dataset, one line one label.
            label_list(:obj:`List[str]`, `optional`, defaults to :obj:`None`):
                The list of all labels of the dataset
            is_file_with_header(:obj:bool, `optional`, default to :obj: False) :
                Whether or not the file is with the header introduction.
        """
        super(TextClassificationDataset, self).__init__(
            base_path=base_path,
            tokenizer=tokenizer,
            max_seq_len=max_seq_len,
            mode=mode,
            data_file=data_file,
            label_file=label_file,
            label_list=label_list)
        self.examples = self._read_file(self.data_file, is_file_with_header)

        self.records = self._convert_examples_to_records(self.examples)

    def _read_file(self, input_file, is_file_with_header: bool = False) -> List[InputExample]:
        """
        Reads a tab separated value file.
        Args:
            input_file (:obj:str) : The file to be read.
            is_file_with_header(:obj:bool, `optional`, default to :obj: False) :
                Whether or not the file is with the header introduction.
        Returns:
            examples (:obj:`List[InputExample]`): All the input data.
        """
        if not os.path.exists(input_file):
            raise RuntimeError("The file {} is not found.".format(input_file))
        else:
            with io.open(input_file, "r", encoding="UTF-8") as f:
                reader = csv.reader(f, delimiter="\t", quotechar=None)
                examples = []
                seq_id = 0
                header = next(reader) if is_file_with_header else None
                for line in reader:
                    example = InputExample(guid=seq_id, label=line[0], text_a=line[1])
                    seq_id += 1
                    examples.append(example)
                return examples

    def _convert_examples_to_records(self, examples: List[InputExample]) -> List[dict]:
        """
        Converts all examples to records which the model needs.
        Args:
            examples(obj:`List[InputExample]`): All data examples returned by _read_file.
        Returns:
            records(:obj:`List[dict]`): All records which the model needs.
        """
        records = []
        for example in examples:
K
KP 已提交
236
            if isinstance(self.tokenizer, PretrainedTokenizer):
237 238 239 240 241 242 243 244 245 246
                if Version(paddlenlp.__version__) <= Version('2.0.0rc2'):
                    record = self.tokenizer.encode(
                        text=example.text_a, text_pair=example.text_b, max_seq_len=self.max_seq_len)
                else:
                    record = self.tokenizer(
                        text=example.text_a,
                        text_pair=example.text_b,
                        max_seq_len=self.max_seq_len,
                        pad_to_max_seq_len=True,
                        return_length=True)
K
KP 已提交
247 248 249 250 251 252 253 254 255 256 257 258
            elif isinstance(self.tokenizer, JiebaTokenizer):
                pad_token = self.tokenizer.vocab.pad_token

                ids = self.tokenizer.encode(sentence=example.text_a)
                seq_len = min(len(ids), self.max_seq_len)
                if len(ids) > self.max_seq_len:
                    ids = trunc_sequence(ids, self.max_seq_len)
                else:
                    pad_token_id = self.tokenizer.vocab.to_indices(pad_token)
                    ids = pad_sequence(ids, self.max_seq_len, pad_token_id)
                record = {'text': ids, 'seq_len': seq_len}
            else:
259 260 261
                raise RuntimeError(
                    "Unknown type of self.tokenizer: {}, it must be an instance of  PretrainedTokenizer or JiebaTokenizer"
                    .format(type(self.tokenizer)))
K
KP 已提交
262

263 264 265 266 267 268 269 270 271 272 273
            if not record:
                logger.info(
                    "The text %s has been dropped as it has no words in the vocab after tokenization." % example.text_a)
                continue
            if example.label:
                record['label'] = self.label_map[example.label]
            records.append(record)
        return records

    def __getitem__(self, idx):
        record = self.records[idx]
K
KP 已提交
274
        if isinstance(self.tokenizer, PretrainedTokenizer):
275 276 277 278
            input_ids = np.array(record['input_ids'])
            if Version(paddlenlp.__version__) >= Version('2.0.0rc5'):
                token_type_ids = np.array(record['token_type_ids'])
            else:
S
Steffy-zxf 已提交
279
                token_type_ids = np.array(record['segment_ids'])
280

K
KP 已提交
281
            if 'label' in record.keys():
282
                return input_ids, token_type_ids, np.array(record['label'], dtype=np.int64)
K
KP 已提交
283
            else:
284 285
                return input_ids, token_type_ids

K
KP 已提交
286 287 288 289 290
        elif isinstance(self.tokenizer, JiebaTokenizer):
            if 'label' in record.keys():
                return np.array(record['text']), np.array(record['label'], dtype=np.int64)
            else:
                return np.array(record['text'])
291
        else:
292 293 294
            raise RuntimeError(
                "Unknown type of self.tokenizer: {}, it must be an instance of  PretrainedTokenizer or JiebaTokenizer".
                format(type(self.tokenizer)))
295 296 297

    def __len__(self):
        return len(self.records)
298 299 300


class SeqLabelingDataset(BaseNLPDataset, paddle.io.Dataset):
K
KP 已提交
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    """
    Ags:
        base_path (:obj:`str`): The directory to the whole dataset.
        tokenizer (:obj:`PretrainedTokenizer` or :obj:`JiebaTokenizer`):
            It tokenizes the text and encodes the data as model needed.
        max_seq_len (:obj:`int`, `optional`, defaults to :128):
            If set to a number, will limit the total sequence returned so that it has a maximum length.
        mode (:obj:`str`, `optional`, defaults to `train`):
            It identifies the dataset mode (train, test or dev).
        data_file(:obj:`str`, `optional`, defaults to :obj:`None`):
            The data file name, which is relative to the base_path.
        label_file(:obj:`str`, `optional`, defaults to :obj:`None`):
            The label file name, which is relative to the base_path.
            It is all labels of the dataset, one line one label.
        label_list(:obj:`List[str]`, `optional`, defaults to :obj:`None`):
            The list of all labels of the dataset
        split_char(:obj:`str`, `optional`, defaults to :obj:`\002`):
            The symbol used to split chars in text and labels
        no_entity_label(:obj:`str`, `optional`, defaults to :obj:`O`):
            The label used to mark no entities
        ignore_label(:obj:`int`, `optional`, defaults to :-100):
            If one token's label == ignore_label, it will be ignored when
            calculating loss
        is_file_with_header(:obj:bool, `optional`, default to :obj: False) :
            Whether or not the file is with the header introduction.
    """
327

328 329
    def __init__(self,
                 base_path: str,
K
KP 已提交
330
                 tokenizer: Union[PretrainedTokenizer, JiebaTokenizer],
331 332 333 334 335
                 max_seq_len: int = 128,
                 mode: str = "train",
                 data_file: str = None,
                 label_file: str = None,
                 label_list: list = None,
336
                 split_char: str = "\002",
K
KP 已提交
337 338
                 no_entity_label: str = "O",
                 ignore_label: int = -100,
339 340 341 342 343 344 345 346 347 348 349 350
                 is_file_with_header: bool = False):
        super(SeqLabelingDataset, self).__init__(
            base_path=base_path,
            tokenizer=tokenizer,
            max_seq_len=max_seq_len,
            mode=mode,
            data_file=data_file,
            label_file=label_file,
            label_list=label_list)

        self.no_entity_label = no_entity_label
        self.split_char = split_char
K
KP 已提交
351
        self.ignore_label = ignore_label
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

        self.examples = self._read_file(self.data_file, is_file_with_header)
        self.records = self._convert_examples_to_records(self.examples)

    def _read_file(self, input_file, is_file_with_header: bool = False) -> List[InputExample]:
        """Reads a tab separated value file."""
        if not os.path.exists(input_file):
            raise RuntimeError("The file {} is not found.".format(input_file))
        else:
            with io.open(input_file, "r", encoding="UTF-8") as f:
                reader = csv.reader(f, delimiter="\t", quotechar=None)
                examples = []
                seq_id = 0
                header = next(reader) if is_file_with_header else None
                for line in reader:
                    example = InputExample(guid=seq_id, label=line[1], text_a=line[0])
                    seq_id += 1
                    examples.append(example)
                return examples

    def _convert_examples_to_records(self, examples: List[InputExample]) -> List[dict]:
        """
        Returns a list[dict] including all the input information what the model need.
        Args:
            examples (list): the data examples, returned by _read_file.
        Returns:
            a list with all the examples record.
        """
        records = []
        for example in examples:
K
KP 已提交
382 383 384 385 386 387 388 389
            tokens = example.text_a.split(self.split_char)
            labels = example.label.split(self.split_char)

            # convert tokens into record
            if isinstance(self.tokenizer, PretrainedTokenizer):
                pad_token = self.tokenizer.pad_token

                tokens, labels = reseg_token_label(tokenizer=self.tokenizer, tokens=tokens, labels=labels)
390 391 392 393 394 395 396 397 398
                if Version(paddlenlp.__version__) <= Version('2.0.0rc2'):
                    record = self.tokenizer.encode(text=tokens, max_seq_len=self.max_seq_len)
                else:
                    record = self.tokenizer(
                        text=tokens,
                        max_seq_len=self.max_seq_len,
                        pad_to_max_seq_len=True,
                        is_split_into_words=True,
                        return_length=True)
K
KP 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411
            elif isinstance(self.tokenizer, JiebaTokenizer):
                pad_token = self.tokenizer.vocab.pad_token

                ids = [self.tokenizer.vocab.to_indices(token) for token in tokens]
                seq_len = min(len(ids), self.max_seq_len)
                if len(ids) > self.max_seq_len:
                    ids = trunc_sequence(ids, self.max_seq_len)
                else:
                    pad_token_id = self.tokenizer.vocab.to_indices(pad_token)
                    ids = pad_sequence(ids, self.max_seq_len, pad_token_id)

                record = {'text': ids, 'seq_len': seq_len}
            else:
412 413 414
                raise RuntimeError(
                    "Unknown type of self.tokenizer: {}, it must be an instance of  PretrainedTokenizer or JiebaTokenizer"
                    .format(type(self.tokenizer)))
K
KP 已提交
415

416 417
            if not record:
                logger.info(
418
                    "The text %s has been dropped as it has no words in the vocab after tokenization." % example.text_a)
419
                continue
K
KP 已提交
420 421

            # convert labels into record
422 423
            if labels:
                record["label"] = []
K
KP 已提交
424 425 426 427 428
                if isinstance(self.tokenizer, PretrainedTokenizer):
                    tokens_with_specical_token = self.tokenizer.convert_ids_to_tokens(record['input_ids'])
                elif isinstance(self.tokenizer, JiebaTokenizer):
                    tokens_with_specical_token = [self.tokenizer.vocab.to_tokens(id_) for id_ in record['text']]
                else:
429 430 431
                    raise RuntimeError(
                        "Unknown type of self.tokenizer: {}, it must be an instance of  PretrainedTokenizer or JiebaTokenizer"
                        .format(type(self.tokenizer)))
K
KP 已提交
432

433 434
                tokens_index = 0
                for token in tokens_with_specical_token:
435 436
                    if tokens_index < len(tokens) and token == tokens[tokens_index]:
                        record["label"].append(self.label_list.index(labels[tokens_index]))
437
                        tokens_index += 1
K
KP 已提交
438
                    elif token in [pad_token]:
K
KP 已提交
439
                        record["label"].append(self.ignore_label)  # label of special token
440
                    else:
441
                        record["label"].append(self.label_list.index(self.no_entity_label))
442 443 444 445 446
            records.append(record)
        return records

    def __getitem__(self, idx):
        record = self.records[idx]
K
KP 已提交
447
        if isinstance(self.tokenizer, PretrainedTokenizer):
448 449 450 451 452 453 454
            input_ids = np.array(record['input_ids'])
            seq_lens = np.array(record['seq_len'])
            if Version(paddlenlp.__version__) >= Version('2.0.0rc5'):
                token_type_ids = np.array(record['token_type_ids'])
            else:
                token_type_ids = np.array(record['segment_ids'])

K
KP 已提交
455
            if 'label' in record.keys():
456
                return input_ids, token_type_ids, seq_lens, np.array(record['label'], dtype=np.int64)
K
KP 已提交
457
            else:
458 459
                return input_ids, token_type_ids, seq_lens

K
KP 已提交
460 461 462 463 464
        elif isinstance(self.tokenizer, JiebaTokenizer):
            if 'label' in record.keys():
                return np.array(record['text']), np.array(record['seq_len']), np.array(record['label'], dtype=np.int64)
            else:
                return np.array(record['text']), np.array(record['seq_len'])
465
        else:
466 467 468
            raise RuntimeError(
                "Unknown type of self.tokenizer: {}, it must be an instance of  PretrainedTokenizer or JiebaTokenizer".
                format(type(self.tokenizer)))
469 470 471

    def __len__(self):
        return len(self.records)