【问题标题】:Customize the encode module in huggingface bert model自定义 huggingface bert 模型中的 encode 模块
【发布时间】:2020-10-09 06:31:26
【问题描述】:

我正在使用Huggingface transformers module 进行文本分类项目。 encode_plus 函数为用户提供了一种方便的方式来生成输入 id、注意掩码、token 类型 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 模块。

我怎样才能实现这种定制的编码器?欢迎任何建议和解决方案!谢谢~

【问题讨论】:

  • 请记住,stackoverflow 不是代码编写服务。你面临什么问题?

标签: nlp text-classification huggingface-transformers bert-language-model


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-12-15
    • 2020-02-25
    • 1970-01-01
    • 2021-01-17
    • 2022-11-08
    • 1970-01-01
    • 2016-01-16
    • 2020-09-18
    • 1970-01-01
    相关资源
    最近更新 更多