东方耀AI技术分享
标题:
08、TensorFlow图的执行阶段及代码案例_笔记
[打印本页]
作者:
东方耀
时间:
2018-9-11 17:56
标题:
08、TensorFlow图的执行阶段及代码案例_笔记
08、TensorFlow图的执行阶段及代码案例_笔记
# -*- coding: utf-8 -*-
__author__ = 'dongfangyao'
__date__ = '2018/9/10 下午7:33'
__product__ = 'PyCharm'
__filename__ = 'tf02'
import os
import tensorflow as tf
# 这是默认的显示等级,显示所有信息
# os.environ["TF_CPP_MIN_LOG_LEVEL"] = '1'
# 只显示 warning 和 Error
os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2'
# 只显示 Error
# os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'
# 1、定义常量矩阵a b
a = tf.constant([[1, 2], [3, 4]], dtype=tf.int32)
print(type(a))
b = tf.constant([5, 6, 7, 8], dtype=tf.int32, shape=[2, 2])
# 2、以a b 作为输入 进行矩阵的乘法操作
c = tf.matmul(a, b)
print(type(c))
# print(c)
print('变量a是否在默认图中:{}'.format(a.graph is tf.get_default_graph()))
# 使用新的 构建的图 而不是默认图
graph1 = tf.Graph()
with graph1.as_default():
# 此时在这个代码块中,使用的就是新定义的图graph1
d = tf.constant(5.0, name='d')
print('变量d是否在新图graph1中:{}'.format(d.graph is graph1))
print('变量d是否在默认图中:{}'.format(d.graph is tf.get_default_graph()))
graph2 = tf.Graph()
with graph2.as_default():
e = tf.constant(3.0, name='e')
print('变量e是否在新图graph2中:{}'.format(e.graph is graph2))
# 注意:不能使用两个图中的变量进行操作
# f = tf.add(d, e)
# 3、以c和a作为输入 进行矩阵的相加操作
g = tf.add(a, c, name='add')
print(type(g))
print(g)
# 增加的操作 复杂点
h = tf.subtract(b, a, name='b-a')
i = tf.matmul(h, c, name='h_cheng_c')
j = tf.add(g, i, name='g_jia_i')
# 4、会话的创建、启动、关闭(默认情况下,创建的session属于默认图)
# sess = tf.Session(graph=tf.get_default_graph())
sess = tf.Session()
# print(sess)
# 调用sess的run方法执行矩阵的乘法,得到c的结果值(所以需要将c作为参数传递进去)
# 不需要考虑图中间的运算,在运行的时候只需要关注最终结果对应的对象以及所需要的输入数据值
# 会自动的根据图中的依赖关系触发所有相关的op操作的执行
# 如果op之间没有依赖关系,TensorFlow底层会自动的并行的执行op(前提是有资源)
# result = sess.run(j)
# print('type:{}, value:\n{}'.format(type(result), result))
# 如果还需要得到c的结果
# result2 = sess.run(c)
# print(result2)
# 如果传递的fetches是一个列表(顺序没有任何关系),那么返回值是一个list集合
result3 = sess.run([j, c])
print('type:{}, value:\n{}'.format(type(result3), result3))
# 会话的关闭
sess.close()
# 当一个会话关闭后,不能再使用了,所以下面的代码错误
# RuntimeError: Attempted to use a closed Session.
# result4 = sess.run(c)
# print(result4)
with tf.Session() as sess2:
print(sess2)
# 获取张量c的结果:通过Session的run方法
print('sess2 run:\n{}'.format(sess2.run(c)))
# 获取张量c的结果:通过张量对象的eval方法 与通过Session的run方法 一致
print('c eval:\n{}'.format(c.eval()))
# 交互式会话构建
# sess3 = tf.InteractiveSession()
# print(j.eval())
复制代码
欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/)
Powered by Discuz! X3.4