tensorflow雜記

1.tf.get_variable或tf.Variable默認trainable=True, 默認將變量添加到圖形集合tf.GraphKeys.TRAINABLE_VARIABLES中,用於優化器Optimizer類優化的默認變量列表,也就是要訓練的變量列表。

2.tf.control_dependencies:with tf.control_dependencies([update_op]):

                                                        add_with_dependencies = tf.add(a_2, b_2)

在計算圖結構中調整優先順序,先計算變量op,

3.tf.GraphKeys.UPDATE_OPS,UPDATE_OPS是ops的集合(圖表運行時執行的操作,如乘法,ReLU等),

保存在訓練之前需要完成的操作,配合tf.control_dependencies使用

output = tf.layers.batch_normalization(input, training=is_traing)

update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)

#在tf.contrib.layers.batch_norm的參數中可以看到有一項updates_collections的默認值即爲tf.GraphKeys.UPDATE_OPS
print(update_ops)
with tf.control_dependencies(update_ops):
    train_op = optimizer.minimize(loss)

4.tf.get_collection

該函數的作用是從一個collection中取出全部變量,形成1個列表,key參數中輸入的是collection的名稱。該函數常常與tf.get_variable和tf.add_to_collection配合使用。

5.變量作用域和名稱作用域tf.variable_scope &&& tf.name_scope:

tf.Variable()可以單獨使用,也可以搭配`tf.name_scope`使用,形成命名區域,給變量分類命名

tf.variable_scope() 主要結合 tf.get_variable() 來使用,實現 變量共享。(reuse= True)

  1. 對於使用tf.Variable來說,tf.name_scope和tf.variable_scope功能一樣,都是給變量加前綴,相當於分類管理,模塊化。
  2. 對於tf.get_variable來說,tf.name_scope對其無效,也就是說tf認爲當你使用tf.get_variable時,你只歸屬於tf.variable_scope來管理共享與否。

with tf.variable_scope(tf.get_variable_scope(), reuse=reuse_variables):

6.tf.GraphKeys.REGULARIZATION_LOSSES,創建一個正則化方法(l1、l2),並把正則化方法應用到參數上。

在使用tf.get_variable()和tf.variable_scope()的時候,它們中有regularizer形參.如果傳入這個參數的話,那麼變量空間variable_scope內的weights的正則化損失,會被添加到GraphKeys.REGULARIZATION_LOSSES中。

regularizer = layers.l1_regularizer(0.1)
with tf.variable_scope('var', initializer=tf.random_normal_initializer(), 
regularizer=regularizer):
    weight = tf.get_variable('weight', shape=[8], initializer=tf.ones_initializer())

7.tf.contrib.slim->with slim.argscope([list_of_ops], **kwargs),爲list_of_ops設置默認值,如果是普通函數,需要

@slim.add_arg_scope

def func(a, b):

       return a+b

with slim.arg_scope([func], a=10)

      x = func(b=1)

     print(x)                              = 10+1

但是平常所用到的slim.conv2d( ),slim.fully_connected( ),slim.max_pool2d( )等函數在他被定義的時候就已經添加了@add_arg_scope。

 

發佈了13 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章