一、TF数据流图
1.案例:TensorFlow 实现一个加法运算
import tensorflow as tf
def tensorflow_demo():
"""
TensorFlow的基本构架
:return;
"""
#原生python加法运算
a=2
b=3
c=a+b
printf("普通加法运算的结果:\n",c)
#TensorFlow实现加法运算
a_t = tf.constant(2)
b_t = tf.constant(3)
c_t = a_t+b_t
printf("TensorFlow加法运算的结果:\n",c_t)
#开启会话
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print("c_t_value:\n",c_t_value)
return None
if name =="__main__":
#代码1:TensorFlow的基本结构
tensorflow_demo()
2.TensorFlow结构分析
一个构件图阶段
流程图:定义数据(张量Tensor)和操作(节点Op)
一个执行图阶段
调用各方资源,将定义好的数据和操作运行起来

2.1数据流图介绍
TensorFlow
Tensor - 张量 - 数据
Flow - 流动
若不想要显示警告日志,增加代码
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
2.2图与TensorBoard
2.2.1什么是图结构
图结构:
数据(Tensor)+操作(Operation)
2.2.2图相关操作
1 默认图
查看默认图的方法
1)调用方法
用tf.get_default_graph()
- 查看属性
.grapg
def graph_demo():
"""
图的演示
:return;
"""
#TensorFlow实现加法运算
a_t = tf.constant(2)
b_t = tf.constant(3)
c_t = a_t+b_t
printf("TensorFlow加法运算的结果:\n",c_t)
#查看默认图
#方法一:调用方法
default_g = tf.get_default_graph()
print("default_g:\n",default_g)
#方法二:查看属性
print("a_t的图属性:\n",a_t.graph)
print("c_t的图属性:\n",c_t_value)
print("sess的图属性:\n",sess.graph)
#开启会话
with tf.Session() as sess:
c_t_value = sess.run(c_t)
print("c_t_value:\n",c_t_value)
return None
if name =="__main__":
#代码1:TensorFlow的基本结构
#tensorflow_demo()
#代码2:图的演示
graph_demo()
2 创建图
new_g = tf.Graph()
with new_g.as_default();定义数据和操作
#自定义图
new_g = tf.Graph()
#在自己的图中定义数据和操作
with new_g.as_default():
a_new = tf.constant(20)
b_new = tf.constant(30)
c_new = a_new + b_new
print("c_new"\n",c_new)
return None
#开启会话
with tf.Session() as sess:
c_t_value = sess.run(c_t)
#试图运行自定义图中的数据、操作
#c_new_value = sess.run((c_new))
#print("c_new_value:\n",c_new_value)
print("c_t_value:\n",c_t_value)
print("sess的图属性:\n"sess.graph)
#开启new_g的会话
with tf.Session(graph=new_g) as new_sess:
c_new_value = sess.run((c_new))
print("c_new_value:\n",c_new_value)
print("new_sess的图属性:\n"new_sess.graph)
return None