TensorFlow Serving图像预测时reshape维度与JSON序列化问题如何解决
问题根因
你遇到的两个报错的核心逻辑如下:
TypeError: Object of type EagerTensor is not JSON serializable是因为JSON格式无法识别TensorFlow的EagerTensor类型,必须转为Python原生的列表/数值类型才能序列化- reshape维度报错和
tolist调用无关,该方法不会改变数据的嵌套维度,本质是你传入的图像总元素数为10000,和模型要求的输入总元素数(784的倍数,对应28*28的输入尺寸)不匹配
解决方法
步骤1:修正输入图像尺寸与模型要求对齐
先将输入图像预处理为模型训练时的输入尺寸,示例代码如下:
# 假设模型要求输入为28*28的灰度图,按你的实际模型输入调整参数 temp_image = tf.image.resize(temp_image, (28, 28)) temp_image = tf.image.rgb_to_grayscale(temp_image) # 非灰度图可省略这行 reshaped_array = tf.expand_dims(temp_image, 0)
你可以先打印reshaped_array.shape确认维度是否符合要求,单张图的总元素数要等于784或784的倍数。
步骤2:正确处理EagerTensor的序列化
将EagerTensor先转为numpy数组再转列表即可解决序列化问题,修改后的make_prediction函数如下:
import json import requests import tensorflow as tf # server URL url = 'http://localhost:8501/v1/models/img_classifier:predict' def make_prediction(instances): # 先转numpy数组再转列表,不会改变维度且能被JSON序列化 data = json.dumps({"signature_name": "serving_default", "instances": instances.numpy().tolist()}) headers = {"content-type": "application/json"} json_response = requests.post(url, data=data, headers=headers) print(json_response.text) predictions = json.loads(json_response.text)['predictions'] return predictions
内容的提问来源于stack exchange,提问作者Joseph Adam
相关产品推荐
相关产品推荐

