python - 向 Huggingface 变压器添加额外的层

标签 python tensorflow keras nlp huggingface-transformers

我想添加额外的 Dense预训练后的层 TFDistilBertModel , TFXLNetModelTFRobertaModel抱脸模特。我已经看到如何使用 TFBertModel 做到这一点。 ,例如in this notebook :

output = bert_model([input_ids,attention_masks])
output = output[1]
output = tf.keras.layers.Dense(32,activation='relu')(output)
所以,在这里我需要使用 1 的第二个项目(即索引为 BERT 的项目)输出元组。根据docs TFBertModelpooler_output在这个元组索引处。但是其他三个型号没有pooler_output .
那么,如何为其他三个模型输出添加额外的层?

最佳答案

它看起来像 pooler_outputRobertaBert具体输出。
但不是使用 pooler_output我们可以用几个hidden_states (因此,不仅是最后的隐藏状态)对于所有模型,我们都想使用它们,因为 papers report那个hidden_states可以提供比一个更准确的精度 last_hidden_state .

# Import the needed model(Bert, Roberta or DistilBert) with output_hidden_states=True
transformer_model = TFBertForSequenceClassification.from_pretrained('bert-large-cased', output_hidden_states=True)

input_ids = tf.keras.Input(shape=(128, ),dtype='int32')
attention_mask = tf.keras.Input(shape=(128, ), dtype='int32')

transformer = transformer_model([input_ids, attention_mask])    
hidden_states = transformer[1] # get output_hidden_states

hidden_states_size = 4 # count of the last states 
hiddes_states_ind = list(range(-hidden_states_size, 0, 1))

selected_hiddes_states = tf.keras.layers.concatenate(tuple([hidden_states[i] for i in hiddes_states_ind]))

# Now we can use selected_hiddes_states as we want
output = tf.keras.layers.Dense(128, activation='relu')(selected_hiddes_states)
output = tf.keras.layers.Dense(1, activation='sigmoid')(output)
model = tf.keras.models.Model(inputs = [input_ids, attention_mask], outputs = output)
model.compile(tf.keras.optimizers.Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])

关于python - 向 Huggingface 变压器添加额外的层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63201036/

相关文章:

python - Django 模板扩展问题

python - 编程从 Bloomberg 终端获取数据

c++ - Tensorflow 和 Bazel C++

python - 如何高效读取 CSV 的特定行?

python - Keras try save and load model error You are trying to load a weight file containing 16 layers into a model with 0 层数

python - 实现余弦相似度损失给出了与 Tensorflow 不同的答案

python - Django Tastypie - 前置 URL 不起作用

python - 在图像上插入文本[2],python

python - Keras 自定义损失计算不正确

Tensorflow 降低 3 阶张量的维度