超过两个输入的 TF BERT 输入打包器

TF BERT input packer on more than two inputs

一些使用 BERT 模型的 TensorFlow 示例展示了如何使用 BERT 预处理器“打包”输入。例如。在 this example

text_preprocessed = bert_preprocess.bert_pack_inputs([tok, tok], tf.constant(20))

文档暗示这对两个以上的输入句子同样有效,这样(我希望)一个人可以做这样的事情:

text_preprocessed = bert_preprocess.bert_pack_inputs([tok, tok, tok], tf.constant(20))

但是,这样做会导致此 post 底部 [1] 的错误。

我知道没有匹配的签名;如果我没看错(我可能没看懂!),会有一个签名用于单个输入和一个用于两个。但是,如上面的 colab 中所建议的,将两个以上的句子打包到适合分类任务的输入中的推荐方法是什么?

1.

ValueError: Could not find matching function to call loaded from the SavedModel. Got:
  Positional arguments (2 total):
    * [tf.RaggedTensor(values=tf.RaggedTensor(values=Tensor("inputs:0", shape=(None,), dtype=int32), row_splits=Tensor("inputs_2:0", shape=(None,), dtype=int64)), row_splits=Tensor("inputs_1:0", shape=(2,), dtype=int64)), tf.RaggedTensor(values=tf.RaggedTensor(values=Tensor("inputs_3:0", shape=(None,), dtype=int32), row_splits=Tensor("inputs_5:0", shape=(None,), dtype=int64)), row_splits=Tensor("inputs_4:0", shape=(2,), dtype=int64)), tf.RaggedTensor(values=tf.RaggedTensor(values=Tensor("inputs_6:0", shape=(None,), dtype=int32), row_splits=Tensor("inputs_8:0", shape=(None,), dtype=int64)), row_splits=Tensor("inputs_7:0", shape=(2,), dtype=int64))]
    * Tensor("seq_length:0", shape=(), dtype=int32)
  Keyword arguments: {}

Expected these arguments to match one of the following 4 option(s):

Option 1:
  Positional arguments (2 total):
    * [RaggedTensorSpec(TensorShape([None, None]), tf.int32, 1, tf.int64)]
    * TensorSpec(shape=(), dtype=tf.int32, name='seq_length')
  Keyword arguments: {}

Option 2:
  Positional arguments (2 total):
    * [RaggedTensorSpec(TensorShape([None, None]), tf.int32, 1, tf.int64), RaggedTensorSpec(TensorShape([None, None]), tf.int32, 1, tf.int64)]
    * TensorSpec(shape=(), dtype=tf.int32, name='seq_length')
  Keyword arguments: {}

Option 3:
  Positional arguments (2 total):
    * [RaggedTensorSpec(TensorShape([None, None, None]), tf.int32, 2, tf.int64), RaggedTensorSpec(TensorShape([None, None, None]), tf.int32, 2, tf.int64)]
    * TensorSpec(shape=(), dtype=tf.int32, name='seq_length')
  Keyword arguments: {}

Option 4:
  Positional arguments (2 total):
    * [RaggedTensorSpec(TensorShape([None, None, None]), tf.int32, 2, tf.int64)]
    * TensorSpec(shape=(), dtype=tf.int32, name='seq_length')
  Keyword arguments: {}```

BERT 模型需要特定的输入形状。

工作示例代码:

bert_preprocess = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3")
bert_encoder = hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4",trainable=True)

def get_sentence_embeding(sentences):
    preprocessed_text = bert_preprocess(sentences)
    return bert_encoder(preprocessed_text)['pooled_output']

get_sentence_embeding([
    "How to find which version of TensorFlow is", 
    "TensorFlow not found using pip"]
)