“5b3d5072346f99e40595f4dee6e4c80f48cf0119”上不存在“05.recommender_system/README.cn.md”
nlp_reader.py 47.2 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

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

            for item in data:
                # set label in order to run the program
S
Steffy-zxf 已提交
228 229 230 231
                if self.dataset:
                    label = list(self.label_map.keys())[0]
                else:
                    label = 0
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
                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
247 248
        else:
            raise ValueError(
249 250
                "Unknown phase, which should be in ['train', 'dev', 'test', 'predict']."
            )
251

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

Z
Zeyu Chen 已提交
256 257
            for batch_data in self._prepare_batch_data(
                    examples, batch_size, phase=phase):
258 259 260 261 262
                yield [batch_data]

        return wrapper


K
kinghuin 已提交
263
class ClassifyReader(BaseNLPReader):
264
    def _pad_batch_records(self, batch_records, phase=None):
Z
Zeyu Chen 已提交
265 266 267
        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]
268

Z
Zeyu Chen 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281
        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)
282

283 284 285 286 287 288 289 290 291
        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
            ]
292 293 294 295 296 297 298 299

            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
                ]
300 301 302 303 304
        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask
            ]
305

306
            if self.use_task_id:
307 308
                padded_task_ids = np.ones_like(
                    padded_token_ids, dtype="int64") * self.task_id
309 310 311 312
                return_list = [
                    padded_token_ids, padded_position_ids, padded_text_type_ids,
                    input_mask, padded_task_ids
                ]
Z
Zeyu Chen 已提交
313
        return return_list
314 315


K
kinghuin 已提交
316
class SequenceLabelReader(BaseNLPReader):
K
kinghuin 已提交
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    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)

345
    def _pad_batch_records(self, batch_records, phase=None):
Z
Zeyu Chen 已提交
346 347 348
        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]
349

Z
Zeyu Chen 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        # 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)
365

366
        if phase != "predict":
K
kinghuin 已提交
367
            batch_label_ids = [record.label_id for record in batch_records]
368 369 370 371 372 373 374 375 376
            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
            ]
377 378 379 380 381 382 383 384 385 386

            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
                ]

387 388 389 390 391
        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask, batch_seq_lens
            ]
392 393 394 395 396 397 398 399 400

            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 已提交
401 402
        return return_list

403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    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 已提交
423
            if len(ret_tokens) != len(ret_labels):
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
                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 已提交
444

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

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        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 已提交
464
            record = self.Record_With_Label_Id(
465 466 467
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids,
K
kinghuin 已提交
468
                label_id=label_ids)
469 470 471 472 473 474 475 476 477 478 479 480
        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 已提交
481
            record = self.Record_Wo_Label_Id(
482 483 484 485
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids,
            )
Z
Zeyu Chen 已提交
486 487 488 489

        return record


K
kinghuin 已提交
490
class MultiLabelClassifyReader(BaseNLPReader):
S
Steffy-zxf 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
    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 已提交
512
            batch_labels_ids = [record.label_id for record in batch_records]
S
Steffy-zxf 已提交
513 514 515 516 517 518 519 520
            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
            ]
521 522 523 524 525 526 527 528

            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 已提交
529 530 531 532 533
        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask
            ]
534 535 536 537 538 539 540 541

            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 已提交
542 543 544 545 546 547 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
        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 = []
590 591 592 593
        if phase == "predict":
            label_ids = [0, 0, 0, 0, 0, 0]
        else:
            for label in example.label:
Z
zhangxuefei 已提交
594
                label_ids.append(int(label))
S
Steffy-zxf 已提交
595 596

        if phase != "predict":
K
kinghuin 已提交
597
            record = self.Record_With_Label_Id(
S
Steffy-zxf 已提交
598 599 600
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids,
K
kinghuin 已提交
601
                label_id=label_ids)
S
Steffy-zxf 已提交
602
        else:
