TensorFlow——图

1. 默认图

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()


def graph_demo():
    # 图的演示
    a_t = tf.constant(10)
    b_t = tf.constant(20)
    c_t = tf.add(a_t, b_t)
    print("tensorflow实现加法运算:
", c_t)

    # 获取默认图
    default_g = tf.get_default_graph()
    print("获取默认图:
", default_g)

    # 数据的图属性
    print("a_t的graph:
", a_t.graph)
    print("b_t的graph:
", b_t.graph)
    # 操作的图属性
    print("c_t的graph:
", c_t.graph)

    # 开启会话
    with tf.Session() as sess:
        sum_t = sess.run(c_t)
        print("在sess当中的sum_t:
", sum_t)
        # 会话的图属性
        print("会话的图属性:
", sess.graph)

    return None


graph_demo()

运行结果:

获取默认图:

tf.get_default_graph()

可知变量a_t,b_t,c_t以及会话session所在的图都在默认图当中。

如何去除运行结果中间这行红色的字:

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2

只需要在代码中加入如下两行:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

2. 创建图

  • 可以通过tf.Graph()自定义创建图

  • 如果要在这张图中创建OP,典型用法是使用tf.Graph.as_default()上下文管理器

# 自定义图
    new_g = tf.Graph()
    print("自定义图:
", new_g)
    # 在自定义图中去定义数据和操作
    with new_g.as_default():
        new_a = tf.constant(30)
        new_b = tf.constant(40)
        new_c = tf.add(new_a, new_b)

    # 数据的图属性
    print("new_a的graph:
", new_a.graph)
    print("new_b的graph:
", new_b.graph)
    # 操作的图属性
    print("new_c的graph:
", new_c.graph)

    with tf.Session(graph=new_g) as sess2:
        sum_new = sess2.run(new_c)
        print("在sess2当中的sum_new:
", sum_new)
        print("会话的图属性:
", sess2.graph)

不同的图之间不能互相访问。
很少会同时开启不同的图,一般用默认的图就够了。
    with tf.Session(graph=new_g) as sess2:
        sum_new = sess2.run(new_c)
        print("在sess2当中的sum_new:
", sum_new)
        print("会话的图属性:
", sess2.graph)

如果有多个图,需要多个会话来开启。

我的前方是万里征途,星辰大海!!
原文地址:https://www.cnblogs.com/taoyuxin/p/14236517.html