1. 程式人生 > >Tensorflow 實戰(-) 基礎知識

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, 如果有變數就複用,沒有變數就自動建立,使用起來比較安全。