赞
踩
今天在写代码的需要提取bert的部分网络或者参数,倒腾了好一会才弄明白。
首先还是加载模型:
- from transformers import BertTokenizer, BertConfig, BertModel
- tokenizer = BertTokenizer.from_pretrained(bert_path)
- bert_config = BertConfig.from_pretrained(bert_path)
- 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"])
任意哪一个参数都可以这样直接取出来,很方便。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。