首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将BertforSequenceClassification模型的权重加载到BertforTokenClassification模型中?

如何将BertforSequenceClassification模型的权重加载到BertforTokenClassification模型中?
EN

Stack Overflow用户
提问于 2020-03-28 13:15:27
回答 2查看 1.8K关注 0票数 1

最初,我使用文本分类数据集对基于BERT的模型进行了微调,为此我使用了BertforSequenceClassification类。

代码语言:javascript
复制
from transformers import BertForSequenceClassification, AdamW, BertConfig

# Load BertForSequenceClassification, the pretrained BERT model with a single 
# linear classification layer on top. 
model = BertForSequenceClassification.from_pretrained(
    "bert-base-uncased", # Use the 12-layer BERT model, with an uncased vocab.
    num_labels = 2, # The number of output labels--2 for binary classification.
                    # You can increase this for multi-class tasks.   
    output_attentions = False, # Whether the model returns attentions weights.
    output_hidden_states = False, # Whether the model returns all hidden-states.
)

现在,我想使用这个经过微调的BERT模型权重来识别命名实体,为此我必须使用BertforTokenClassification类。我不知道如何将微调的BERT模型权重加载到使用BertforTokenClassification创建的新模型中。

预先致谢..

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-03-28 15:42:27

您可以从第一个模型中的bert获得权重,然后加载到第二个模型中的bert中:

代码语言:javascript
复制
new_model = BertForTokenClassification(config=config)
new_model.bert.load_state_dict(model.bert.state_dict())
票数 4
EN

Stack Overflow用户

发布于 2020-04-14 15:41:43

这对我很有效

代码语言:javascript
复制
new_model = BertForTokenClassification.from_pretrained('/config path')
new_model.bert.load_state_dict(model.bert.state_dict())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60897514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档