batch = [ "我喜欢红色", "你喜欢蓝色吗", "我们都喜欢绿色,不是吗"]
可以使用Tokenizer进行数字编码,例如:
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') # 加载中文BERT分词器
batch = [
"我喜欢红色",
"你喜欢蓝色吗",
"我们都喜欢绿色,不是吗"
]
encoded_batch = tokenizer(batch, padding=True, truncation=True, return_tensors='pt') # 返回pytorch张量
print(encoded_batch)
输出结果:
{'input_ids': tensor([[ 101, 2769, 6421, 4692, 2399, 102],
[ 101, 872, 6421, 5023, 7274, 720, 102],
[ 101, 2767, 6963, 2218, 4692, 1086, 8024, 679, 3221, 2739,
8024, 679, 3221, 6662, 102]]),
'token_type_ids': tensor([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]),
'attention_mask': tensor([[1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])}
其中,input_ids
是每个句子的token id序列,token_type_ids
表示句子所属的句子对,attention_mask
是注意力掩码,以便在序列长度不同时进行填充。需要注意的是,如果使用其他预训练模型,语言对应的分词器不一定相同