K
kinghuin 已提交
603
            record = self.Record_Wo_Label_Id(
S
Steffy-zxf 已提交
604 605 606 607 608 609 610
                token_ids=token_ids,
                text_type_ids=text_type_ids,
                position_ids=position_ids)

        return record


K
kinghuin 已提交
611
class RegressionReader(BaseNLPReader):
K
kinghuin 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    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 已提交
641 642 643 644 645 646 647 648

            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 已提交
649 650 651 652 653 654
        else:
            return_list = [
                padded_token_ids, padded_position_ids, padded_text_type_ids,
                input_mask
            ]

K
kinghuin 已提交
655 656 657 658 659 660 661 662
            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 已提交
663 664 665 666 667 668 669
        return return_list

    def data_generator(self,
                       batch_size=1,
                       phase='train',
                       shuffle=True,
                       data=None):
S
Steffy-zxf 已提交
670 671
        if phase != 'predict' and not self.dataset:
            raise ValueError("The dataset is none and it's not allowed.")
K
kinghuin 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
        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 已提交
691
                label = -1  # different from BaseNLPReader
K
kinghuin 已提交
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
                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):
                yield [batch_data]

        return wrapper


K
kinghuin 已提交
723 724 725 726 727 728 729 730 731 732 733 734 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
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 已提交
766
class ReadingComprehensionReader(BaseNLPReader):
K
kinghuin 已提交
767 768 769 770
    def __init__(self,
                 dataset,
                 vocab_path,
                 do_lower_case=True,
K
kinghuin 已提交
771
                 max_seq_len=512,
K
kinghuin 已提交
772 773
                 doc_stride=128,
                 max_query_length=64,
K
kinghuin 已提交
774
                 random_seed=None,
K
kinghuin 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
                 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 已提交
791 792
        self.doc_stride = doc_stride
        self.max_query_length = max_query_length
K
kinghuin 已提交
793
        self._DocSpan = collections.namedtuple("DocSpan", ["start", "length"])
K
kinghuin 已提交
794 795 796 797
        # 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 已提交
798

K
kinghuin 已提交
799 800 801 802 803 804 805
    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 已提交
806

K
kinghuin 已提交
807 808 809 810 811 812 813 814 815 816 817 818 819 820
        # 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 已提交
821

K
kinghuin 已提交
822 823 824 825 826 827 828 829 830 831 832
        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 已提交
833

K
kinghuin 已提交
834 835 836 837 838
            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 已提交
839

K
kinghuin 已提交
840 841 842 843 844 845 846 847 848 849 850 851 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
            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 已提交
882 883 884 885 886 887

    def data_generator(self,
                       batch_size=1,
                       phase='train',
                       shuffle=False,
                       data=None):
K
kinghuin 已提交
888 889 890 891 892
        # 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 已提交
893
        else:
K
kinghuin 已提交
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
            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 已提交
918

K
kinghuin 已提交
919 920 921
        # 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 已提交
922 923 924

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

K
kinghuin 已提交
927 928
            for batch_data in self._prepare_batch_data(
                    features, batch_size, phase=phase):
K
kinghuin 已提交
929 930 931 932
                yield [batch_data]

        return wrapper

K
kinghuin 已提交
933 934 935 936 937
    def _convert_examples_to_records(self,
                                     examples,
                                     max_seq_length,
                                     tokenizer,
                                     phase=None):
K
kinghuin 已提交
938
        """Loads a data file into a list of `InputBatch`s."""
K
kinghuin 已提交
939
        features = []
K
kinghuin 已提交
940 941 942
        unique_id = 1000000000

        for (example_index, example) in enumerate(examples):
K
kinghuin 已提交
943 944 945
            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 已提交
946 947 948 949 950
            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 已提交
951
                sub_tokens = tokenizer.tokenize(token)
K
kinghuin 已提交
952 953 954 955 956 957
                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 已提交
958 959 960 961
            is_impossible = example.is_impossible if hasattr(
                example, "is_impossible") else False

            if phase != "predict" and is_impossible:
K
kinghuin 已提交
962 963
                tok_start_position = -1
                tok_end_position = -1
K
kinghuin 已提交
964
            if phase != "predict" and not is_impossible:
K
kinghuin 已提交
965 966 967 968 969 970 971 972 973
                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 已提交
974
                     tokenizer, example.orig_answer_text)
