tensorflow002-图

tensorflow的组成

首先我们用tensorflow实现一个加法运算,tensorflow和其他编程语言不同,数据不能直接用于运算,将数据组成一张图
图中包括:op和tensor,上下文环境

  • op:只要使用了tensorflow定义的的api都是op
  • tensor就指代的是数据

实现一个加法运算

tensorflow默认会有一张图,只需将tensor(张量)添加入op中,之后再对op进行运算

#coding:utf-8
import tensorflow as tf
import os
#实现一个加法运算
a = tf.constant(3.0)
b = tf.constant(4.0)
sum1 = tf.add(a, b)
#  #创建一个会话用于运行图:
with tf.Session() as sess:
    print(sess.run(sum1))

在这里插入图片描述

获取图的调用

  • tf.get_default_graph()
  • op,session或者tensor的graph属性
# 获取默认图的调用
graph = tf.get_default_graph()
#打印op的图的调用
print (a.graph)
print (sum1.graph)
with tf.Session() as sess:
    #打印sess的图的调用
    print(sess.graph)
    #运行图的结果
    print(sess.run(sum1))

可以发现运行结果的地址一样,即调用了同一个图:
在这里插入图片描述

创建一张新图

使用tf.Grap()创建一张新图

#创建一张新图,并获取新图的对象
g = tf.Graph()
#打印新图的地址
print (g)
#使用上下文环境,在with语句下将g作为tf的默认的图:
with g.as_default():
    c = tf.constant(11.0)
    print(c.graph)

查看运行结果可以发现新创建的图的地址和默认图的地址不同:
在这里插入图片描述
当离开with后再次打印默认的图的地址发现又和原来的相同,证明出了上下文环境默认的图又变成原来的图:

#使用上下文环境,将g作为默认的图:
with g.as_default():
    c = tf.constant(11.0)
    print(c.graph)
#离开上下文环境,打印tf默认图的地址
print(tf.get_default_graph())

在这里插入图片描述
此时程序中有两个图,通过会话(session)来运行图时默认运行默认的图,怎么运行新创建的图呢?
这就需要在session函数内传入参数grap=

#打开新图的会话:
with tf.Session(graph=g) as sess:
    print(sess.run(sum2))

打印结果:
在这里插入图片描述

完整代码

#coding:utf-8
import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'   #设置报错的等级,避免爆红
#创建一张图包括一组op和tensor,上下文环境
#op:只要使用了tensorflow定义的的api都是op
#tensor就指代的是数据

#实现一个加法运算
a = tf.constant(3.0)
b = tf.constant(4.0)
sum1 = tf.add(a, b)

#程序默认会给图进行注册,即给图分配地址
# 获取默认图的调用
graph = tf.get_default_graph()
#打印
print(graph)
#打印op的图的调用
print (a.graph)
print (sum1.graph)
#  #创建一个会话用于运行图:
with tf.Session() as sess:
    #打印sess的图的调用
    print(sess.graph)
    #运行图的结果
    print(sess.run(sum1))
#创建一张新图,并获取新图的对象
g = tf.Graph()
#打印新图的地址
print (g)
#使用上下文环境,将g作为默认的图:
with g.as_default():
    c = tf.constant(11.0)
    d = tf.constant(12.0)
    sum2 = tf.add(c, d)
    print(c.graph)
#离开上下文环境,打印tf默认图的地址
print(tf.get_default_graph())
#打开新图的会话:
with tf.Session(graph=g) as sess:
    print(sess.run(sum2))


猜你喜欢

转载自blog.csdn.net/qq_38441692/article/details/87191312
002