深度学习--第2章 tensorflow图和会话
第1节 tensorflow图的结构
import tensorflow as tf
def add(a,b):
return a+b
a = 1
b = 2
c=add(a,b)
print(c)
将以上程序改写为tensorflow计算方式:
import tensorflow as tf
#实现一个加法的运算
a = tf.constant(5.0)
b = tf.constant(6.0)
sum = tf.add(a,b)
# print(sum)
with tf.Session() as sess:
print(sess.run(sum))
结果:
红色警告是因为需要源码安装才能解决,所以不影响计算;
如果非要除去就添加两行代码在代码开头,如下:
import tensorflow as tf
import os----这一行
os.environ["TF_CPP_MIN_LOG_LEVEL"]="2"----还有这一行
数据流图分析:
注意:
- op是计算的节点,运算都在节点中进行
- 会话才是计算整个图,其他之前的操作都是建立图
- 变量和张量的区别
第2节图
#coding:utf-8
import tensorflow as tf
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
#实现一个加法运算
a = tf.constant(5.0)
b = tf.constant(6.0)
sum1 = tf.add(a,b)
#默认的这张图,是相当于给程序分配一段内存,然后将图存储在内存中
graph = tf.get_default_graph()
print(graph)
with tf.Session() as sess:
print(sess.run(sum1))
print(a.graph)
print(sum1.graph)
print(sess.graph)
结果:
<tensorflow.python.framework.ops.Graph object at 0x0000000000B21828>
11.0
<tensorflow.python.framework.ops.Graph object at 0x0000000000B21828>
<tensorflow.python.framework.ops.Graph object at 0x0000000000B21828>
<tensorflow.python.framework.ops.Graph object at 0x0000000000B21828>
Process finished with exit code 0
注意:
1. 图建立起来后,所有计算的变量都在同一段内存中
2. 建立图,是相当于给程序分配一段内存,然后将图存储在内存中
图的创建
#coding:utf-8
import tensorflow as tf
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
#创建一张图,包含OP和tensor
#OP:只要使用tf的API定义的函数都是OP
#张量tensor:指代的就是数据
g = tf.Graph()#op
print(g)
# 使用一张图需要上下文环境
with g.as_default():
c = tf.constant(11.0)#OP
print(c.graph)
#实现一个加法运算
# a =0 #不是OP
a = tf.constant(5.0)#OP
b = tf.constant(6.0)#OP
sum1 = tf.add(a,b)#OP
#默认的这张图,是相当于给程序分配一段内存,然后将图存储在内存中
graph = tf.get_default_graph()#OP
# print(sum1)
print(graph)
with tf.Session() as sess:
print(sess.run(sum1))
# print(a.graph)
# print(sum1.graph)
# print(sess.graph)
结果:
<tensorflow.python.framework.ops.Graph object at 0x0000000000DDD240>
<tensorflow.python.framework.ops.Graph object at 0x0000000000DDD240>
<tensorflow.python.framework.ops.Graph object at 0x00000000087BBB70>
11.0
注意:
1. 两张图保存在不同位置,可见每张图是独立分配内存的。互不干扰
2. with tf.Session() as sess:默认会话只能运算一张图
3. 创建一张图,包含OP和tensor
OP:只要使用tf的API定义的函数都是OP
张量tensor:指代的就是数据
第3节会话
第4节会话的run方法