前言
本文章是一篇源于Tensorflow里面Programmer's Guide的Sharing Variables教程。這也算是自己在學習tensorflow里面的一些感悟吧,所以就記錄下來與大家分享并作為回憶錄。在tensorflow官網的地址:Sharing Variables。這個變量范圍和共享變量一開始看起來好像沒啥用,可是一旦你在實際項目進行deep learning編碼的時候,你會發現這是一個對代碼重構和編碼優化很有幫助的東西。過幾天我會寫一篇使用CNN模型進行人臉識別的實戰文章,里面很能體現今天講的內容。
問題
先看一個例子(也是官網上的例子)
def my_image_filter(input_images):
conv1_weights = tf.Variable(tf.random_normal([5, 5, 32, 32]),
name="conv1_weights")
conv1_biases = tf.Variable(tf.zeros([32]), name="conv1_biases")
conv1 = tf.nn.conv2d(input_images, conv1_weights,
strides=[1, 1, 1, 1], padding='SAME')
relu1 = tf.nn.relu(conv1 + conv1_biases)
conv2_weights = tf.Variable(tf.random_normal([5, 5, 32, 32]),
name="conv2_weights")
conv2_biases = tf.Variable(tf.zeros([32]), name="conv2_biases")
conv2 = tf.nn.conv2d(relu1, conv2_weights,
strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.relu(conv2 + conv2_biases)
在官網上說想利用這個方法對兩張圖片進行相同的卷積操作。但是Variable()
會重新創建變量,這樣變量就不能復用了。這是個很蛋疼的事情。
# 第一次執行方法創建4個變量
result1 = my_image_filter(image1)
# 第二次執行再創建4個變量
result2 = my_image_filter(image2)
但我覺得還有個問題,就是代碼的重復問題。盡管這個問題不是解決的重點,但作為寫慣項目的人來說,這個真的受不了。Tensorflow給出一個很優雅的解決方案。
引入Variable Scope(變量范圍)
首先這里要介紹兩個方法:
-
tf.get_variable(<name>, <shape>, <initializer>)
:創建一個名為<name>
的變量 -
tf.variable_scope(<scope_name>)
:創建namespaces
其中創建了variable_scope(<scope_name>)
后,get_variable(<name>)
的變量名就會變為scope_name/name
啦!這就可以用來管理我們的變量啦!因為我們有時候在不同的情況想創建相同名稱的變量,假如用get_variable()
創建兩個相同名字的變量是會報錯的,但你用Variable()
的話就會把之前相同名稱的變量給覆蓋了。所以我們就用了variable_scope()
這個方法了。話不多說,直接貼代碼展示一下。
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
input_images = tf.placeholder(tf.float32, shape=(1, 32, 32, 1))
# 定義了一層卷積神經網絡
def conv_relu(input, kernel_shape, bias_shape):
# 創建名為weights的變量
weights = tf.get_variable("weights", kernel_shape, initializer=tf.random_normal_initializer())
# 創建名為biases的變量
biases = tf.get_variable("biases", bias_shape, initializer=tf.constant_initializer(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"):
# 在名為conv1的variable scope下調用一層神經網絡,對應的參數名為
# "conv1/weights", "conv1/biases"
relu1 = conv_relu(input_images, [3, 3, 1, 1], [1])
with tf.variable_scope("conv2"):
# 在名為conv2的variable scope下調用一層神經網絡,對應的參數名為
# "conv2/weights", "conv2/biases"
return conv_relu(relu1, [3, 3, 1, 1], [1])
with tf.variable_scope("image_filter") as scope:
result1 = my_image_filter(input_images)
# 重用變量
scope.reuse_variables()
result2 = my_image_filter(input_images)
init = tf.global_variables_initializer();
with tf.Session() as sess:
sess.run(init)
image = np.random.rand(1, 32, 32, 1)
result1 = sess.run(result1, feed_dict={input_images: image})
result2 = sess.run(result2, feed_dict={input_images: image})
print(result2.all() == result1.all())
理解get_variable_scope()
其實根據上面的代碼,我們可以想到一些關于這個內容。假如tf.get_variable_scope().reuse == False
的話,在這個scope下面的變量都會創建新的變量,加入有同樣名字的話就拋出異常。所以想重用變量的話,就要變成reuse
設置為True啦。
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
with tf.variable_scope("foo", reuse=True):
v1 = tf.get_variable("v", [1])
assert v1 is v
# True
理解variable_scope
1. scope可以一層一層的疊下去,如
with tf.variable_scope("foo"):
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.name == "foo/bar/v:0"
2. 同一個scope里面調用同名變量名則:
with tf.variable_scope("foo"):
v = tf.get_variable("v", [1])
tf.get_variable_scope().reuse_variables()
v1 = tf.get_variable("v", [1])
assert v1 is v
3. scope的reuse可繼承,子層的可重用性不影響父層的可重用性:
with tf.variable_scope("root"):
# 一開始root scope是不可重用的
assert tf.get_variable_scope().reuse == False
with tf.variable_scope("foo"):
# 接下來root的子scope foo也是不可重用的
assert tf.get_variable_scope().reuse == False
with tf.variable_scope("foo", reuse=True):
# 這里我們設置foo可重用
assert tf.get_variable_scope().reuse == True
with tf.variable_scope("bar"):
# 這樣他的的子scope就繼承了父scope的可復用性
assert tf.get_variable_scope().reuse == True
# 退回到root scope,發現并沒有影響到
assert tf.get_variable_scope().reuse == False
4. 獲取variable scope
我們調用variable_scope
創建新的scope后,可能經過一段時間又會再度使用這個scope。那就會用到像下面的代碼那樣啦
with tf.variable_scope("foo") as foo_scope:
v = tf.get_variable("v", [1])
# 進行其他操作....
with tf.variable_scope(foo_scope):
w = tf.get_variable("w", [1])
with tf.variable_scope(foo_scope, reuse=True):
v1 = tf.get_variable("v", [1])
w1 = tf.get_variable("w", [1])
assert v1 is v
assert w1 is w
而且可以在任何時候都可以跳回原來的scope,并且獨立于當前所在的scope:
with tf.variable_scope("foo") as foo_scope:
assert foo_scope.name == "foo"
with tf.variable_scope("bar"):
with tf.variable_scope("baz") as other_scope:
assert other_scope.name == "bar/baz"
with tf.variable_scope(foo_scope) as foo_scope2:
assert foo_scope2.name == "foo" # 沒有任何改變
本人認為這個用法很容易把自己思維混淆,建議編程的時候還是注意點或者少用。
5. 變量作用域中的初始化器
在我們調用tf.get_variable()
真的十分蛋疼,因為都需要定義initializer
,因為有時候我們都使用一樣的初始器。那variable_scope
就幫到你了。我們可以在variable_scope方法里面傳入參數initializer作為當前scope下每個變量的默認初始器
with tf.variable_scope("foo", initializer=tf.constant_initializer(0.4)):
v = tf.get_variable("v", [1])
assert v.eval() == 0.4 # 默認初始器起作用了
w = tf.get_variable("w", [1], initializer=tf.constant_initializer(0.3)):
assert w.eval() == 0.3 # 這個變量我定義了其他初始器
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.eval() == 0.4 # 原來子scope也會繼承父scope的初始器,這個和reuse有點相似哦。
好啦!今天的內容就到這里為止啦!是不是很簡單呢?哈哈。看完記得早睡哦~早唞!好夢!