nlp_reader.py 50.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
import collections
21
import numpy as np
S
Steffy-zxf 已提交
22
import six
Z
Zeyu Chen 已提交
23
from collections import namedtuple
24

25
import paddle.fluid as fluid
26

W
wuzewu 已提交
27
from paddlehub.reader import tokenization
28
from paddlehub.common.logger import logger
W
wuzewu 已提交
29
from paddlehub.common.utils import sys_stdout_encoding
30
from paddlehub.dataset.dataset import InputExample
K
kinghuin 已提交
31
from .batching import pad_batch_data
W
wuzewu 已提交
32
import paddlehub as hub
K
kinghuin 已提交
33
from .base_reader import BaseReader
34 35


K
kinghuin 已提交
36
class BaseNLPReader(BaseReader):
37 38
    def __init__(self,
                 vocab_path,
S
Steffy-zxf 已提交
39
                 dataset=None,
Z
Zeyu Chen 已提交
40 41
                 label_map_config=None,
                 max_seq_len=512,
42
                 do_lower_case=True,
43
                 random_seed=None,
K
kinghuin 已提交
44
                 use_task_id=False,
K
kinghuin 已提交
45 46
                 sp_model_path=None,
                 word_dict_path=None,
K
kinghuin 已提交
47
                 in_tokens=False):
K
kinghuin 已提交
48
        super(BaseNLPReader, self).__init__(dataset, random_seed)
49
        self.max_seq_len = max_seq_len
K
kinghuin 已提交
50
        if sp_model_path and word_dict_path:
K
kinghuin 已提交
51
            self.tokenizer = tokenization.WSSPTokenizer(
K
kinghuin 已提交
52 53 54 55
                vocab_path, sp_model_path, word_dict_path, ws=True, lower=True)
        else:
            self.tokenizer = tokenization.FullTokenizer(
                vocab_file=vocab_path, do_lower_case=do_lower_case)
56
        self.vocab = self.tokenizer.vocab
Z
Zeyu Chen 已提交
57 58 59
        self.pad_id = self.vocab["[PAD]"]
        self.cls_id = self.vocab["[CLS]"]
        self.sep_id = self.vocab["[SEP]"]
K
kinghuin 已提交
60
        self.mask_id = self.vocab["[MASK]"]
K
kinghuin 已提交
61
        self.in_tokens = in_tokens
62 63 64
        self.use_task_id = use_task_id

        if self.use_task_id:
K
kinghuin 已提交
65
            logger.warning(
K
kinghuin 已提交
66 67
                "use_task_id has been de discarded since PaddleHub v1.4.0, it's no necessary to feed task_ids now."
            )
68
            self.task_id = 0
69

K
kinghuin 已提交
70 71 72 73 74
        self.Record_With_Label_Id = namedtuple(
            'Record',
            ['token_ids', 'text_type_ids', 'position_ids', 'label_id'])
        self.Record_Wo_Label_Id = namedtuple(
            'Record', ['token_ids', 'text_type_ids', 'position_ids'])
Z
Zeyu Chen 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

    def _truncate_seq_pair(self, tokens_a, tokens_b, max_length):
        """Truncates a sequence pair in place to the maximum length."""

        # This is a simple heuristic which will always truncate the longer sequence
        # one token at a time. This makes more sense than truncating an equal percent
        # of tokens from each, since if one sequence is very short then each token
        # that's truncated likely contains more information than a longer sequence.
        while True:
            total_length = len(tokens_a) + len(tokens_b)
            if total_length <= max_length:
                break
            if len(tokens_a) > len(tokens_b):
                tokens_a.pop()
            else:
                tokens_b.pop()

92 93 94 95 96
    def _convert_example_to_record(self,
                                   example,
                                   max_seq_length,
                                   tokenizer,
                                   phase=None):
Z
Zeyu Chen 已提交
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
        """Converts a single `Example` into a single `Record`."""

        text_a = tokenization.convert_to_unicode(example.text_a)
        tokens_a = tokenizer.tokenize(text_a)
        tokens_b = None
        if example.text_b is not None:
            #if "text_b" in example._fields:
            text_b = tokenization.convert_to_unicode(example.text_b)
            tokens_b = tokenizer.tokenize(text_b)

        if tokens_b:
            # Modifies `tokens_a` and `tokens_b` in place so that the total
            # length is less than the specified length.
            # Account for [CLS], [SEP], [SEP] with "- 3"
            self._truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
        else:
            # Account for [CLS] and [SEP] with "- 2"
            if len(tokens_a) > max_seq_length - 2:
                tokens_a = tokens_a[0:(max_seq_length - 2)]

        # The convention in BERT/ERNIE is:
        # (a) For sequence pairs:
        #  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
        #  type_ids: 0     0  0    0    0     0       0 0     1  1  1  1   1 1
        # (b) For single sequences:
        #  tokens:   [CLS] the dog is hairy . [SEP]
        #  type_ids: 0     0   0   0  0     0 0
        #
        # Where "type_ids" are used to indicate whether this is the first
        # sequence or the second sequence. The embedding vectors for `type=0` and
        # `type=1` were learned during pre-training and are added to the wordpiece
        # embedding vector (and position vector). This is not *strictly* necessary
        # since the [SEP] token unambiguously separates the sequences, but it makes
        # it easier for the model to learn the concept of sequences.
        #
        # For classification tasks, the first vector (corresponding to [CLS]) is
        # used as as the "sentence vector". Note that this only makes sense because
        # the entire model is fine-tuned.
        tokens = []
        text_type_ids = []
        tokens.append("[CLS]")
        text_type_ids.append(0)
        for token in tokens_a:
            tokens.append(token)
            text_type_ids.append(0)
        tokens.append("[SEP]")
        text_type_ids.append(0)
