翻译模型预测:类型错误:“EagerTensor”类型的对象不可 JSON 序列化

ech*_*n00 7 python tensorflow tensor2tensor

我已按照 Google 张量2张量存储库的建议遵循翻译 colab 笔记本教程

导出模型并将其上传到 Google 的 AI Platform 引擎进行在线预测后,我在向模型发出请求时遇到了问题。

我相信翻译模型的输入是源文本的张量。但我收到一个错误TypeError: Object of type 'EagerTensor' is not JSON serializable


def encode(input_str, output_str=None):
  """Input str to features dict, ready for inference"""
  inputs = encoders["inputs"].encode(input_str) + [1]  # add EOS id
  batch_inputs = tf.reshape(inputs, [1, -1, 1])  # Make it 3D.
  return {"inputs": batch_inputs}

enfr_problem = problems.problem(PROBLEM)
encoders = enfr_problem.feature_encoders(DATA_DIR)

encoded_inputs = encode("Some text")
model_output = predict_json('project_name','model_name', encoded_inputs,'version_1')["outputs"]
Run Code Online (Sandbox Code Playgroud)

我尝试将张量转换为 numpy 但仍然没有成功。有人能指出我正确的方向吗?

ccs*_*mnn 6

问题是,当您执行以下操作时,TensorFlow 将返回 EagerTensor:

inputs = encoders["inputs"].encode(input_str) + [1]  # add EOS id
batch_inputs = tf.reshape(inputs, [1, -1, 1])
Run Code Online (Sandbox Code Playgroud)

并且EagerTensor无法转换为JSON。不幸的是,3D numpy 数组也无法转换为 JSON。但 numpy 数组可以轻松转换为列表。一个例子:

import json
import numpy as np
import tensorflow as tf

a = np.array([1, 2, 3])
b = np.array([1, 2, 3])
c = tf.multiply(a, b)

print(c)  # -> <tf.Tensor: shape=(3,), dtype=int64, numpy=array([1, 4, 9])>
print(c.numpy())  # -> array([1, 4, 9])
print(c.numpy().tolist())  # -> [1, 4, 9]

with open("example.json", "w") as f:
   json.dump(c, f)  # TypeError: Object of type EagerTensor is not JSON serializable
   json.dump(c.numpy(), f)  # TypeError: Object of type ndarray is not JSON serializable
   json.dump(c.numpy().tolist(), f)  # works!
Run Code Online (Sandbox Code Playgroud)

我无法为您的具体情况提供示例,因为您的代码片段不够完整。但

return {"inputs": batch_inputs.numpy().tolist()}
Run Code Online (Sandbox Code Playgroud)

应该做这项工作。