【问题标题】:How to mix tensorflow keras model and transformers如何混合使用 tensorflow keras 模型和转换器
【发布时间】:2021-03-17 08:24:13
【问题描述】:

我正在尝试从 Huggingface 的转换器库中导入一个预训练模型,并使用 tensorflow keras 将其扩展几层以进行分类。当我直接使用 Transformers 模型(方法 1)时,模型训练得很好,并且在 1 个 epoch 后达到了 0.93 的验证准确度。但是,当尝试将模型用作 tf.keras 模型中的层时(方法 2),模型的准确度无法达到 0.32 以上。据我根据文档可以看出,这两种方法应该是等效的。我的目标是让方法 2 正常工作,这样我就可以向它添加更多层,而不是直接使用 Huggingface 的分类器头产生的 logits,但我被困在这个阶段。

import tensorflow as tf

from transformers import TFRobertaForSequenceClassification

方法一:

model = TFRobertaForSequenceClassification.from_pretrained("roberta-base", num_labels=6)

方法二:

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

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

transformer = TFRobertaForSequenceClassification.from_pretrained("roberta-base", num_labels=6)

encoded = transformer([input_ids, attention_mask])

logits = encoded[0]

model = tf.keras.models.Model(inputs = [input_ids, attention_mask], outputs = logits)

这两种方法的其余代码是相同的,

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=3e-5, epsilon=1e-08, clipnorm=1.0),
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), 
              metrics=[tf.keras.metrics.SparseCategoricalAccuracy('accuracy')])

我正在使用 Tensorflow 2.3.0 并尝试使用转换器版本 3.5.0 和 4.0.0。

【问题讨论】:

    标签: python tensorflow keras nlp huggingface-transformers


    【解决方案1】:

    在这里回答我自己的问题。我在 HuggingFace GitHub 上发布了一个错误报告,他们在新的开发版本(截至 2020 年 12 月的 4.1.0.dev0)中修复了这个问题。下面的 sn-p 现在可以按预期工作了:

    input_ids = tf.keras.Input(shape=(128,), dtype='int32')
    attention_mask = tf.keras.Input(shape=(128, ), dtype='int32')
    
    transformer = TFRobertaForSequenceClassification.from_pretrained("roberta-base", num_labels=6)
    encoded = transformer({"input_ids": input_ids, "attention_mask": attention_mask})
    logits = encoded[0]
     
    model = tf.keras.models.Model(inputs = {"input_ids": input_ids, "attention_mask": attention_mask}, outputs = logits)
    

    【讨论】:

    • 嗨@Deepdelusion!为什么我们需要encoded = transformer({"input_ids": input_ids, "attention_mask": attention_mask}) 部分?谢谢。
    猜你喜欢
    • 2018-10-08
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    相关资源
    最近更新 更多