144

Z
Zeyu Chen 已提交
145 146 147 148 149 150 151 152 153 154 155
        if tokens_b:
            for token in tokens_b:
                tokens.append(token)
                text_type_ids.append(1)
            tokens.append("[SEP]")
            text_type_ids.append(1)

        token_ids = tokenizer.convert_tokens_to_ids(tokens)
        position_ids = list(range(len(token_ids)))

        if self.label_map:
156 157 158
            if example.label not in self.label_map:
                raise KeyError(
                    "example.label = {%s} not in label" % example.label)
Z
Zeyu Chen 已提交
159 160 161 162
            label_id = self.label_map[example.label]
        else:
            label_id = example.label

163
        if phase != "predict":
K
kinghuin 已提交
164
            record = self.Record_With_Label_Id(
165 166 167 168 169
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids,
                label_id=label_id)
        else:
K
kinghuin 已提交
170
            record = self.Record_Wo_Label_Id(
171 172 173 174
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids)

Z
Zeyu Chen 已提交
175 176
        return record

K
kinghuin 已提交
177 178 179
    def _pad_batch_records(self, batch_records, phase):
        raise NotImplementedError

Z
Zeyu Chen 已提交
180 181 182 183 184 185 186
    def _prepare_batch_data(self, examples, batch_size, phase=None):
        """generate batch records"""
        batch_records, max_len = [], 0
        for index, example in enumerate(examples):
            if phase == "train":
                self.current_example = index
            record = self._convert_example_to_record(example, self.max_seq_len,
187
                                                     self.tokenizer, phase)
Z
Zeyu Chen 已提交
188 189 190 191 192 193 194 195
            max_len = max(max_len, len(record.token_ids))
            if self.in_tokens:
                to_append = (len(batch_records) + 1) * max_len <= batch_size
            else:
                to_append = len(batch_records) < batch_size
            if to_append:
                batch_records.append(record)
            else:
196
                yield self._pad_batch_records(batch_records, phase)
Z
Zeyu Chen 已提交
197 198 199
                batch_records, max_len = [record], len(record.token_ids)

        if batch_records:
200
            yield self._pad_batch_records(batch_records, phase)
Z
Zeyu Chen 已提交
201

202 203 204 205
    def data_generator(self,
                       batch_size=1,
                       phase='train',
                       shuffle=True,
206 207
                       data=None,
                       return_list=True):
S
Steffy-zxf 已提交
208 209
        if phase != 'predict' and not self.dataset:
            raise ValueError("The dataset is None ! It isn't allowed.")
210
        if phase == 'train':
211
            shuffle = True
212 213 214
            examples = self.get_train_examples()
            self.num_examples['train'] = len(examples)
        elif phase == 'val' or phase == 'dev':
215
            shuffle = False
216 217 218
            examples = self.get_dev_examples()
            self.num_examples['dev'] = len(examples)
        elif phase == 'test':
219
            shuffle = False
220 221
            examples = self.get_test_examples()
            self.num_examples['test'] = len(examples)
222 223 224 225 226 227 228
        elif phase == 'predict':
            shuffle = False
            examples = []
            seq_id = 0

            for item in data:
                # set label in order to run the program
S
Steffy-zxf 已提交
229 230 231 232
                if self.dataset:
                    label = list(self.label_map.keys())[0]
                else:
                    label = 0
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
                if len(item) == 1:
                    item_i = InputExample(
                        guid=seq_id, text_a=item[0], label=label)
                elif len(item) == 2:
                    item_i = InputExample(
                        guid=seq_id,
                        text_a=item[0],
                        text_b=item[1],
                        label=label)
                else:
                    raise ValueError(
                        "The length of input_text is out of handling, which must be 1 or 2!"
                    )
                examples.append(item_i)
                seq_id += 1
248 249
        else:
            raise ValueError(
250 251
                "Unknown phase, which should be in ['train', 'dev', 'test', 'predict']."
            )
252

Z
Zeyu Chen 已提交
253
        def wrapper():
254 255 256
            if shuffle:
                np.random.shuffle(examples)

Z
Zeyu Chen 已提交
257 258
            for batch_data in self._prepare_batch_data(
                    examples, batch_size, phase=phase):
259 260 261 262 263 264
                if return_list:
                    # for DataFeeder
                    yield [batch_data]
                else:
                    # for DataLoader
                    yield batch_data
265 266 267 268

        return wrapper


K
kinghuin 已提交
269
class ClassifyReader(BaseNLPReader):
270
    def _pad_batch_records(self, batch_records, phase=None):
Z
Zeyu Chen 已提交
271 272 273
        batch_token_ids = [record.token_ids for record in batch_records]
        batch_text_type_ids = [record.text_type_ids for record in batch_records]
        batch_position_ids = [record.position_ids for record in batch_records]
274

Z
Zeyu Chen 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287
        padded_token_ids, input_mask = pad_batch_data(
            batch_token_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id,
            return_input_mask=True)
        padded_text_type_ids = pad_batch_data(
            batch_text_type_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id)
        padded_position_ids = pad_batch_data(
            batch_position_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id)
288

289 290 291 292 293 294 295 296 297
        if phase != "predict":
            batch_labels = [record.label_id for record in batch_records]
            batch_labels = np.array(batch_labels).astype("int64").reshape(
                [-1, 1])

            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask, batch_labels
            ]
298 299 300 301 302 303 304 305

            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids, batch_labels
                ]
306 307 308 309 310
        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask
            ]
311

312
            if self.use_task_id:
313 314
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
315 316 317 318
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids
                ]
Z
Zeyu Chen 已提交
319
        return return_list
320 321


