首页 > 解决方案 > 如何使用transformers.BertTokenizer对多个句子进行编码?

问题描述

我想通过使用 transform.BertTokenizer 对多个句子进行编码来创建一个小批量。它似乎适用于一个句子。如何使它适用于几个句子?

from transformers import BertTokenizer

tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')

# tokenize a single sentence seems working
tokenizer.encode('this is the first sentence')
>>> [2023, 2003, 1996, 2034, 6251]

# tokenize two sentences
tokenizer.encode(['this is the first sentence', 'another sentence'])
>>> [100, 100] # expecting 7 tokens

标签: word-embeddinghuggingface-transformershuggingface-tokenizers

解决方案


transformers >= 4.0.0tokenizer
的 使用__call__方法。它将为每个输入句子生成一个包含,和as 列表的字典:input_idstoken_type_idsattention_mask

tokenizer(['this is the first sentence', 'another setence'])

输出:

{'input_ids': [[101, 2023, 2003, 1996, 2034, 6251, 102], [101, 2178, 2275, 10127, 102]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]}

变压器 < 4.0.0
使用tokenizer.batch_encode_plus文档)。它将为每个输入句子生成一个包含input_ids,token_type_ids和as 列表的字典:attention_mask

tokenizer.batch_encode_plus(['this is the first sentence', 'another setence'])

输出:

{'input_ids': [[101, 2023, 2003, 1996, 2034, 6251, 102], [101, 2178, 2275, 10127, 102]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]}

适用于call和 batch_encode_plus:
如果您只想生成 input_ids,则必须将return_token_type_idsans设置return_attention_mask为 False:

tokenizer.batch_encode_plus(['this is the first sentence', 'another setence'], return_token_type_ids=False, return_attention_mask=False)

输出:

{'input_ids': [[101, 2023, 2003, 1996, 2034, 6251, 102], [101, 2178, 2275, 10127, 102]]}

推荐阅读