[英]How to using the pre-trained bert model as embedding layer in my model?
I'm using this pre-trained model by bert-for-tf2 in my functional model like following:我在我的功能 model 中使用由 bert-for-tf2 预训练的 model ,如下所示:
def build_model(model_dir, batch_size, max_seq_num, max_seq_len):
bert_params = bert.params_from_pretrained_ckpt(model_dir)
l_bert = bert.BertModelLayer.from_params(bert_params, name="bert", trainable=False)
input_ids = tf.keras.layers.Input(shape=(max_seq_num, max_seq_len,), dtype='int32', name='input_ids')
reshaped_input_ids = tf.reshape(input_ids, (batch_size * max_seq_num, max_seq_len))
token_type_ids = tf.keras.layers.Input(shape=(max_seq_num, max_seq_len,), dtype='int32', name='token_type')
reshaped_token_type_ids = tf.reshape(token_type_ids, (batch_size * max_seq_num, max_seq_len))
mask_ids = tf.keras.layers.Input(shape=(max_seq_num, max_seq_len,), dtype='int32', name='mask_ids')
reshaped_mask_ids = tf.reshape(mask_ids, (batch_size * max_seq_num, max_seq_len))
# provide a custom token_type/segment id as a layer input
bert_embedd = l_bert([reshaped_input_ids, reshaped_token_type_ids], mask=reshaped_mask_ids) # [batch_size*max_seq_num, max_seq_len, hidden_size]
model = tf.keras.models.Model(inputs=[input_ids, token_type_ids, mask_ids], outputs=bert_embedd)
model.build(input_shape=[(batch_size, max_seq_num, max_seq_len),
(batch_size, max_seq_num, max_seq_len),
(batch_size, max_seq_num, max_seq_len)])
bert.load_bert_weights(l_bert, os.path.join(model_dir, "bert_model.ckpt")) # should be called after model.build()
model.summary()
tf.keras.utils.plot_model(model, show_shapes=True)
learning_rate = 1e-2
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
loss=tf.keras.losses.MeanSquaredError(), metrics=['mse'])
return model
I can build the model succeed.我可以成功构建 model。 But when I fed data to the model:
但是当我将数据输入 model 时:
model = build_model(path, 16, 16, 16)
x_input = np.random.randint(0, 10000, size=[16, 16, 16])
x_token_type = [[[i] * 16 for i in range(16)] for _ in range(16)]
x_mask = np.ones(shape=[16, 16, 16])
y_predict = model(x_input, x_token_type, x_mask)
the error appears:出现错误:
ValueError: Layer model expects 2 input(s), but it received 1 input tensors. Inputs received: ...
In the last instruction:在最后一条指令中:
"y_predict = model(x_input, x_token_type, x_mask)" “y_predict = 模型(x_input,x_token_type,x_mask)”
2 inputs have been expected, but you provide one input.预期有 2 个输入,但您提供了 1 个输入。
I think you have 3 inputs x_input, x_token_type, and x_mask.我认为您有 3 个输入 x_input、x_token_type 和 x_mask。 If you want to train your model try this:
如果你想训练你的 model 试试这个:
model.fit([x_input, x_token_type, x_mask]) model.fit([x_input, x_token_type, x_mask])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.