K
kinghuin 已提交
322
class SequenceLabelReader(BaseNLPReader):
K
kinghuin 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    def __init__(self,
                 vocab_path,
                 dataset=None,
                 label_map_config=None,
                 max_seq_len=512,
                 do_lower_case=True,
                 random_seed=None,
                 use_task_id=False,
                 sp_model_path=None,
                 word_dict_path=None,
                 in_tokens=False):
        super(SequenceLabelReader, self).__init__(
            vocab_path=vocab_path,
            dataset=dataset,
            label_map_config=label_map_config,
            max_seq_len=max_seq_len,
            do_lower_case=do_lower_case,
            random_seed=random_seed,
            use_task_id=use_task_id,
            sp_model_path=sp_model_path,
            word_dict_path=word_dict_path,
            in_tokens=in_tokens)
        if sp_model_path and word_dict_path:
            self.tokenizer = tokenization.FullTokenizer(
                vocab_file=vocab_path,
                do_lower_case=do_lower_case,
                use_sentence_piece_vocab=True)

351
    def _pad_batch_records(self, batch_records, phase=None):
Z
Zeyu Chen 已提交
352 353 354
        batch_token_ids = [record.token_ids for record in batch_records]
        batch_text_type_ids = [record.text_type_ids for record in batch_records]
        batch_position_ids = [record.position_ids for record in batch_records]
355

Z
Zeyu Chen 已提交
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
        # padding
        padded_token_ids, input_mask, batch_seq_lens = pad_batch_data(
            batch_token_ids,
            pad_idx=self.pad_id,
            max_seq_len=self.max_seq_len,
            return_input_mask=True,
            return_seq_lens=True)
        padded_text_type_ids = pad_batch_data(
            batch_text_type_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id)
        padded_position_ids = pad_batch_data(
            batch_position_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id)
371

372
        if phase != "predict":
K
kinghuin 已提交
373
            batch_label_ids = [record.label_id for record in batch_records]
374 375 376 377 378 379 380 381 382
            padded_label_ids = pad_batch_data(
                batch_label_ids,
                max_seq_len=self.max_seq_len,
                pad_idx=len(self.label_map) - 1)

            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask, padded_label_ids, batch_seq_lens
            ]
383 384 385 386 387 388 389 390 391 392

            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids, padded_label_ids,
                    batch_seq_lens
                ]

393 394 395 396 397
        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask, batch_seq_lens
            ]
398 399 400 401 402 403 404 405 406

            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids, batch_seq_lens
                ]

Z
Zeyu Chen 已提交
407 408
        return return_list

409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    def _reseg_token_label(self, tokens, tokenizer, phase, labels=None):
        if phase != "predict":
            if len(tokens) != len(labels):
                raise ValueError(
                    "The length of tokens must be same with labels")
            ret_tokens = []
            ret_labels = []
            for token, label in zip(tokens, labels):
                sub_token = tokenizer.tokenize(token)
                if len(sub_token) == 0:
                    continue
                ret_tokens.extend(sub_token)
                ret_labels.append(label)
                if len(sub_token) < 2:
                    continue
                sub_label = label
                if label.startswith("B-"):
                    sub_label = "I-" + label[2:]
                ret_labels.extend([sub_label] * (len(sub_token) - 1))

A
Austendeng 已提交
429
            if len(ret_tokens) != len(ret_labels):
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
                raise ValueError(
                    "The length of ret_tokens can't match with labels")
            return ret_tokens, ret_labels
        else:
            ret_tokens = []
            for token in tokens:
                sub_token = tokenizer.tokenize(token)
                if len(sub_token) == 0:
                    continue
                ret_tokens.extend(sub_token)
                if len(sub_token) < 2:
                    continue

            return ret_tokens

    def _convert_example_to_record(self,
                                   example,
                                   max_seq_length,
                                   tokenizer,
                                   phase=None):
Z
Zeyu Chen 已提交
450

451
        tokens = tokenization.convert_to_unicode(example.text_a).split(u"")
Z
Zeyu Chen 已提交
452

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        if phase != "predict":
            labels = tokenization.convert_to_unicode(example.label).split(u"")
            tokens, labels = self._reseg_token_label(
                tokens=tokens, labels=labels, tokenizer=tokenizer, phase=phase)

            if len(tokens) > max_seq_length - 2:
                tokens = tokens[0:(max_seq_length - 2)]
                labels = labels[0:(max_seq_length - 2)]

            tokens = ["[CLS]"] + tokens + ["[SEP]"]
            token_ids = tokenizer.convert_tokens_to_ids(tokens)
            position_ids = list(range(len(token_ids)))
            text_type_ids = [0] * len(token_ids)
            no_entity_id = len(self.label_map) - 1
            label_ids = [no_entity_id
                         ] + [self.label_map[label]
                              for label in labels] + [no_entity_id]
K
kinghuin 已提交
470
            record = self.Record_With_Label_Id(
471 472 473
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids,
K
kinghuin 已提交
474
                label_id=label_ids)
475 476 477 478 479 480 481 482 483 484 485 486
        else:
            tokens = self._reseg_token_label(
                tokens=tokens, tokenizer=tokenizer, phase=phase)

            if len(tokens) > max_seq_length - 2:
                tokens = tokens[0:(max_seq_length - 2)]

            tokens = ["[CLS]"] + tokens + ["[SEP]"]
            token_ids = tokenizer.convert_tokens_to_ids(tokens)
            position_ids = list(range(len(token_ids)))
            text_type_ids = [0] * len(token_ids)

K
kinghuin 已提交
487
            record = self.Record_Wo_Label_Id(
488 489 490 491
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids,
            )
Z
Zeyu Chen 已提交
492 493 494 495

        return record


