您可以调用tokenizer.convert_ids_to_tokens() 来获取一个 id 的实际令牌:
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
tokens = []
tokens.append(tokenizer.encode(["Hello, my dog is cute", "He is really nice"]))
tokens.append(tokenizer.encode("Hello, my dog is cute", "He is really nice"))
tokens.append(tokenizer.encode(["Hello, my dog is cute"]))
tokens.append(tokenizer.encode("Hello, my dog is cute"))
for t in tokens:
print(tokenizer.convert_ids_to_tokens(t))
输出:
['[CLS]', '[UNK]', '[UNK]', '[SEP]']
['[CLS]', 'hello', ',', 'my', 'dog', 'is', 'cute', '[SEP]', 'he', 'is', 'really', 'nice', '[SEP]']
['[CLS]', '[UNK]', '[SEP]']
['[CLS]', 'hello', ',', 'my', 'dog', 'is', 'cute', '[SEP]']
正如您在此处看到的,您的每个输入都经过标记化,并根据您的模型 (bert) 添加了特殊标记。编码功能没有正确处理您的列表,这可能是一个错误或预期的行为,具体取决于您如何定义它,因为它们是一种批处理方法batch_encode_plus:
tokenizer.batch_encode_plus(["Hello, my dog is cute", "He is really nice"], return_token_type_ids=False, return_attention_mask=False)
输出:
{'input_ids': [[101, 7592, 1010, 2026, 3899, 2003, 10140, 102], [101, 2002, 2003, 2428, 3835, 102]]}
我不确定为什么没有记录 encode 方法,但可能是 huggingface 希望我们直接使用 call 方法:
tokens = []
tokens.append(tokenizer(["Hello, my dog is cute", "He is really nice"], return_token_type_ids=False, return_attention_mask=False))
tokens.append(tokenizer("Hello, my dog is cute", "He is really nice", return_token_type_ids=False, return_attention_mask=False))
tokens.append(tokenizer(["Hello, my dog is cute"], return_token_type_ids=False, return_attention_mask=False))
tokens.append(tokenizer("Hello, my dog is cute", return_token_type_ids=False, return_attention_mask=False))
print(tokens)
输出:
[{'input_ids': [[101, 7592, 1010, 2026, 3899, 2003, 10140, 102], [101, 2002, 2003, 2428, 3835, 102]]}, {'input_ids': [101, 7592, 1010, 2026, 3899, 2003, 10140, 102, 2002, 2003, 2428, 3835, 102]}, {'input_ids': [[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]]}, {'input_ids': [101, 7592, 1010, 2026, 3899, 2003, 10140, 102]}]