无法找到我添加到 Huggingface Bert 分词器词汇表中的词

Unable to find the word that I added to the Huggingface Bert tokenizer vocabulary

我尝试向 Bert tokenizer vocab 添加新词。我看到词汇表的长度在增加,但是我在词汇表中找不到新添加的单词。

tokenizer.add_tokens(['covid', 'wuhan'])

v = tokenizer.get_vocab()

print(len(v))
'covid' in tokenizer.vocab

输出:

30524

False

您用 tokenizer.vocabtokenizer.get_vocab() 调用了两个不同的东西。第一个包含没有添加标记的基础词汇,而另一个包含添加标记的基础词汇。

from transformers import BertTokenizer

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

print(len(t.vocab))
print(len(t.get_vocab()))
print(t.get_added_vocab())
t.add_tokens(['covid'])
print(len(t.vocab))
print(len(t.get_vocab()))
print(t.get_added_vocab())

输出:

30522
30522
{}
30522
30523
{'covid': 30522}