K
kinghuin 已提交
496
class MultiLabelClassifyReader(BaseNLPReader):
S
Steffy-zxf 已提交
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    def _pad_batch_records(self, batch_records, phase=None):
        batch_token_ids = [record.token_ids for record in batch_records]
        batch_text_type_ids = [record.text_type_ids for record in batch_records]
        batch_position_ids = [record.position_ids for record in batch_records]

        # padding
        padded_token_ids, input_mask = pad_batch_data(
            batch_token_ids,
            pad_idx=self.pad_id,
            max_seq_len=self.max_seq_len,
            return_input_mask=True)
        padded_text_type_ids = pad_batch_data(
            batch_text_type_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id)
        padded_position_ids = pad_batch_data(
            batch_position_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id)

        if phase != "predict":
K
kinghuin 已提交
518
            batch_labels_ids = [record.label_id for record in batch_records]
S
Steffy-zxf 已提交
519 520 521 522 523 524 525 526
            num_label = len(self.dataset.get_labels())
            batch_labels = np.array(batch_labels_ids).astype("int64").reshape(
                [-1, num_label])

            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask, batch_labels
            ]
527 528 529 530 531 532 533 534

            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids, batch_labels
                ]
S
Steffy-zxf 已提交
535 536 537 538 539
        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask
            ]
540 541 542 543 544 545 546 547

            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids
                ]
S
Steffy-zxf 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595
        return return_list

    def _convert_example_to_record(self,
                                   example,
                                   max_seq_length,
                                   tokenizer,
                                   phase=None):
        """Converts a single `Example` into a single `Record`."""

        text_a = tokenization.convert_to_unicode(example.text_a)
        tokens_a = tokenizer.tokenize(text_a)
        tokens_b = None
        if example.text_b is not None:
            #if "text_b" in example._fields:
            text_b = tokenization.convert_to_unicode(example.text_b)
            tokens_b = tokenizer.tokenize(text_b)

        if tokens_b:
            # Modifies `tokens_a` and `tokens_b` in place so that the total
            # length is less than the specified length.
            # Account for [CLS], [SEP], [SEP] with "- 3"
            self._truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
        else:
            # Account for [CLS] and [SEP] with "- 2"
            if len(tokens_a) > max_seq_length - 2:
                tokens_a = tokens_a[0:(max_seq_length - 2)]

        tokens = []
        text_type_ids = []
        tokens.append("[CLS]")
        text_type_ids.append(0)
        for token in tokens_a:
            tokens.append(token)
            text_type_ids.append(0)
        tokens.append("[SEP]")
        text_type_ids.append(0)

        if tokens_b:
            for token in tokens_b:
                tokens.append(token)
                text_type_ids.append(1)
            tokens.append("[SEP]")
            text_type_ids.append(1)

        token_ids = tokenizer.convert_tokens_to_ids(tokens)
        position_ids = list(range(len(token_ids)))

        label_ids = []
596 597 598 599
        if phase == "predict":
            label_ids = [0, 0, 0, 0, 0, 0]
        else:
            for label in example.label:
Z
zhangxuefei 已提交
600
                label_ids.append(int(label))
S
Steffy-zxf 已提交
601 602

        if phase != "predict":
K
kinghuin 已提交
603
            record = self.Record_With_Label_Id(
S
Steffy-zxf 已提交
604 605 606
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids,
K
kinghuin 已提交
607
                label_id=label_ids)
S
Steffy-zxf 已提交
608
        else:
K
kinghuin 已提交
609
            record = self.Record_Wo_Label_Id(
S
Steffy-zxf 已提交
610 611 612 613 614 615 616
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids)

        return record


K
kinghuin 已提交
617
class RegressionReader(BaseNLPReader):
K
kinghuin 已提交
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
    def _pad_batch_records(self, batch_records, phase=None):
        batch_token_ids = [record.token_ids for record in batch_records]
        batch_text_type_ids = [record.text_type_ids for record in batch_records]
        batch_position_ids = [record.position_ids for record in batch_records]

        padded_token_ids, input_mask = pad_batch_data(
            batch_token_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id,
            return_input_mask=True)
        padded_text_type_ids = pad_batch_data(
            batch_text_type_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id)
        padded_position_ids = pad_batch_data(
            batch_position_ids,
            max_seq_len=self.max_seq_len,
            pad_idx=self.pad_id)

        if phase != "predict":
            batch_labels = [record.label_id for record in batch_records]
            # the only diff with ClassifyReader: astype("float32")
            batch_labels = np.array(batch_labels).astype("float32").reshape(
                [-1, 1])

            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask, batch_labels
            ]
K
kinghuin 已提交
647 648 649 650 651 652 653 654

            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids, batch_labels
                ]
K
kinghuin 已提交
655 656 657 658 659 660
        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask
            ]

K
kinghuin 已提交
661 662 663 664 665 666 667 668
            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids
                ]

K
kinghuin 已提交
669 670 671 672 673 674
        return return_list

    def data_generator(self,
                       batch_size=1,
                       phase='train',
                       shuffle=True,
675 676
                       data=None,
                       return_list=True):
S
Steffy-zxf 已提交
677 678
        if phase != 'predict' and not self.dataset:
            raise ValueError("The dataset is none and it's not allowed.")
K
kinghuin 已提交
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
        if phase == 'train':
            shuffle = True
            examples = self.get_train_examples()
            self.num_examples['train'] = len(examples)
        elif phase == 'val' or phase == 'dev':
            shuffle = False
            examples = self.get_dev_examples()
            self.num_examples['dev'] = len(examples)
        elif phase == 'test':
            shuffle = False
            examples = self.get_test_examples()
            self.num_examples['test'] = len(examples)
        elif phase == 'predict':
            shuffle = False
            examples = []
            seq_id = 0

            for item in data:
                # set label in order to run the program
