python神經網絡tf.name_scope和tf.variable_scope函數區(qū)別
學習前言
最近在學目標檢測……SSD的源碼好復雜……看了很多版本的SSD源碼,發(fā)現(xiàn)他們會使用tf.variable_scope,剛開始我還以為就是tf.name_scope,才發(fā)現(xiàn)原來兩者是不一樣的
兩者區(qū)別
tf.name_scope()和tf.variable_scope()是兩個作用域,一般與兩個創(chuàng)建/調用變量的函數tf.variable() 和tf.get_variable()搭配使用。
為什么要使用兩個不同的作用域方式呢?其主要原因與變量共享相關。
變量共享主要涉及兩個函數:tf.Variable() 和tf.get_variable()
在tf.variable_scope的作用域下需要使用tf.get_variable()函數,這是因為tf.get_variable()擁有一個變量檢查機制,會檢測已經存在的變量是否設置為共享變量,當同名變量存在共享機制時,不會報錯,如果并未設置為共享變量,則報錯。
如果使用tf.Variable() 的話每次都會新建變量。但是很多時候我們希望重用一些變量,所以我們使用到了get_variable(),它會去搜索變量名,有就直接用,沒有再新建。
在進行變量共享的時候需要使用到標志reuse,當reuse = True時是可以共享,F(xiàn)alse時不可以共享。
tf.variable_scope函數
tf.variable_scope( name_or_scope, default_name=None, values=None, initializer=None, regularizer=None, caching_device=None, partitioner=None, custom_getter=None, reuse=None, dtype=None, use_resource=None, constraint=None, auxiliary_name_scope=True )
其中:
1、name_or_scope:范圍的名稱。
2、default_name:如果name_or_scope參數為None,則使用默認的名稱,該名稱將是唯一的;如果提供了name_or_scope,它將不會被使用,因此它不是必需的,并且可以是None。
3、values:傳遞給操作函數的Tensor參數列表。
4、initializer:此范圍內變量的默認初始值設定項。
5、regularizer:此范圍內變量的默認正規(guī)化器。
6、caching_device:此范圍內變量的默認緩存設備。
7、partitioner:此范圍內變量的默認分區(qū)程序。
8、custom_getter:此范圍內的變量的默認自定義吸氣。
9、reuse:可以是True、None或tf.AUTO_REUSE;如果是True,即可以開始共享變量,變量重構用;如果是tf.AUTO_REUSE,則我們創(chuàng)建變量(如果它們不存在),否則返回它們(用于在第一輪創(chuàng)建變量);如果是None,則我們繼承父范圍的重用標志。
10、dtype:在此范圍中創(chuàng)建的變量類型。
測試代碼
1、使用reuse=True共享變量
import tensorflow as tf # 初始化第一個v1 with tf.variable_scope("scope1"): v1 = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1)) print(v1.name) # 不同的作用域 with tf.variable_scope("scope2"): v1 = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1)) print(v1.name) # 開始共享 with tf.variable_scope("scope1",reuse = True): v1_share = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1)) print(v1_share.name)
運行結果為:
scope1/v1:0
scope2/v1:0
scope1/v1:0
如果在下部再加上
with tf.variable_scope("scope2"): v1_share = tf.get_variable("v1",[3,3],tf.float32,initializer=tf.constant_initializer(1)) print(v1_share.name)
此時沒有reuse,不能共享,程序報錯。
2、使用AUTO_REUSE共享變量
import tensorflow as tf # 使用AUTO_REUSE可以直接創(chuàng)建 # 如果reuse = True,初始化第一輪創(chuàng)建的時候會報錯 def demo(): with tf.variable_scope("demo", reuse=tf.AUTO_REUSE): v = tf.get_variable("v", [1]) return v v1 = demo() v2 = demo() print(v1.name)
運行結果為:
demo/v:0
demo/v:0
以上就是python神經網絡tf.name_scope和tf.variable_scope函數區(qū)別的詳細內容,更多關于tf.name_scope和tf.variable_scope的資料請關注腳本之家其它相關文章!