gpt4 book ai didi

tensorflow - 如何访问 Huggingface 预训练 BERT 模型的特定层?

转载 作者:行者123 更新时间:2023-12-02 02:16:40 25 4
gpt4 key购买 nike

出于实验目的,我需要访问编码器的嵌入层。也就是说,假设 Tensorflow 实现,该层定义为 tf.keras.layers.Embedding(...)。

例如,在转换器的编码器部分设置 Embedding() 层的 'embeddings_regularizer=' 参数的方法是什么?

最佳答案

您可以像任何其他模型一样迭代 BERT 模型,如下所示:

for layer in model.layers:
if isinstance(layer ,tf.keras.layers.Embedding):
layer.embeddings_regularizer = argument

isinstance 检查图层的类型,因此您实际上可以在此处放置任何图层类型并更改您需要的内容。

我还没有具体检查 embeddings_regularizer 是否可用,但是如果您想查看该特定层可以使用哪些方法,请运行调试器并调用 dir(layer) code> 在上面的函数中。

更新问题

TFBertForSequenceClassification 模型有 3 层:

>>> model.summary()

Model: "tf_bert_for_sequence_classification"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
bert (TFBertMainLayer) multiple 108310272
_________________________________________________________________
dropout_37 (Dropout) multiple 0
_________________________________________________________________
classifier (Dense) multiple 1538
=================================================================
Total params: 108,311,810
Trainable params: 108,311,810
Non-trainable params: 0

同样,调用 model.layers 会得到:

[<transformers.models.bert.modeling_tf_bert.TFBertMainLayer at 0x7efda85595d0>,
<tensorflow.python.keras.layers.core.Dropout at 0x7efd6000ae10>,
<tensorflow.python.keras.layers.core.Dense at 0x7efd6000afd0>]

我们可以访问TFBERtMainLayer内部的层:

>>> model.layers[0]._layers


[<transformers.models.bert.modeling_tf_bert.TFBertEmbeddings at 0x7efda8080f90>,
<transformers.models.bert.modeling_tf_bert.TFBertEncoder at 0x7efda855ced0>,
<transformers.models.bert.modeling_tf_bert.TFBertPooler at 0x7efda84f0450>,
DictWrapper({'name': 'bert'})]

因此,从上面我们可以通过以下方式访问 TFBertEmbeddings 层:

model.layers[0].embeddings

OR

model.layers[0]._layers[0]

如果您检查 documentation (搜索“TFBERtEmbeddings”类)您可以看到它继承了标准的 tf.keras.layers.Layer 这意味着您可以访问所有正常的正则化器方法,因此您应该能够调用像这样:

from tensorflow.keras import regularizers

model.layers[0].embeddings.activity_regularizer = regularizers.l2(1e-5)

或者您需要更改的任何参数/正则化器。请参阅here用于正则化器文档。

关于tensorflow - 如何访问 Huggingface 预训练 BERT 模型的特定层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67052427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com