K
kinghuin 已提交
698
                label = -1  # different from BaseNLPReader
K
kinghuin 已提交
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
                if len(item) == 1:
                    item_i = InputExample(
                        guid=seq_id, text_a=item[0], label=label)
                elif len(item) == 2:
                    item_i = InputExample(
                        guid=seq_id,
                        text_a=item[0],
                        text_b=item[1],
                        label=label)
                else:
                    raise ValueError(
                        "The length of input_text is out of handling, which must be 1 or 2!"
                    )
                examples.append(item_i)
                seq_id += 1
        else:
            raise ValueError(
                "Unknown phase, which should be in ['train', 'dev', 'test', 'predict']."
            )

        def wrapper():
            if shuffle:
                np.random.shuffle(examples)

            for batch_data in self._prepare_batch_data(
                    examples, batch_size, phase=phase):
725 726 727 728 729 730
                if return_list:
                    # for DataFeeder
                    yield [batch_data]
                else:
                    # for DataLoader
                    yield batch_data
K
kinghuin 已提交
731 732 733 734

        return wrapper


K
kinghuin 已提交
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
class Features(object):
    """A single set of features of squad_data."""

    def __init__(
            self,
            unique_id,
            example_index,
            doc_span_index,
            tokens,
            token_to_orig_map,
            token_is_max_context,
            token_ids,
            position_ids,
            text_type_ids,
            start_position=None,
            end_position=None,
            is_impossible=None,
    ):
        self.unique_id = unique_id
        self.example_index = example_index
        self.doc_span_index = doc_span_index
        self.tokens = tokens
        self.token_to_orig_map = token_to_orig_map
        self.token_is_max_context = token_is_max_context
        self.token_ids = token_ids
        self.position_ids = position_ids
        self.text_type_ids = text_type_ids
        self.start_position = start_position
        self.end_position = end_position
        self.is_impossible = is_impossible

    def __repr__(self):
        s = ""
        s += "unique_id: %s " % self.unique_id
        s += "example_index: %s " % self.example_index
        s += "start_position: %s " % self.start_position
        s += "end_position: %s " % self.end_position
        s += "is_impossible: %s " % self.is_impossible
        # s += "tokens: %s" % self.tokens
        # s += "token_to_orig_map %s" % self.token_to_orig_map
        return s


K
kinghuin 已提交
778
class ReadingComprehensionReader(BaseNLPReader):
K
kinghuin 已提交
779 780 781 782
    def __init__(self,
                 dataset,
                 vocab_path,
                 do_lower_case=True,
K
kinghuin 已提交
783
                 max_seq_len=512,
K
kinghuin 已提交
784 785
                 doc_stride=128,
                 max_query_length=64,
K
kinghuin 已提交
786
                 random_seed=None,
K
kinghuin 已提交
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
                 use_task_id=False,
                 sp_model_path=None,
                 word_dict_path=None,
                 in_tokens=False):
        super(ReadingComprehensionReader, self).__init__(
            vocab_path=vocab_path,
            dataset=dataset,
            label_map_config=None,
            max_seq_len=max_seq_len,
            do_lower_case=do_lower_case,
            random_seed=random_seed,
            use_task_id=use_task_id,
            sp_model_path=sp_model_path,
            word_dict_path=word_dict_path,
            in_tokens=in_tokens)

K
kinghuin 已提交
803 804
        self.doc_stride = doc_stride
        self.max_query_length = max_query_length
K
kinghuin 已提交
805
        self._DocSpan = collections.namedtuple("DocSpan", ["start", "length"])
K
kinghuin 已提交
806 807 808 809
        # self.all_examples[phase] and self.all_features[phase] will be used
        # in write_prediction in reading_comprehension_task
        self.all_features = {"train": [], "dev": [], "test": [], "predict": []}
        self.all_examples = {"train": [], "dev": [], "test": [], "predict": []}
K
kinghuin 已提交
810

K
kinghuin 已提交
811 812 813 814 815 816 817
    def _pad_batch_records(self, batch_records, phase):
        batch_token_ids = [record.token_ids for record in batch_records]
        batch_text_type_ids = [record.text_type_ids for record in batch_records]
        batch_position_ids = [record.position_ids for record in batch_records]
        batch_unique_ids = [record.unique_id for record in batch_records]
        batch_unique_ids = np.array(batch_unique_ids).astype("int64").reshape(
            [-1, 1])
K
kinghuin 已提交
818

K
kinghuin 已提交
819 820 821 822 823 824 825 826 827 828 829 830 831 832
        # padding
        padded_token_ids, input_mask = pad_batch_data(
            batch_token_ids,
            pad_idx=self.pad_id,
            return_input_mask=True,
            max_seq_len=self.max_seq_len)
        padded_text_type_ids = pad_batch_data(
            batch_text_type_ids,
            pad_idx=self.pad_id,
            max_seq_len=self.max_seq_len)
        padded_position_ids = pad_batch_data(
            batch_position_ids,
            pad_idx=self.pad_id,
            max_seq_len=self.max_seq_len)
K
kinghuin 已提交
833

K
kinghuin 已提交
834 835 836 837 838 839 840 841 842 843 844
        if phase != "predict":
            batch_start_position = [
                record.start_position for record in batch_records
            ]
            batch_end_position = [
                record.end_position for record in batch_records
            ]
            batch_start_position = np.array(batch_start_position).astype(
                "int64").reshape([-1, 1])
            batch_end_position = np.array(batch_end_position).astype(
                "int64").reshape([-1, 1])
K
kinghuin 已提交
845

K
kinghuin 已提交
846 847 848 849 850
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask, batch_unique_ids, batch_start_position,
                batch_end_position
            ]
K
kinghuin 已提交
851

