【问题标题】:Converting a TensorFlow sess.run to a @tf.function将 TensorFlow sess.run 转换为 @tf.function
【发布时间】:2019-10-26 18:49:15
【问题描述】:

如何编辑 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})

我阅读了over here 的文档并了解到您必须更改这样的函数:

  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)

但我不知道如何更改第一个。

这里有一点上下文,我在尝试this 代码实验室,并在其中发现sess.run,这给我带来了麻烦。

This is the command line output when running the label_images file.

And this is the function that gave errors.

【问题讨论】:

    标签: python tensorflow tensorflow2.0


    【解决方案1】:

    使用 TensorFlow 1.x,我们曾经创建 tf.placeholder 张量,数据可以通过这些张量进入图表。我们使用了feed_dict=tf.Session() 对象。

    在 TensorFlow 2.0 中,我们可以直接将数据提供给图形,因为默认情况下启用了 Eager Execution。使用@tf.function 注解,我们可以将函数直接包含在我们的图中。 official docs 说,

    此次合并的核心是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 带注释的函数中。

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多