带参数的Tensorflow serving_input_receiver_fn

时间:2018-01-15 19:17:53

标签: python tensorflow machine-learning

我想在函数serving_input_receiver_fn中添加一些参数,因为要素数组的大小取决于模型。问题是serve_input_receiver_fn的官方定义是:

  

serving_input_receiver_fn:不带参数的函数   返回一个ServingInputReceiver。自定义模型需要。

我对此功能的实现是:

def serving_input_receiver_fn():
    serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[None], name='input_tensors')
    receiver_tensors = {'inputs': serialized_tf_example}
    feature_spec     = {'words': tf.FixedLenFeature([25],tf.int64)}
    features         = tf.parse_example(serialized_tf_example, feature_spec)

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

所以,我希望大小([25]),功能名称('单词')和接收者名称('输入')可以是变量。这个函数有机会有参数吗?或另一种方法吗?

1 个答案:

答案 0 :(得分:1)

如何使用嵌套函数或闭包?

>>> def create_serving_fn(size, feature, inputs):

        def serving_input_receiver_fn():
            serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[None], name='input_tensors')
            receiver_tensors = {inputs: serialized_tf_example}
            feature_spec     = {feature: tf.FixedLenFeature([size],tf.int64)}
            features         = tf.parse_example(serialized_tf_example, feature_spec)    
            return tf.estimator.export.ServingInputReceiver(features, receiver_tensors)
        return serving_input_receiver_fn

    your_serving_fn = create_serving_fn(25, 'words', 'inputs')
    print(your_serving_fn)

<function create_serving_fn.<locals>.serving_input_receiver_fn at 0x7f10df77bf28>

这样,serving_input_receiver_fn可以访问传递给create_serving_fn的参数。