【发布时间】:2020-11-16 16:36:39
【问题描述】:
我想使用 bert 的 hidden_states 作为下一层的输入,并使用 keras.Model 构建它。但是bert只返回最后一层和pooler的输出。
这是我尝试过的代码:
def _def_input():
input_ids = Input(batch_shape=(None, 256), name='input_ids', dtype='int32')
input_type_ids = Input(batch_shape=(None, 256), name='input_type_ids', dtype='int32')
attention_mask = Input(batch_shape=(None, 256), name='attention_mask', dtype='int32')
return [input_ids, input_type_ids, attention_mask]
config = BertConfig.from_pretrained("bert-base-multilingual-cased", output_hidden_states=True)
model = TFBertModel.from_pretrained("bert-base-multilingual-cased", config=config)
inputs = _def_input()
out = model({'input_ids': inputs[0],
'token_type_ids': inputs[1],
'attention_mask': inputs[2]})
print(f'Out len: {len(out)}')
print(f'Out: {out}')
print(model.config)
这是输出:
Out len: 2
Out: (<tf.Tensor 'tf_bert_model_10/Identity:0' shape=(None, 256, 768) dtype=float32>, <tf.Tensor 'tf_bert_model_10/Identity_1:0' shape=(None, 768) dtype=float32>)
BertConfig {
"architectures": [
"BertForMaskedLM"
],
"attention_probs_dropout_prob": 0.1,
"directionality": "bidi",
"gradient_checkpointing": false,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.1,
"hidden_size": 768,
"initializer_range": 0.02,
"intermediate_size": 3072,
"layer_norm_eps": 1e-12,
"max_position_embeddings": 512,
"model_type": "bert",
"num_attention_heads": 12,
"num_hidden_layers": 12,
"output_hidden_states": true,
"pad_token_id": 0,
"pooler_fc_size": 768,
"pooler_num_attention_heads": 12,
"pooler_num_fc_layers": 3,
"pooler_size_per_head": 128,
"pooler_type": "first_token_transform",
"type_vocab_size": 2,
"vocab_size": 119547
}
【问题讨论】:
标签: python tensorflow keras huggingface-transformers