【问题标题】:How to use TFBertModel's hidden states as part of custom Keras model?如何使用 TFBertModel 的隐藏状态作为自定义 Keras 模型的一部分?
【发布时间】: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


    【解决方案1】:

    您使用的转换器是什么版本的?我遇到了同样的问题,将变压器降级到 2.7.0 解决了我的问题,如以下链接所示:https://github.com/huggingface/transformers/issues/6029

    【讨论】:

      猜你喜欢
      • 2021-05-18
      • 2019-01-27
      • 2019-05-18
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2018-11-11
      相关资源
      最近更新 更多