文章目录
正如quickstar中描述的,我们使用tokenizer来讲句子进行分词,切成许多个tokens,然后将其转化成数字,再转化成矩阵/向量,这样才能传输进模型中。记住用什么模型,就要用其对应的tokenizer
使用from_pretrained()
方法,来自动获取某个特定模型在预训练和微调时用的vocab字典
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained('bert-base-cased')
1. Base Use 基本用途
PreTrainedTokenizer
有很多方法(methods),但是对于preprocessing,只需要记住对它本身的调用
encoded_input = tokenizer("Hello, I'm a single sentence!")
print(encoded_input)
得一字典:
{
'input_ids': [101, 138, 18696, 155, 1942, 3190, 1144, 1572, 13745, 1104, 159, 9664, 2107, 102],
'token_type_ids': [0, 0, 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, 1, 1]}
再下一节会介绍'token_type_ids'
和'attention_mask'
干什么用的
tokenizer还能decode解码token_ids
tokenizer.decode(encoded_input["input_ids"])
"[CLS] Hello, I'm a single sentence! [SEP]"
可以看到tokenizer自动地加上了些特殊tokens [CLS]
和[SEP]
,并不是所有的模型需要特殊tokens,
部分模型可以传入add_special_tokens=False
来取消
如果您要处理多个句子,则可以通过将它们作为列表发送到tokenizer来有效地做到这一点:
batch_sentences = ["Hello I'm a single sentence",
"And another sentence",
"And the very very last one"]
encoded_inputs = tokenizer(batch_sentences)
print(encoded_inputs)
得:
{
'input_ids': [[101, 8667, 146, 112, 182, 170, 1423, 5650, 102],
[101, 1262, 1330, 5650, 102],
[101, 1262, 1103, 1304, 1304, 1314, 1141, 102]],
'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]],
'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1],