首页 > 解决方案 > 如何使用 Tensorflow 后端从头开始训练任何 Hugging face 转换器模型(例如 DistilBERT)以回答问题?

问题描述

我想了解如何为问答系统和 TensorFlow 作为后端训练一个拥抱人脸转换器模型(如 BERT、DistilBERT 等)。以下是我目前使用的逻辑(但我不确定它是否正确):

  1. 我正在使用 SQuAD v1.1 数据集。
  2. 在 SQuAd 数据集中,任何问题的答案总是存在于上下文中。所以简单地说,我试图预测开始索引和结束索引和答案。
  3. 我出于同样的目的转换了数据集。我在执行标记化后添加了单词级别的开始索引和结束索引。这是我的数据集的外观, 在此处输入图像描述

  4. 接下来,我根据拥抱面部文档指南对问题和上下文进行编码并返回 input_ids、attention_ids 和 token_type_ids;这将用作模型的输入。

def tokenize(questions, contexts):
  input_ids, input_masks, input_segments = [],[],[]
  for question,context in tqdm_notebook(zip(questions, contexts)):
      inputs = tokenizer.encode_plus(question,context, add_special_tokens=True, max_length=512, pad_to_max_length=True,return_attention_mask=True, return_token_type_ids=True )
      input_ids.append(inputs['input_ids'])
      input_masks.append(inputs['attention_mask'])
      input_segments.append(inputs['token_type_ids'])

  return [np.asarray(input_ids, dtype='int32'), np.asarray(input_masks, dtype='int32'), np.asarray(input_segments, dtype='int32')]
  1. 最后,我定义了一个 Keras 模型,它接受这三个输入并预测两个值,即给定上下文中答案的开始和结束词索引。
input_ids_in = tf.keras.layers.Input(shape=(512,), name='input_token', dtype='int32')
input_masks_in = tf.keras.layers.Input(shape=(512,), name='masked_token', dtype='int32')
input_segment_in = tf.keras.layers.Input(shape=(512,), name='segment_token', dtype='int32')
embedding_layer = transformer_model({'inputs':input_ids_in,'attention_mask':input_masks_in,
                                     'token_type_ids':input_segment_in})[0]
X = tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(50, return_sequences=True, dropout=0.1, recurrent_dropout=0.1))(embedding_layer)
X = tf.keras.layers.GlobalMaxPool1D()(X)

start_branch = tf.keras.layers.Dense(1024, activation='relu')(X)
start_branch = tf.keras.layers.Dropout(0.3)(start_branch)
start_branch_output = tf.keras.layers.Dense(512, activation='softmax', name='start_branch')(start_branch)

end_branch = tf.keras.layers.Dense(1024, activation='relu')(X)
end_branch = tf.keras.layers.Dropout(0.3)(end_branch)
end_branch_output = tf.keras.layers.Dense(512, activation='softmax', name='end_branch')(end_branch)


model = tf.keras.Model(inputs=[input_ids_in, input_masks_in, input_segment_in], outputs = [start_branch_output, end_branch_output])

我正在使用具有 512 个单位的最后一个 softmax 层,因为这是我的最大单词数,我的目标是预测索引 dromit。

标签: tensorflowkerasnlphuggingface-transformers

解决方案


推荐阅读