tensorflow - 使用 BERT (TF 1.x) 保存的模型执行推理

标签 tensorflow tensorflow-serving tensorflow-estimator

我被困在一行代码上,结果整个周末都在一个项目上停滞不前。

我正在从事一个使用 BERT 进行句子分类的项目。我已成功训练模型,我可以使用 run_classifier.py 中的示例代码测试结果。

我可以使用这个示例代码导出模型(已被多次重新发布,所以我相信它适合这个模型):

def export(self):
  def serving_input_fn():
    label_ids = tf.placeholder(tf.int32, [None], name='label_ids')
    input_ids = tf.placeholder(tf.int32, [None, self.max_seq_length], name='input_ids')
    input_mask = tf.placeholder(tf.int32, [None, self.max_seq_length], name='input_mask')
    segment_ids = tf.placeholder(tf.int32, [None, self.max_seq_length], name='segment_ids')
    input_fn = tf.estimator.export.build_raw_serving_input_receiver_fn({
        'label_ids': label_ids, 'input_ids': input_ids,
        'input_mask': input_mask, 'segment_ids': segment_ids})()
    return input_fn
  self.estimator._export_to_tpu = False
  self.estimator.export_savedmodel(self.output_dir, serving_input_fn)

我还可以加载导出的估算器(其中导出函数将导出的模型保存到标有时间戳的子目录中):

predict_fn = predictor.from_saved_model(self.output_dir + timestamp_number)

但是,对于我来说,我无法弄清楚向 predict_fn 提供什么作为推理输入。这是我目前最好的代码:

def predict(self):
  input = 'Test input'
  guid = 'predict-0'
  text_a = tokenization.convert_to_unicode(input)
  label = self.label_list[0]
  examples = [InputExample(guid=guid, text_a=text_a, text_b=None, label=label)]
  features = convert_examples_to_features(examples, self.label_list,
    self.max_seq_length, self.tokenizer)
  predict_input_fn = input_fn_builder(features, self.max_seq_length, False)
  predict_fn = predictor.from_saved_model(self.output_dir + timestamp_number)
  result = predict_fn(predict_input_fn)       # this generates an error
  print(result)

我向 predict_fn 提供什么似乎并不重要:examples 数组、features 数组、predict_input_fn 函数。显然,predict_fn 需要某种类型的字典 - 但由于张量不匹配或其他通常意味着输入错误的错误,我尝试过的每一件事都会产生异常。

我假设 from_saved_model 函数需要与模型测试函数相同类型的输入 - 显然,事实并非如此。

似乎很多人都问过这个问题——“我如何使用导出的 BERT TensorFlow 模型进行推理?” - 没有得到任何答案:

Thread #1

Thread #2

Thread #3

Thread #4

有什么帮助吗?提前致谢。

最佳答案

谢谢你的帖子。你的 serving_input_fn 正是我所缺少的!您的 predict 函数需要更改为直接提供特征字典,而不是使用 predict_input_fn:

def predict(sentences):
    labels = [0, 1]
    input_examples = [
        run_classifier.InputExample(
            guid="",
            text_a = x,
            text_b = None,
            label = 0
        ) for x in sentences] # here, "" is just a dummy label
    input_features = run_classifier.convert_examples_to_features(
        input_examples, labels, MAX_SEQ_LEN, tokenizer
    )
    # this is where pred_input_fn is replaced
    all_input_ids = []
    all_input_mask = []
    all_segment_ids = []
    all_label_ids = []

    for feature in input_features:
        all_input_ids.append(feature.input_ids)
        all_input_mask.append(feature.input_mask)
        all_segment_ids.append(feature.segment_ids)
        all_label_ids.append(feature.label_id)
    pred_dict = {
        'input_ids': all_input_ids,
        'input_mask': all_input_mask,
        'segment_ids': all_segment_ids,
        'label_ids': all_label_ids
    }
    predict_fn = predictor.from_saved_model('../testing/1589418540')
    result = predict_fn(pred_dict)
    print(result)
pred_sentences = [
  "That movie was absolutely awful",
  "The acting was a bit lacking",
  "The film was creative and surprising",
  "Absolutely fantastic!",
]
predict(pred_sentences)
{'probabilities': array([[-0.3579178 , -1.2010787 ],
       [-0.36648935, -1.1814401 ],
       [-0.30407643, -1.3386648 ],
       [-0.45970002, -0.9982413 ],
       [-0.36113673, -1.1936386 ],
       [-0.36672896, -1.1808994 ]], dtype=float32), 'labels': array([0, 0, 0, 0, 0, 0])}

但是,pred_sentences 中的句子返回的概率与我使用 estimator.predict(predict_input_fn) 得到的概率不匹配,其中 estimator 是在同一(python) session 中使用的微调模型。例如,使用 estimator 的 [-0.27276006, -1.4324446 ] 与使用 predictor 的 [-0.26713806, -1.4505868 ]。

关于tensorflow - 使用 BERT (TF 1.x) 保存的模型执行推理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61310331/

相关文章:

python - Tensorflow 2.0.0-alpha0 : tf. logging.set_verbosity

python - Keras 的 Expand_dims 函数导致张量丢失元数据

tensorflow - 如何卡住特定于设备的保存模型?

python - tensorflow 错误 : unsupported callable

python - 属性错误: 'NoneType' object has no attribute 'dtype'

testing - Tensorflow batch_norm 在测试时无法正常工作(is_training=False)

python - 服务 TensorFlow 预构建的线性分类器估计器模型

python - Tensorflow服务容器进入事件循环后Heroku Dyno崩溃

python - 如何在 Estimator 训练期间动态加载数据集的新部分?

python - 如何正确组合 tf.data.Dataset 和 tf.estimator.DNNRegressor