【发布时间】: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