tensorflow - 如何使用 Tensorflow 后端从头开始训练任何 Hugging face 转换器模型(例如 DistilBERT)以回答问题?
问题描述
我想了解如何为问答系统和 TensorFlow 作为后端训练一个拥抱人脸转换器模型(如 BERT、DistilBERT 等)。以下是我目前使用的逻辑(但我不确定它是否正确):
- 我正在使用 SQuAD v1.1 数据集。
- 在 SQuAd 数据集中,任何问题的答案总是存在于上下文中。所以简单地说,我试图预测开始索引和结束索引和答案。
接下来,我根据拥抱面部文档指南对问题和上下文进行编码并返回 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')]
- 最后,我定义了一个 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。
解决方案
推荐阅读
- java - Java字符串操作空格
- c# - SQL Server to .Net Decimals with EF6 dDatabase 第一个问题
- android - certificatePinner 无法使用 okhttp 抛出 SSLHandshakeException:CertPathValidatorException 未找到证书路径的信任锚
- vb.net - VB 表达式帮助在 UiPath 中搜索抓取的数据
- excel - 列到行(形成新行)
- python - 如何根据第一个值Python替换已排序的元组列表中的元组
- r - R 有 Zlib 吗?原始膨胀函数 - 如何解压缩十六进制值
- angular - 有没有办法在 ng For 中搜索
- c# - 如何发布包含 Iformfile 的视图模型数组的表单?
- php - 按 id 合并数组并考虑具有重复关联索引的唯一值