K
kinghuin 已提交
975 976

            # The -3 accounts for [CLS], [SEP] and [SEP]
K
kinghuin 已提交
977
            max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
K
kinghuin 已提交
978 979 980 981 982 983 984 985 986 987

            # 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 已提交
988 989
                doc_spans.append(
                    self._DocSpan(start=start_offset, length=length))
K
kinghuin 已提交
990 991
                if start_offset + length == len(all_doc_tokens):
                    break
K
kinghuin 已提交
992
                start_offset += min(length, self.doc_stride)
K
kinghuin 已提交
993 994 995 996 997

            for (doc_span_index, doc_span) in enumerate(doc_spans):
                tokens = []
                token_to_orig_map = {}
                token_is_max_context = {}
K
kinghuin 已提交
998
                text_type_ids = []
K
kinghuin 已提交
999
                tokens.append("[CLS]")
K
kinghuin 已提交
1000
                text_type_ids.append(0)
K
kinghuin 已提交
1001 1002
                for token in query_tokens:
                    tokens.append(token)
K
kinghuin 已提交
1003
                    text_type_ids.append(0)
K
kinghuin 已提交
1004
                tokens.append("[SEP]")
K
kinghuin 已提交
1005
                text_type_ids.append(0)
K
kinghuin 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

                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 已提交
1016
                    text_type_ids.append(1)
K
kinghuin 已提交
1017
                tokens.append("[SEP]")
K
kinghuin 已提交
1018
                text_type_ids.append(1)
K
kinghuin 已提交
1019

K
kinghuin 已提交
1020 1021
                token_ids = tokenizer.convert_tokens_to_ids(tokens)
                position_ids = list(range(len(token_ids)))
K
kinghuin 已提交
1022 1023
                start_position = None
                end_position = None
K
kinghuin 已提交
1024
                if phase != "predict" and not is_impossible:
K
kinghuin 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
                    # 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 已提交
1041
                if phase != "predict" and is_impossible:
K
kinghuin 已提交
1042 1043 1044
                    start_position = 0
                    end_position = 0

K
kinghuin 已提交
1045
                feature = Features(
K
kinghuin 已提交
1046 1047 1048 1049 1050 1051
                    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 已提交
1052 1053 1054
                    token_ids=token_ids,
                    position_ids=position_ids,
                    text_type_ids=text_type_ids,
K
kinghuin 已提交
1055 1056
                    start_position=start_position,
                    end_position=end_position,
K
kinghuin 已提交
1057 1058
                    is_impossible=is_impossible)
                features.append(feature)
K
kinghuin 已提交
1059 1060 1061

                unique_id += 1

K
kinghuin 已提交
1062
        return features
K
kinghuin 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 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

    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 已提交
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
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
        self.feed_key = list(
            self.lac.processor.data_format(
                sign_name="lexical_analysis").keys())[0]

    def data_generator(self,
                       batch_size=1,
                       phase="train",
                       shuffle=False,
                       data=None):
        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):
            data_dict = {self.feed_key: [text]}
            processed = self.lac.lexical_analysis(data=data_dict)
            processed = [
                self.vocab[word] for word in processed[0]['word']
                if word in self.vocab
            ]
            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))
            return processed

        def _data_reader():
            if shuffle:
                np.random.shuffle(data)

            if phase == "predict":
                for text in data:
                    text = preprocess(text)
                    if not text:
                        continue
                    yield (text, )
            else:
                for item in data:
                    text = preprocess(item.text_a)
                    if not text:
                        continue
                    yield (text, item.label)

        return paddle.batch(_data_reader, batch_size=batch_size)


1211 1212
if __name__ == '__main__':
    pass