如何编辑sessions.run
函数,使其在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})
我阅读了这里的文档,了解到你必须更改这样的功能:
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
,这给我带来了麻烦。
这是运行label_images
文件时的命令行输出。
这就是产生错误的函数。
使用TensorFlow 1.x,我们曾经创建tf.placeholder
张量,通过这些张量数据可以进入图形。我们使用了feed_dict=
和tf.Session()
对象。
在TensorFlow 2.0中,我们可以直接将数据馈送到图中,因为默认情况下启用了热切执行。使用@tf.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)
现在,研究一下你的问题,你可以转换你的函数,比如
@tf.function
def get_output_operation( input_op ):
# The function goes here
# from here return `results`
results = get_output_operation( some_input_op )
用简单而不太精确的词来说,占位符张量被转换为函数自变量,sess.run( tensor )
中的tensor
由函数返回。所有这些都发生在一个带@tf.function
注释的函数中。