K
kinghuin 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids, batch_unique_ids,
                    batch_start_position, batch_end_position
                ]

        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask, batch_unique_ids
            ]
            if self.use_task_id:
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids, batch_unique_ids
                ]
        return return_list

    def _prepare_batch_data(self, records, batch_size, phase=None):
        """generate batch records"""
        batch_records, max_len = [], 0
        for index, record in enumerate(records):
            if phase == "train":
                self.current_example = index
            max_len = max(max_len, len(record.token_ids))
            if self.in_tokens:
                to_append = (len(batch_records) + 1) * max_len <= batch_size
            else:
                to_append = len(batch_records) < batch_size
            if to_append:
                batch_records.append(record)
            else:
                yield self._pad_batch_records(batch_records, phase)
                batch_records, max_len = [record], len(record.token_ids)

        if batch_records:
            yield self._pad_batch_records(batch_records, phase)
K
kinghuin 已提交
894 895 896 897 898

    def data_generator(self,
                       batch_size=1,
                       phase='train',
                       shuffle=False,
899 900
                       data=None,
                       return_list=True):
K
kinghuin 已提交
901 902 903 904 905
        # we need all_examples and  all_features in write_prediction in reading_comprehension_task
        # we can also use all_examples and all_features to avoid duplicate long-time preprocessing
        examples = None
        if self.all_examples[phase]:
            examples = self.all_examples[phase]
K
kinghuin 已提交
906
        else:
K
kinghuin 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930
            if phase == 'train':
                examples = self.get_train_examples()
            elif phase == 'dev':
                examples = self.get_dev_examples()
            elif phase == 'test':
                examples = self.get_test_examples()
            elif phase == 'predict':
                examples = data
            else:
                raise ValueError(
                    "Unknown phase, which should be in ['train', 'dev', 'test', 'predict']."
                )
            self.all_examples[phase] = examples
        shuffle = True if phase == 'train' else False

        # As reading comprehension task will divide a long context into several doc_spans and then get multiple features
        # To get the real total steps, we need to know the features' length
        # So we use _convert_examples_to_records rather than _convert_example_to_record in this task
        if self.all_features[phase]:
            features = self.all_features[phase]
        else:
            features = self._convert_examples_to_records(
                examples, self.max_seq_len, self.tokenizer, phase)
            self.all_features[phase] = features
K
kinghuin 已提交
931

K
kinghuin 已提交
932 933 934
        # self.num_examples["train"] use in strategy.py to show the total steps,
        # we need to cover it with correct len(features)
        self.num_examples[phase] = len(features)
K
kinghuin 已提交
935 936 937

        def wrapper():
            if shuffle:
K
kinghuin 已提交
938
                np.random.shuffle(features)
K
kinghuin 已提交
939

K
kinghuin 已提交
940 941
            for batch_data in self._prepare_batch_data(
                    features, batch_size, phase=phase):
942 943 944 945 946 947
                if return_list:
                    # for DataFeeder
                    yield [batch_data]
                else:
                    # for DataLoader
                    yield batch_data
K
kinghuin 已提交
948 949 950

        return wrapper

K
kinghuin 已提交
951 952 953 954 955
    def _convert_examples_to_records(self,
                                     examples,
                                     max_seq_length,
                                     tokenizer,
                                     phase=None):
K
kinghuin 已提交
956
        """Loads a data file into a list of `InputBatch`s."""
K
kinghuin 已提交
957
        features = []
K
kinghuin 已提交
958 959 960
        unique_id = 1000000000

        for (example_index, example) in enumerate(examples):
K
kinghuin 已提交
961 962 963
            query_tokens = tokenizer.tokenize(example.question_text)
            if len(query_tokens) > self.max_query_length:
                query_tokens = query_tokens[0:self.max_query_length]
K
kinghuin 已提交
964 965 966 967 968
            tok_to_orig_index = []
            orig_to_tok_index = []
            all_doc_tokens = []
            for (i, token) in enumerate(example.doc_tokens):
                orig_to_tok_index.append(len(all_doc_tokens))
K
kinghuin 已提交
969
                sub_tokens = tokenizer.tokenize(token)
K
kinghuin 已提交
970 971 972 973 974 975
                for sub_token in sub_tokens:
                    tok_to_orig_index.append(i)
                    all_doc_tokens.append(sub_token)

            tok_start_position = None
            tok_end_position = None
K
kinghuin 已提交
976 977 978 979
            is_impossible = example.is_impossible if hasattr(
                example, "is_impossible") else False

            if phase != "predict" and is_impossible:
K
kinghuin 已提交
980 981
                tok_start_position = -1
                tok_end_position = -1
K
kinghuin 已提交
982
            if phase != "predict" and not is_impossible:
K
kinghuin 已提交
983 984 985 986 987 988 989 990 991
                tok_start_position = orig_to_tok_index[example.start_position]
                if example.end_position < len(example.doc_tokens) - 1:
                    tok_end_position = orig_to_tok_index[example.end_position +
                                                         1] - 1
                else:
                    tok_end_position = len(all_doc_tokens) - 1
                (tok_start_position,
                 tok_end_position) = self.improve_answer_span(
                     all_doc_tokens, tok_start_position, tok_end_position,
K
kinghuin 已提交
992
                     tokenizer, example.orig_answer_text)
K
kinghuin 已提交
993 994

            # The -3 accounts for [CLS], [SEP] and [SEP]
K
kinghuin 已提交
995
            max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
K
kinghuin 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005

            # We can have documents that are longer than the maximum sequence length.
            # To deal with this we do a sliding window approach, where we take chunks
            # of the up to our max length with a stride of `doc_stride`.
            doc_spans = []
            start_offset = 0
            while start_offset < len(all_doc_tokens):
                length = len(all_doc_tokens) - start_offset
                if length > max_tokens_for_doc:
                    length = max_tokens_for_doc
