简体   繁体   English

带参数的Tensorflow serving_input_receiver_fn

[英]Tensorflow serving_input_receiver_fn with arguments

I want to add some arguments to the function serving_input_receiver_fn, because the size of the feature array depends of the model. 我想为函数serving_input_receiver_fn添加一些参数,因为特征数组的大小取决于模型。 The problem is that the oficial definition of serving_input_receiver_fn is: 问题是serve_input_receiver_fn的官方定义是:

serving_input_receiver_fn: A function that takes no argument and returns a ServingInputReceiver. serving_input_receiver_fn:不带参数的函数,返回ServingInputReceiver。 Required for custom models. 自定义模型必需。

My implementation of this function is: 我的这个功能的实现是:

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)

So, I want that the size ([25]), the name of the features ('words') and the name of the receiver ('inputs') can be variables. 所以,我希望大小([25]),功能名称('单词')和接收者名称('输入')可以是变量。 There is a chance to have arguments in this function? 这个函数有机会有参数吗? or another way to do this? 或另一种方式来做到这一点?

How about using a nested function or closure? 如何使用嵌套函数或闭包?

>>> 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>

This way, serving_input_receiver_fn has access to arguments passed to create_serving_fn . 这样, serving_input_receiver_fn可以访问传递给create_serving_fn参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM