自定义huggingface bert模型中的encode模块

Customize the encode module in huggingface bert model

我正在使用 Huggingface transformers module 进行文本分类项目。 encode_plus 函数为用户提供了一种生成输入 id、注意掩码、令牌类型 id 等的便捷方式。例如:

from transformers import BertTokenizer

pretrained_model_name = 'bert-base-cased'
bert_base_tokenizer = BertTokenizer.from_pretrained(pretrained_model_name)

sample_text = 'Bamboo poles, ‍installation by an unknown building constructor #discoverhongkong #hongkonginsta'

encoding = bert_base_tokenizer.encode_plus(
        cleaned_tweet, hashtag_string,
        max_length=70,
        add_special_tokens=True,  # Add '[CLS]' and '[SEP]'
        return_token_type_ids=True,
        pad_to_max_length=True,
        return_attention_mask=True,
        return_tensors='pt',  # Return PyTorch tensors
    )

print('*'*20)
print(encoding['input_ids'])
print(encoding['attention_mask'])
print(encoding['token_type_ids'])
print('*'*20)

但是,我当前的项目要求我为给定文本生成自定义 ID。例如,对于一个单词列表 [HK, US, UK],我想为这些单词生成 id,并将该列表中不存在的其他单词的 id 设为零。这些 id 用于查找另一个自定义嵌入矩阵中的嵌入,而不是来自预训练的 bert 模块。

如何实现这种自定义编码器?欢迎任何建议和解决方案!谢谢~

我认为您可以在 BERT 词汇表中使用 <unusedxxx> 标记并在其中添加您的自定义标记。所以现在您可以使用有效的令牌 ID 轻松引用它们。