K
kinghuin 已提交
1006 1007
                doc_spans.append(
                    self._DocSpan(start=start_offset, length=length))
K
kinghuin 已提交
1008 1009
                if start_offset + length == len(all_doc_tokens):
                    break
K
kinghuin 已提交
1010
                start_offset += min(length, self.doc_stride)
K
kinghuin 已提交
1011 1012 1013 1014 1015

            for (doc_span_index, doc_span) in enumerate(doc_spans):
                tokens = []
                token_to_orig_map = {}
                token_is_max_context = {}
K
kinghuin 已提交
1016
                text_type_ids = []
K
kinghuin 已提交
1017
                tokens.append("[CLS]")
K
kinghuin 已提交
1018
                text_type_ids.append(0)
K
kinghuin 已提交
1019 1020
                for token in query_tokens:
                    tokens.append(token)
K
kinghuin 已提交
1021
                    text_type_ids.append(0)
K
kinghuin 已提交
1022
                tokens.append("[SEP]")
K
kinghuin 已提交
1023
                text_type_ids.append(0)
K
kinghuin 已提交
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033

                for i in range(doc_span.length):
                    split_token_index = doc_span.start + i
                    token_to_orig_map[len(
                        tokens)] = tok_to_orig_index[split_token_index]

                    is_max_context = self.check_is_max_context(
                        doc_spans, doc_span_index, split_token_index)
                    token_is_max_context[len(tokens)] = is_max_context
                    tokens.append(all_doc_tokens[split_token_index])
K
kinghuin 已提交
1034
                    text_type_ids.append(1)
K
kinghuin 已提交
1035
                tokens.append("[SEP]")
K
kinghuin 已提交
1036
                text_type_ids.append(1)
K
kinghuin 已提交
1037

K
kinghuin 已提交
1038 1039
                token_ids = tokenizer.convert_tokens_to_ids(tokens)
                position_ids = list(range(len(token_ids)))
K
kinghuin 已提交
1040 1041
                start_position = None
                end_position = None
K
kinghuin 已提交
1042
                if phase != "predict" and not is_impossible:
K
kinghuin 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
                    # For training, if our document chunk does not contain an annotation
                    # we throw it out, since there is nothing to predict.
                    doc_start = doc_span.start
                    doc_end = doc_span.start + doc_span.length - 1
                    out_of_span = False
                    if not (tok_start_position >= doc_start
                            and tok_end_position <= doc_end):
                        out_of_span = True
                    if out_of_span:
                        start_position = 0
                        end_position = 0
                    else:
                        doc_offset = len(query_tokens) + 2
                        start_position = tok_start_position - doc_start + doc_offset
                        end_position = tok_end_position - doc_start + doc_offset

K
kinghuin 已提交
1059
                if phase != "predict" and is_impossible:
K
kinghuin 已提交
1060 1061 1062
                    start_position = 0
                    end_position = 0

K
kinghuin 已提交
1063
                feature = Features(
K
kinghuin 已提交
1064 1065 1066 1067 1068 1069
                    unique_id=unique_id,
                    example_index=example_index,
                    doc_span_index=doc_span_index,
                    tokens=tokens,
                    token_to_orig_map=token_to_orig_map,
                    token_is_max_context=token_is_max_context,
K
kinghuin 已提交
1070 1071 1072
                    token_ids=token_ids,
                    position_ids=position_ids,
                    text_type_ids=text_type_ids,
K
kinghuin 已提交
1073 1074
                    start_position=start_position,
                    end_position=end_position,
K
kinghuin 已提交
1075 1076
                    is_impossible=is_impossible)
                features.append(feature)
K
kinghuin 已提交
1077 1078 1079

                unique_id += 1

K
kinghuin 已提交
1080
        return features
K
kinghuin 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155

    def improve_answer_span(self, doc_tokens, input_start, input_end, tokenizer,
                            orig_answer_text):
        """Returns tokenized answer spans that better match the annotated answer."""

        # The SQuAD annotations are character based. We first project them to
        # whitespace-tokenized words. But then after WordPiece tokenization, we can
        # often find a "better match". For example:
        #
        #   Question: What year was John Smith born?
        #   Context: The leader was John Smith (1895-1943).
        #   Answer: 1895
        #
        # The original whitespace-tokenized answer will be "(1895-1943).". However
        # after tokenization, our tokens will be "( 1895 - 1943 ) .". So we can match
        # the exact answer, 1895.
        #
        # However, this is not always possible. Consider the following:
        #
        #   Question: What country is the top exporter of electornics?
        #   Context: The Japanese electronics industry is the lagest in the world.
        #   Answer: Japan
        #
        # In this case, the annotator chose "Japan" as a character sub-span of
        # the word "Japanese". Since our WordPiece tokenizer does not split
        # "Japanese", we just use "Japanese" as the annotation. This is fairly rare
        # in SQuAD, but does happen.
        tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))

        for new_start in range(input_start, input_end + 1):
            for new_end in range(input_end, new_start - 1, -1):
                text_span = " ".join(doc_tokens[new_start:(new_end + 1)])
                if text_span == tok_answer_text:
                    return (new_start, new_end)

        return (input_start, input_end)

    def check_is_max_context(self, doc_spans, cur_span_index, position):
        """Check if this is the 'max context' doc span for the token."""

        # Because of the sliding window approach taken to scoring documents, a single
        # token can appear in multiple documents. E.g.
        #  Doc: the man went to the store and bought a gallon of milk
        #  Span A: the man went to the
        #  Span B: to the store and bought
        #  Span C: and bought a gallon of
        #  ...
        #
        # Now the word 'bought' will have two scores from spans B and C. We only
        # want to consider the score with "maximum context", which we define as
        # the *minimum* of its left and right context (the *sum* of left and
        # right context will always be the same, of course).
        #
        # In the example the maximum context for 'bought' would be span C since
        # it has 1 left context and 3 right context, while span B has 4 left context
        # and 0 right context.
        best_score = None
        best_span_index = None
        for (span_index, doc_span) in enumerate(doc_spans):
            end = doc_span.start + doc_span.length - 1
            if position < doc_span.start:
                continue
            if position > end:
                continue
            num_left_context = position - doc_span.start
            num_right_context = end - position
            score = min(num_left_context,
                        num_right_context) + 0.01 * doc_span.length
            if best_score is None or score > best_score:
                best_score = score
                best_span_index = span_index

        return cur_span_index == best_span_index


