Tensorflow 实战(-) 基础知识

1. tensorflow 介绍

1.1 设计理念
1) 图的定义与图的运行是分离开的
简单来说,就是定义了一个操作,但是并没有真正去运行,
tensorflow 被认为是一个符号主义的库。
编程模式分为命令式编程和符号式编程,
2) TensorFlow 中涉及的运算都在在图中,图的运算只能在session中,过程就是启动会话之后,用数据去填充节点,进行运算,关闭会话就不再进行计算。

2. tensorflow 变量作用域-上下文管理器

有点儿类似于python的with block上下文管理器,当你调用with Object() as obj:的时候,会自动调用obj对象的__enter__()和obj对象的__exit__()方法。
2.1 variable_scope

只需要掌握两点:
tf.variable_scope(<scope_name>) #创建域名
tf.get_variable(name, shape, dtype, initializer) # 通过名称创建或者返回一个变量

相关实例如下:

def test_scope():
    with tf.variable_scope("scope1") as scope1:
        assert scope1.name == "scope1"
        v = tf.get_variable('v1', [1])
    with tf.variable_scope(scope1, reuse=True):  # #### reuse method
        v2 = tf.get_variable('v1', [1])
    assert v == v2

    with tf.variable_scope("foo", initializer=tf.constant_initializer(0.4)):
        mm = tf.get_variable("mm", [1])
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            x = sess.run(mm)
            print(x)
2.2 name_scope

name_scope 只对op和通过Variable创建的变量有作用,对get_variable的无影响。

def name_scope():
    with tf.variable_scope("scope1"):
        with tf.name_scope("name_scope1"):
            v = tf.get_variable("v", [1])
            b = tf.Variable(tf.zeros([1]), name='b')
            x = 1.0 + v

    assert v.name == "scope1/v:0"
    assert b.name == "scope1/name_scope1/b:0"
    assert x.op.name == "scope1/name_scope1/add"

总结两者的区别:
http://blog.csdn.net/u012436149/article/details/53081454
http://blog.csdn.net/u012436149/article/details/73555017
思考如下问题:
1. tensorflow如何实现variable_scope上下文管理器这个机制?
Graph是像一个大容器,OP、Tensor、Variable是这个大容器的组成部件。Graph中维护一个collection,这个collection中的 键_VARSCOPE_KEY对应一个 [current_variable_scope_obj],保存着当前的variable_scope。使用 get_variable() 创建变量的时候,就从这个collection 取出 current_variable_scope_obj,通过这个 variable_scope创建变量。
目前新推出的Eager模式下面,使用tf.AUTO, 如果有变量就复用,没有变量就自动创建,使用起来比较安全。

猜你喜欢

转载自blog.csdn.net/u011415481/article/details/77996923