Dav*_*tia 1 python machine-learning tensorflow
我想给函数serving_input_receiver_fn 添加一些参数,因为特征数组的大小取决于模型。问题是serving_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)
Run Code Online (Sandbox Code Playgroud)
所以,我希望大小([25])、特征名称('words')和接收器的名称('inputs')可以是变量。有机会在这个函数中有参数吗?或另一种方法来做到这一点?
使用嵌套函数或闭包怎么样?
>>> 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>
Run Code Online (Sandbox Code Playgroud)
这样,serving_input_receiver_fn就可以访问传递给create_serving_fn.