当前位置:   article > 正文

取出BERT中的某一部分网络/参数_bertconfig.from_pretrained

bertconfig.from_pretrained

今天在写代码的需要提取bert的部分网络或者参数,倒腾了好一会才弄明白。

准备工作

首先还是加载模型:

  1. from transformers import BertTokenizer, BertConfig, BertModel
  2. tokenizer = BertTokenizer.from_pretrained(bert_path)
  3. bert_config = BertConfig.from_pretrained(bert_path)
  4. model = BertModel.from_pretrained(bert_path)

获取某一层的网络

查看所有层

print(model)

会得到这样的结果:

 获取网络

然后就需要像俄罗斯套娃一样一层层去获取,比如我想要第一层中attention中output的dense层,那我就可以通过以下指令获取:

model.encoder.layer[0].attention.output.dense

 得到结果:

Linear(in_features=768, out_features=768, bias=True)

 其他层也是一样的,不麻烦!真棒~

获取某一层的参数 

查看所有层名和参数

print(model.state_dict())  # 这里相当于是参数层名和参数用字典存起来的

然后会有一大推下图这个,我是debug模式在调试控制台输出的,差不多一个意思啦。 

取出参数

然后如果我想要第一层的某个网络的参数就可以通过字典的key取出来,比如我想取这一层:

encoder.layer.3.attention.output.dense.bias

可以执行以下代码:

print(model.state_dict()["encoder.layer.3.attention.output.dense.bias"])

 任意哪一个参数都可以这样直接取出来,很方便。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/235714
推荐阅读
相关标签
  

闽ICP备14008679号