在TensorFlow2.x中执行TensorFlow1.x代码的静态图执行模式

在TensorFlow2.x中执行TensorFlow1.x代码的静态图执行模式

改为图执行模式
在这里插入图片描述
TensorFlow2虽然和TensorFlow1.x有较大差异,不能直接兼容。但实际上还是提供了对TensorFlow1.x的API支持


TensorFlow 2中执行或开发TensorFlow1.x代码,可以做如下处理:

  1. 导入TensorFlow时使用
import tensorflow.compat.v1 as tf
  1. 禁用即时执行模式
tf.disable_eager_execution()

简单两步即可

举例

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()

node1 = tf.constant(3.0)
node2 = tf.constant(4.0)
node3 = tf.add(node1,node2)
print(node3)

由于是图执行模式,这时仅仅是建立了计算图,但没有执行

定义好计算图后,需要建立一个Session,使用会话对象来实现执行图的执行

sess = tf.Session()
print("node1:",sess.run(node1))
print("node2:",sess.run(node2))
print("node3:",sess.run(node3))
Session.close()

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_45176548/article/details/114343184