我按照建议的 by Google's tensor2tensor repository 遵循了翻译 colab notebook 教程
导出模型并将其上传到 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"]
我试过将张量转换为 numpy 但仍然没有运气。有人能指出我正确的方向吗?
最佳答案
问题在于,当您执行以下操作时,TensorFlow 会返回一个 EagerTensor:
inputs = encoders["inputs"].encode(input_str) + [1] # add EOS id
batch_inputs = tf.reshape(inputs, [1, -1, 1])
并且 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!
我无法为您的具体情况提供示例,因为您的代码片段不够完整。但return {"inputs": batch_inputs.numpy().tolist()}
应该做的工作。
关于python - 翻译模型预测 : TypeError: Object of type 'EagerTensor' is not JSON serializable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58220123/