Python TensorFlow,计算图,创建计算图,Graph,运算操作(op)

TensorFlow中封装的函数基本上都是运算操作(op):


demo.py(计算图,创建计算图,Graph):

import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'  # 设置警告级别


# TensorFlow程序中,系统会自动维护一个默认的计算图。 (所有的张量(tensor)和运算操作(op)都会转换成计算图中的一部分)
# 计算图就是一块内存空间,维护张量和运算操作,不同的计算图不能共享张量和运算操作。

a = tf.constant(5.0)  # 张量a自动属于默认计算图。 TensorFlow中封装的函数都是运算操作(op),例如:constant()/add()等。

# 获取默认的计算图。
graph = tf.get_default_graph()
print(graph)  # <tensorflow.python.framework.ops.Graph object at 0x7f87355c7d68>

# 会话(运行计算图的类,使用默认注册的图(也可以手动指定计算图),一个会话只能运行一个计算图)
with tf.Session() as sess:
    # 查看张量所属的计算图
    print(a.graph)  # <tensorflow.python.framework.ops.Graph object at 0x7f87355c7d68>
    print(sess.graph)  # <tensorflow.python.framework.ops.Graph object at 0x7f87355c7d68>


# 也可以手动创建计算图。
new_graph = tf.Graph()
print(new_graph)  # <tensorflow.python.framework.ops.Graph object at 0x7f771c9dae48>

# 在新创建的计算图中添加张量
with new_graph.as_default():
    b = tf.constant(6.0)
    print(b.graph)  # <tensorflow.python.framework.ops.Graph object at 0x7f771c9dae48>

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/88087801