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

如何向TensorFlow Serving模型发送含稀疏张量的REST API请求?

解决TensorFlow Serving请求稀疏张量输入的格式问题

这个问题我之前也碰到过,核心原因是你用了VarLenFeature定义x和y,这类特征会被解析成SparseTensor,而TF Serving对于稀疏张量的请求格式有特定要求,不是直接传普通数组就能匹配的。你收到的错误就是因为请求里的张量格式和模型图里的不匹配导致的。

正确的请求JSON格式

针对VarLenFeature(稀疏张量),请求里需要用稀疏张量的标准结构,包含三个字段:

  • values: 所有非空的特征值列表(对应你原来的数组内容)
  • indices: 每个值对应的索引(对于一维稀疏张量,就是[[0,0], [0,1], ..., [0,n-1]],这里第一个0表示样本索引,第二个是特征内的位置)
  • dense_shape: 稀疏张量的密集形状,格式为[样本数, 特征长度]

而z是FixedLenFeature,直接传字符串即可。你的请求应该改成这样:

{
  "instances": [
    {
      "x": {
        "values": ["text","text","text","text","text","text"],
        "indices": [[0,0], [0,1], [0,2], [0,3], [0,4], [0,5]],
        "dense_shape": [1, 6]
      },
      "y": {
        "values": ["test","test","test","test","test","test"],
        "indices": [[0,0], [0,1], [0,2], [0,3], [0,4], [0,5]],
        "dense_shape": [1, 6]
      },
      "z": "str"
    }
  ]
}

简化方案:转成密集张量(可选)

如果你觉得稀疏张量的请求格式太繁琐,也可以在导出模型时把稀疏张量转成密集张量,这样就能用你原来的简洁格式请求。只需要修改make_serving_input_fn里的代码,把transformed_features中的稀疏张量转成密集张量:

def make_serving_input_fn(tf_transform_output):
    raw_feature_spec = { 
        'x': tf.io.VarLenFeature(tf.string), 
        'y': tf.io.VarLenFeature(tf.string), 
        'z': tf.io.FixedLenFeature([], tf.string) 
    }
    def serving_input_fn():
        raw_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(raw_feature_spec)
        raw_features = raw_input_fn().features  # 修正了你代码里的拼写错误:raw_reatures -> raw_features
        transformed_features = tf_transform_output.transform_raw_features(raw_features)
        
        # 把稀疏张量转成密集张量,这里用空字符串填充空值,可按需修改
        transformed_features['x'] = tf.sparse.to_dense(transformed_features['x'], default_value="")
        transformed_features['y'] = tf.sparse.to_dense(transformed_features['y'], default_value="")
        
        return tf.estimator.export.ServingInputReceiver(transformed_features, raw_features)
    return serving_input_fn

重新导出模型后,你原来的请求格式就能正常工作了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 06:38:11