K
kinghuin 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164
class LACClassifyReader(BaseReader):
    def __init__(self, vocab_path, dataset=None, in_tokens=False):
        super(LACClassifyReader, self).__init__(dataset)
        self.in_tokens = in_tokens

        self.lac = hub.Module(name="lac")
        self.tokenizer = tokenization.FullTokenizer(
            vocab_file=vocab_path, do_lower_case=False)
        self.vocab = self.tokenizer.vocab
1165 1166 1167 1168 1169 1170 1171
        self.has_processed = {
            "train": False,
            "dev": False,
            "val": False,
            "test": False,
            "predict": False
        }
K
kinghuin 已提交
1172 1173 1174 1175 1176

    def data_generator(self,
                       batch_size=1,
                       phase="train",
                       shuffle=False,
1177 1178
                       data=None,
                       return_list=True):
K
kinghuin 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
        if phase != "predict" and not self.dataset:
            raise ValueError("The dataset is None and it isn't allowed.")
        if phase == "train":
            shuffle = True
            data = self.dataset.get_train_examples()
            self.num_examples['train'] = len(data)
        elif phase == "test":
            shuffle = False
            data = self.dataset.get_test_examples()
            self.num_examples['test'] = len(data)
        elif phase == "val" or phase == "dev":
            shuffle = False
            data = self.dataset.get_dev_examples()
            self.num_examples['dev'] = len(data)
        elif phase == "predict":
            data = data
        else:
            raise ValueError(
                "Unknown phase, which should be in ['train', 'dev', 'test'].")

        def preprocess(text):
1200
            data_dict = {'text': [text]}
K
kinghuin 已提交
1201 1202 1203 1204 1205
            processed = self.lac.lexical_analysis(data=data_dict)
            processed = [
                self.vocab[word] for word in processed[0]['word']
                if word in self.vocab
            ]
1206

K
kinghuin 已提交
1207 1208 1209 1210 1211 1212
            if len(processed) == 0:
                if six.PY2:
                    text = text.encode(sys_stdout_encoding())
                logger.warning(
                    "The words in text %s can't be found in the vocabulary." %
                    (text))
1213

K
kinghuin 已提交
1214 1215
            return processed

K
kinghuin 已提交
1216
        if not self.has_processed[phase] or phase == "predict":
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
            logger.info(
                "processing %s data now... this may take a few minutes" % phase)
            for i in range(len(data)):
                if phase == "predict":
                    data[i] = preprocess(data[i])
                else:
                    data[i].text_a = preprocess(data[i].text_a)
                    if self.label_map:
                        if data[i].label not in self.label_map:
                            raise KeyError("example.label = {%s} not in label" %
                                           data[i].label)
                        label_id = self.label_map[data[i].label]
                    else:
                        label_id = data[i].label
                    data[i].label = label_id
            self.has_processed[phase] = True

K
kinghuin 已提交
1234 1235 1236
        def _data_reader():
            if shuffle:
                np.random.shuffle(data)
1237 1238
            texts = []
            labels = []
K
kinghuin 已提交
1239 1240 1241 1242
            if phase == "predict":
                for text in data:
                    if not text:
                        continue
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
                    texts.append(text)
                    if len(texts) == batch_size:
                        if return_list:
                            # for DataFeeder
                            # if you want to use high-performance predictor, yield [[[t] for t in texts]]
                            yield [[t] for t in texts]
                        else:
                            # for DataLoader
                            # cannot use in high-performance predictor, as PaddleTensor rejects lod_tensor
                            texts = fluid.create_lod_tensor(
                                texts, [[len(seq) for seq in texts]],
                                fluid.CPUPlace())
                            yield [texts]
                        texts = []
                if texts:
                    if return_list:
                        yield [[t] for t in texts]
                    else:
                        texts = fluid.create_lod_tensor(
                            texts, [[len(seq) for seq in texts]],
                            fluid.CPUPlace())

                        yield [texts]
                    texts = []
K
kinghuin 已提交
1267 1268
            else:
                for item in data:
1269
                    text = item.text_a
K
kinghuin 已提交
1270 1271
                    if not text:
                        continue
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
                    texts.append(text)
                    labels.append([item.label])
                    if len(texts) == batch_size:
                        if return_list:
                            yield list(zip(texts, labels))
                        else:
                            texts = fluid.create_lod_tensor(
                                texts, [[len(seq) for seq in texts]],
                                fluid.CPUPlace())
                            yield [texts, labels]
                        texts = []
                        labels = []
                if texts:
                    if return_list:
                        yield list(zip(texts, labels))
                    else:
                        texts = fluid.create_lod_tensor(
                            texts, [[len(seq) for seq in texts]],
                            fluid.CPUPlace())
                        yield [texts, labels]
                    texts = []
                    labels = []

        return _data_reader
K
kinghuin 已提交
1296 1297


1298 1299
if __name__ == '__main__':
    pass