You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow Serving输出shape与本地Keras推理结果不一致

问题根源

你返回结果取值逻辑错误,丢失了batch维度。
TensorFlow Serving的predict接口在传入instances参数时,返回的predictions是长度等于输入batch大小的列表,你输入batch是145,这个列表就有145个元素,每个元素对应单条样本的输出字典。你代码里写的res = res.json()['predictions'][0]只取了列表里第一个样本的输出,自然没有batch维度,单条样本下dense5_2输出形状就是(4,),softmax输出形状是(2,),和本地批量推理的(145,4)、(145,2)形状不一致。
另外你调用requests的时候用data=payload传参不会自动做JSON序列化,容易触发请求格式错误,建议改成json=payload传参。

修复方案

方案1:保留instances传参,批量拼接输出

不要取predictions的第一个元素,遍历所有预测结果拼接成带batch维度的张量即可:

img_boxes = get_image_boxes(bboxes, img, height, width, num_boxes, size=24)
img_in = tf.make_tensor_proto(img_boxes)
img_in = tf.make_ndarray(img_in)
print(img_in.shape) # (145, 24, 24, 3)

payload = {'instances': img_in.tolist()}
# 用json参数自动序列化,设置正确请求头
res = requests.post('http://localhost:8501/v1/models/r_net:predict', json=payload)
all_predictions = res.json()['predictions']

# 提取所有样本的输出拼接
probs = tf.convert_to_tensor([item['softmax'] for item in all_predictions])
offsets = tf.convert_to_tensor([item['dense5_2'] for item in all_predictions])
print(probs.shape) # 输出(145, 2)
print(offsets.shape) # 输出(145, 4),和本地推理结果完全一致

方案2:改用inputs传参,直接拿到批量输出

如果不想手动拼接,可以把请求参数的键从instances改成inputs,TF Serving会直接返回按输出层分组的批量结果,不需要遍历:

payload = {'inputs': img_in.tolist()}
res = requests.post('http://localhost:8501/v1/models/r_net:predict', json=payload)
outputs = res.json()['outputs']

probs = tf.convert_to_tensor(outputs['softmax'])
offsets = tf.convert_to_tensor(outputs['dense5_2'])
# 输出形状直接匹配本地推理结果

内容的提问来源于stack exchange,提问作者Dat Le

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 09:24:18