在使用Bert Tokenizer时,可以使用padding参数来指定如何进行填充。padding有两个可选项:“max_length”和“longest”,默认值为“max_length”。
如果padding为“max_length”,则在序列的末尾添加0,以使所有序列的长度相同。其中,序列的最大长度是通过tokenizer.encode_plus()函数中设置的max_length参数指定的。
代码示例:
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
text = "Hello, welcome to my world."
encoded_dict = tokenizer.encode_plus(text, padding='max_length', max_length=10, return_tensors='pt')
print(encoded_dict['input_ids'])
#outputs: tensor([[ 101, 7592, 1010, 6160, 2000, 2026, 2088, 1012, 0, 0]])
如果padding为“longest”,则将所有序列填充到最长序列的长度,并将短序列前置0以使它们达到相同长度。
代码示例:
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
texts = ["Hello, welcome to my world.", "This is your world."]
encoded_dict = tokenizer.batch_encode_plus(texts, padding='longest', return_tensors='pt')
print(encoded_dict['input_ids'])
#outputs: tensor([[ 101, 7592, 1010, 6160, 2000, 2026, 2088, 1012, 0, 0],
# [ 101, 2023, 2003, 2115, 2088, 1012, 0, 0, 0, 0]])