如何创建具有多个功能的Tensorflow服务_输入_接收器_fn?

时间:2019-01-18 14:54:18

标签: tensorflow tensorflow-serving

TF guide on saving models中,serving_input_receiver_fn上有一个段落讨论了实现预处理逻辑的功能。我正在尝试对DNNRegressor的输入数据进行一些标准化。他们的函数代码如下:

feature_spec = {'foo': tf.FixedLenFeature(...),
                'bar': tf.VarLenFeature(...)}

def serving_input_receiver_fn():
  """An input receiver that expects a serialized tf.Example."""
  serialized_tf_example = tf.placeholder(dtype=tf.string,
                                         shape=[default_batch_size],
                                         name='input_example_tensor')
  receiver_tensors = {'examples': serialized_tf_example}
  features = tf.parse_example(serialized_tf_example, feature_spec)
  return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)

我的代码如下:

feat_cols = [
    tf.feature_column.numeric_column(key="FEATURE1"),
    tf.feature_column.numeric_column(key="FEATURE2")
]

def serving_input_receiver_fn():
    feature_spec = tf.feature_column.make_parse_example_spec(feat_cols)

    default_batch_size = 1

    serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[default_batch_size], name='tf_example')

    receiver_tensors = { 'examples': serialized_tf_example}

    features = tf.parse_example(serialized_tf_example, feature_spec)

    fn_norm1 = lamba FEATURE1: normalize_input_data('FEATURE1', FEATURE1)
    fn_norm2 = lamba FEATURE2: normalize_input_data('FEATURE2', FEATURE2)
    features['FEATURE1'] = tf.map_fn(fn_norm1, features['FEATURE1'], dtype=tf.float32)
    features['FEATURE2'] = tf.map_fn(fn_norm2, features['FEATURE2'], dtype=tf.float32)

    return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)

所有已保存的模型在图中都没有我的特征。我想弄清楚如果您要通过的功能不只一个,那么这是如何工作的。

我使用keras MPG数据创建了一个示例。 It is located here

1 个答案:

答案 0 :(得分:0)

features中的

ServingInputReceiver被直接传递给您的模型函数。您想要的是receive_tensorsreceive_tensor_alternatives,即ServingInputReceiver构造函数的第二个和第三个参数。

例如,您可以这样做

serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[default_batch_size], name='tf_example')

receiver_tensors = { 'examples': serialized_tf_example}

raw_features = tf.parse_example(serialized_tf_example, feature_spec)

fn_norm1 = lamba FEATURE1: normalize_input_data('FEATURE1', FEATURE1)
fn_norm2 = lamba FEATURE2: normalize_input_data('FEATURE2', FEATURE2)
features['FEATURE1'] = tf.map_fn(fn_norm1, raw_features['FEATURE1'], dtype=tf.float32)
features['FEATURE2'] = tf.map_fn(fn_norm2, raw_features['FEATURE2'], dtype=tf.float32)
return tf.estimator.export.ServingInputReceiver(
      features=features,
      receiver_tensors=receiver_tensors,
      receiver_tensors_alternatives={'SOME_KEY': raw_features})

如果您不需要向网络提供Example原型,则可以完全跳过它。

raw_features = {'FEATURE1': tf.placeholder(...), 'FEATURE2': tf.placeholder(...)}
features = preprepocess(raw_features)
return tf.estimator.export.ServingInputReceiver(features, {'SOME_OTHER_KEY': raw_features})