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

如何构造带context和examples格式的TensorFlow Serving gRPC Regress请求

解决方案

核心思路

TF Serving的gRPC接口原生支持Classify和Regress请求类型,不需要基于Predict接口改造,可直接匹配你当前使用的context+examples的输入格式,无需使用tf.make_tensor_proto构造张量参数。

实现步骤

1. 依赖导入

import grpc
import tensorflow as tf
from tensorflow_serving.apis import classification_pb2
from tensorflow_serving.apis import classification_service_pb2_grpc
from tensorflow_serving.apis import model_pb2

如果使用Regress接口,将classification替换为regression导入对应类即可。

2. 构造context和examples的tf.Example对象

# 构造全局context的tf.Example,对应REST请求的context字段
context = tf.train.Example(
    features=tf.train.Features(
        feature={
            "feature_name3": tf.train.Feature(int64_list=tf.train.Int64List(value=[123])),
            "feature_name4": tf.train.Feature(float_list=tf.train.FloatList(value=[0.1, 0.2]))
        }
    )
)

# 构造样本列表,对应REST请求的examples字段
examples = []
# 第一条样本
example1 = tf.train.Example(
    features=tf.train.Features(
        feature={
            "feature_name1": tf.train.Feature(bytes_list=tf.train.BytesList(value=[b"sample1"])),
            "feature_name2": tf.train.Feature(float_list=tf.train.FloatList(value=[1.5, 2.5]))
        }
    )
)
examples.append(example1)
# 第二条样本
example2 = tf.train.Example(
    features=tf.train.Features(
        feature={
            "feature_name1": tf.train.Feature(bytes_list=tf.train.BytesList(value=[b"sample2"])),
            "feature_name2": tf.train.Feature(float_list=tf.train.FloatList(value=[3.5, 4.5]))
        }
    )
)
examples.append(example2)

3. 构造gRPC请求并发送

# 初始化gRPC连接
channel = grpc.insecure_channel("TF_Serving服务地址:端口")
stub = classification_service_pb2_grpc.ClassificationServiceStub(channel)

# 构造分类请求
request = classification_pb2.ClassificationRequest()
# 配置模型信息
request.model_spec.name = "你的部署模型名"
request.model_spec.signature_name = "你使用的签名名称" # 对应REST请求的signature_name
# 传入context和样本列表
request.input.context.CopyFrom(context)
request.input.examples.extend([e.SerializeToString() for e in examples])

# 发送请求获取结果
response = stub.Classify(request)
print(response)

注意事项

  • 特征类型需和模型导出时定义的特征类型严格对齐,整数用Int64List、浮点数用FloatList、字符串用BytesList
  • context中定义的特征不要在examples中重复声明,TF Serving会自动将context特征合并到每一条样本中
  • 模型签名名需要和导出SavedModel时指定的Classify/Regress签名对应,不要错用Predict签名

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:27:00