utils.py 2.3 KB
Newer Older
S
Steffy-zxf 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np


17
def convert_example(example, tokenizer, is_test=False):
S
Steffy-zxf 已提交
18 19 20 21 22 23
    """
    Builds model inputs from a sequence for sequence classification tasks. 
    It use `jieba.cut` to tokenize text.

    Args:
        example(obj:`list[str]`): List of input data, containing text and label if it have label.
24
        tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese string.
S
Steffy-zxf 已提交
25 26 27
        is_test(obj:`False`, defaults to `False`): Whether the example contains label or not.

    Returns:
28
        input_ids(obj:`list[int]`): The list of token ids.
S
Steffy-zxf 已提交
29 30 31 32
        valid_length(obj:`int`): The input sequence valid length.
        label(obj:`numpy.array`, data type of int64, optional): The input label if not is_test.
    """

33
    input_ids = tokenizer.encode(example[0])
34
    valid_length = np.array(len(input_ids), dtype='int64')
35
    input_ids = np.array(input_ids, dtype='int64')
S
Steffy-zxf 已提交
36 37 38 39 40 41 42 43

    if not is_test:
        label = np.array(example[-1], dtype="int64")
        return input_ids, valid_length, label
    else:
        return input_ids, valid_length


44
def preprocess_prediction_data(data, tokenizer):
S
Steffy-zxf 已提交
45 46 47 48 49
    """
    It process the prediction data as the format used as training.

    Args:
        data (obj:`List[str]`): The prediction data whose each element is  a tokenized text.
50
        tokenizer(obj: paddlenlp.data.JiebaTokenizer): It use jieba to cut the chinese string.
S
Steffy-zxf 已提交
51 52 53

    Returns:
        examples (obj:`List(Example)`): The processed data whose each element is a Example (numedtuple) object.
Z
Zeyu Chen 已提交
54
            A Example object contains `text`(word_ids) and `seq_len`(sequence length).
S
Steffy-zxf 已提交
55 56 57 58

    """
    examples = []
    for text in data:
59
        ids = tokenizer.encode(text)
S
Steffy-zxf 已提交
60 61
        examples.append([ids, len(ids)])
    return examples