Exemplo n.º 1
0
def encode_context(history: list, answer: str, tokenizer: BertTokenizer):
    token_ids = [tokenizer.cls_token_id]
    for sentence in history:
        token_ids.extend(tokenizer.encode(sentence)[1:])
    seg_ids = [0] * len(token_ids)
    token_ids.extend(tokenizer.encode(answer)[1:])
    seg_ids += [1] * (len(token_ids) - len(seg_ids))
    if len(token_ids) >= MAX_LEN:
        token_ids = [tokenizer.cls_token_id] + token_ids[-MAX_LEN + 1:]
        seg_ids = seg_ids[-MAX_LEN:]
    return token_ids, seg_ids
def convert_data_to_input_items(
        examples: List[Dict], label2idx: Dict, max_seq_length: int,
        tokenizer: BertTokenizer) -> List[BertInputItem]:
    """
    Converts a list of input examples to BertInputItems

    Args:
        examples: a list of examples as dicts of the form {"text": ..., "label": ...}
        label2idx: a dict that maps label strings to label ids
        max_seq_length: the maximum sequence length for the input items
        tokenizer: the tokenizer that will be used to tokenize the text

    Returns: a list of BertInputItems

    """

    input_items = []
    for (ex_index, ex) in enumerate(examples):

        # Create a list of token ids
        input_ids = tokenizer.encode("[CLS] " + ex["text"] + " [SEP]")
        if len(input_ids) > max_seq_length:
            input_ids = input_ids[:max_seq_length]

        # All our tokens are in the first input segment (id 0).
        segment_ids = [0] * len(input_ids)

        # The mask has 1 for real tokens and 0 for padding tokens. Only real
        # tokens are attended to.
        input_mask = [1] * len(input_ids)

        # Zero-pad up to the sequence length.
        padding = [0] * (max_seq_length - len(input_ids))
        input_ids += padding
        input_mask += padding
        segment_ids += padding

        assert len(input_ids) == max_seq_length
        assert len(input_mask) == max_seq_length
        assert len(segment_ids) == max_seq_length

        if type(ex["label"]) == str:
            label_id = label2idx[ex["label"]]
        elif type(ex["label"]) == list:
            label_id = np.zeros(len(label2idx))
            for label in ex["label"]:
                label_id[label2idx[label]] = 1

        input_items.append(
            BertInputItem(text=ex["text"],
                          input_ids=input_ids,
                          input_mask=input_mask,
                          segment_ids=segment_ids,
                          label_id=label_id))
    return input_items
Exemplo n.º 3
0
from transformers.tokenization_bert import BertTokenizer

vocab_path = "../data/wordpiece_pretty.txt"
vocab_path2 = "../data/wpm-vocab-all.txt"
vocab_path3 = "../data/wiki-vocab.txt"

tokenizer = BertTokenizer(vocab_file=vocab_path3, do_lower_case=False)
"""  """
test_str = ' [CLS] 나는 워드피스 토크나이저를 써요. 하리보가 걸어다니네? 하리보보 하리보 [SEP]'
print('테스트 문장: ', test_str)
encoded_str = tokenizer.encode(test_str, add_special_tokens=False)
print('문장 인코딩: ', encoded_str)
decoded_str = tokenizer.decode(encoded_str)
print('문장 디코딩: ', decoded_str)
"""
겱과
테스트 문장:   [CLS] 나는 워드피스 토크나이저를 써요. 성능이 좋은지 테스트 해보려 합니다. [SEP]
문장 인코딩:  [2, 9310, 4868, 6071, 12467, 21732, 12200, 6126, 6014, 4689, 6100, 18, 11612, 6037, 9389, 6073, 16784, 17316, 6070, 10316, 18, 3]
문장 디코딩:  [CLS] 나는 워드피스 토크나이저를 써요. 성능이 좋은지 테스트 해보려 합니다. [SEP]
"""