[英]Converting a TensorFlow sess.run to a @tf.function
如何编辑sessions.run
function 使其在 Tensorflow 2.0 上运行?
with tf.compat.v1.Session(graph=graph) as sess:
start = time.time()
results = sess.run(output_operation.outputs[0],
{input_operation.outputs[0]: t})
我在这里阅读了文档,了解到您必须像这样更改 function:
normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])
sess = tf.compat.v1.Session()
result = sess.run(normalized)
return result
对此:
def myFunctionToReplaceSessionRun(resized,input_mean,input_std):
return tf.divide(tf.subtract(resized, [input_mean]), [input_std])
normalized = myFunctionToReplaceSessionRun(resized,input_mean,input_std)
但我无法弄清楚如何改变第一个。
这里有一些上下文,我正在尝试这个代码实验室,并在其中发现sess.run
,这给我带来了麻烦。
在 TensorFlow 1.x 中,我们曾经创建tf.placeholder
张量,数据可以通过该张量进入图表。 我们使用feed_dict=
和tf.Session()
object。
在 TensorFlow 2.0 中,我们可以直接将数据提供给图形,因为默认情况下启用了急切执行。 使用@tf.function
注释,我们可以将 function 直接包含在我们的图中。 官方文档说,
此合并的中心是
tf.function
,它允许您将 Python 语法的子集转换为可移植的高性能 TensorFlow 图。
这是文档中的一个简单示例,
@tf.function
def simple_nn_layer(x, y):
return tf.nn.relu(tf.matmul(x, y))
x = tf.random.uniform((3, 3))
y = tf.random.uniform((3, 3))
simple_nn_layer(x, y)
现在,查看您的问题,您可以将您的 function 转换为,
@tf.function
def get_output_operation( input_op ):
# The function goes here
# from here return `results`
results = get_output_operation( some_input_op )
简而言之,占位符张量转换为 function arguments, sess.run( tensor )
tensor
的张量由 ZC1C425268E68385D1AB5074C17ZA9 返回。 所有这些都发生在@tf.function
注释 function 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.