我正试图利用tensorflow_hub中的预训练BERT模型实现一个自定义分类器。 我正面临一个问题,我不知道如何解决它
代码如下:
class BERTClassifier(tf.keras.models.Model):
def __init__(self):
super(BERTClassifier, self).__init__()
self.preprocessing_layer = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', name='preprocessing')
self.encoder = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3', trainable=True, name='BERT_encoder')
def call(self, inputs):
x = self.preprocessing_layer(inputs)
x = self.encoder(x)
x = x['outputs']
return x
bert_clf = BERTClassifier('small_bert/bert_en_uncased_L-8_H-768_A-12', 'small_bert/bert_en_uncased_L-8_H-768_A-12')
bert_clf.predict(np.array(tf.reshape(["[CLS] Hello world [SEP]"])
我希望predict方法会返回句子的嵌入,但当我运行代码时,我会得到以下错误:
ValueError: Could not find matching function to call loaded from the SavedModel. Got:
Positional arguments (3 total):
* Tensor("inputs:0", shape=(None, 1), dtype=string)
* False
* None
Keyword arguments: {}
Expected these arguments to match one of the following 4 option(s):
Option 1:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='sentences')
* False
* None
Keyword arguments: {}
Option 2:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='sentences')
* True
* None
Keyword arguments: {}
Option 3:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='inputs')
* False
* None
Keyword arguments: {}
Option 4:
Positional arguments (3 total):
* TensorSpec(shape=(None,), dtype=tf.string, name='inputs')
* True
* None
Keyword arguments: {}
有什么问题?我怎样才能解决它? 提前谢谢大家
我想问题是您正在定义
call
,但正在执行predict
,这已经由您正在扩展的keras模型定义。我不得不像这样更新你的代码片段:请注意,编码器的输出存储在
pooled_output
中,但也有一个sequence_output
条目。有关这两方面的更多信息,请参见on the documentation page of the model相关问题 更多 >
编程相关推荐