溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

TensorFLow中變量命名空間的示例分析

發(fā)布時間:2021-08-23 10:11:50 來源:億速云 閱讀:139 作者:小新 欄目:開發(fā)技術

這篇文章將為大家詳細講解有關TensorFLow中變量命名空間的示例分析,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

一、name_scope

with tf.name_scope(name):

name_scope: 為了更好地管理變量的命名空間而提出的。比如在 tensorboard 中,因為引入了 name_scope, 我們的 Graph 看起來才井然有序。

name_scope 對 get_variable 創(chuàng)建變量的 name 沒有影響,即 get_variable 創(chuàng)建的變量不在 name_scope 這個命名空間中

二、variable_scope

with tf.variable_scope(name_or_scope, reuse=None):

variable_scope: 大部分情況下,跟 tf.get_variable() 配合使用,實現(xiàn)變量共享的功能

可通過tf.get_variable_scope().reuse == True/False 判斷參變量是否共享

當前變量作用域可以用tf.get_variable_scope()進行檢索并且reuse 標簽可以通過調用tf.get_variable_scope().reuse_variables()設置為True

三、共享參變量

1、方法

使用 tf.Variable() 創(chuàng)建同一個 name 的變量(操作名不同),均不會報錯,但系統(tǒng)會自動修改 name(實質還是不讓共享參變量)

使用 tf.get_varible() 創(chuàng)建同一個 name 的變量(操作名不同),均會報錯(為了避免無意識的參變量復用造成的錯誤)

我們可以在 variable_scope 中使用 tf.get_variable() 創(chuàng)建變量,并通過 with tf.variable_scope(name_or_scope, reuse=True) 來共享參變量:

reuse=True:將只能獲取命名空間中已經創(chuàng)建過的變量,如果變量不存在,則tf.get_variable函數(shù)將報錯。

reuse=None / False:tf.get_variable操作將創(chuàng)建新的變量,如果同名的變量已經存在,則tf.get_variable函數(shù)將報錯。

2、代碼示例

# 下面是定義一個卷積層的通用方式
def conv_relu(input, kernel_shape, bias_shape):
  # Create variable named "weights".
  weights = tf.get_variable("weights", kernel_shape,
    initializer=tf.random_normal_initializer())
  # Create variable named "biases".
  biases = tf.get_variable("biases", bias_shape,
    initializer=tf.constant_intializer(0.0))
  conv = tf.nn.conv2d(input, weights,
    strides=[1, 1, 1, 1], padding='SAME')
  return tf.nn.relu(conv + biases)


# 定義一個圖片過濾器
def my_image_filter(input_images):
  with tf.variable_scope("conv1"):
    # Variables created here will be named "conv1/weights", "conv1/biases".
    relu1 = conv_relu(input_images, [5, 5, 32, 32], [32])
  with tf.variable_scope("conv2"):
    # Variables created here will be named "conv2/weights", "conv2/biases".
    return conv_relu(relu1, [5, 5, 32, 32], [32])


# 實驗一:調用 my_image_filter() 兩次
result1 = my_image_filter(image1)
result2 = my_image_filter(image2)
>>> Raises ValueError(... conv1/weights already exists ...), tf.get_variable()會檢測已經存在的變量是否已經共享


# 解決方法一, 可以在設計網絡時加上一個布爾型的 reuse 參數(shù) 
with tf.variable_scope("image_filters"):
  result1 = my_image_filter(image1)
with tf.variable_scope("image_filters", reuse=True):
  result2 = my_image_filter(image2)


# 解決方法二
with tf.variable_scope("image_filters") as scope:
  # 下面我們兩次調用 my_image_filter 函數(shù),但是由于引入了變量共享機制
  # 可以看到我們只是創(chuàng)建了一遍網絡結構。
  result1 = my_image_filter(image1)
  scope.reuse_variables()
  result2 = my_image_filter(image2)


# 解決方法三
with tf.variable_scope("image_filters") as scope:
  result1 = my_image_filter(image1)
with tf.variable_scope(scope, reuse=True):
  result2 = my_image_filter(image2)


# 打印出所有的可訓練參變量
vs = tf.trainable_variables()
print('There are %d trainable_variables in the Graph: ' % len(vs))
for v in vs:
  print(v)


# 輸出結果證明確實:參變量共享,因為只有四個變量,沒有創(chuàng)建新的變量。
There are 4 trainable_variables in the Graph: 
Tensor("image_filters/conv1/weights/read:0", shape=(5, 5, 32, 32), dtype=float32)
Tensor("image_filters/conv1/biases/read:0", shape=(32,), dtype=float32)
Tensor("image_filters/conv2/weights/read:0", shape=(5, 5, 32, 32), dtype=float32)
Tensor("image_filters/conv2/biases/read:0", shape=(32,), dtype=float32)

四、取出所有可訓練參數(shù)

# Returns all variables created with trainable=True in a var_list
var_list = tf.trainable_variables()

init = tf.global_variables_initializer()
sess.run(init)

for var in var_list:
  sess.run(var)

關于“TensorFLow中變量命名空間的示例分析”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI