《TensorFlow 与卷积神经网络 (从算法到入门)》学习笔记
get_variable(
name,
shape=None,
dtype=None,
initializer=None,
regularizer=None,
trainable=True,
collections=None,
caching_device=None,
partitioner=None,
validate_shape=True,
use_resource=None,
custom_getter=None
)
import tensorflow as tf
A = [[1, 2, 3],
[4, 5, 6]]
# 创建变量初始化器
initializer = tf.constant_initializer(A)
A_tf = tf.get_variable(name='A', shape=[2, 3], initializer=initializer)
print('A shape:', A_tf.get_shape().as_list())
print('A dtype:', A_tf.dtype)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
A = sess.run(A_tf)
print('A value:', A)
# 输出为:
# A shape: [2, 3]
# A dtype:
# A value: [[1. 2. 3.]
# [4. 5. 6.]]
使用 tf.get_variable() 创建或获取指定名称的变量时,如果命名空间中已经有对应的名称变量时,一定要设置变量重用(reuse 标记为 True),否则会报错,如下:
import tensorflow as tf
input = [[1, 2, 3],
[4, 5, 6]]
initializer = tf.constant_initializer(input)
input_tf1 = tf.get_variable(name='input', shape=[2, 3], initializer=initializer)
input_tf2 = tf.get_variable(name='input', shape=[2, 3], initializer=initializer)
print('input_tf1 shape:', input_tf1.name)
print('input_tf2 shape:', input_tf2.name)
print('A_tf1 == A_tf2 ? ', input_tf1 == input_tf2)
# 报错提示:
# ValueError: Variable input already exists, disallowed.
# Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?
A_tf1 , A_tf2 指向的是同一个变量
import tensorflow as tf
input = [[1, 2, 3],
[4, 5, 6]]
initializer = tf.constant_initializer(input)
input_tf1 = tf.get_variable(name='input', shape=[2, 3], initializer=initializer)
print('reuse = ', tf.get_variable_scope().reuse)
# 现获取当前的变量命名空间,通过调用 reuse_variables() 函数, 将reuse属性设置为True
tf.get_variable_scope().reuse_variables()
print('reuse = ', tf.get_variable_scope().reuse)
# 下面调用 tf.get_variable() 函数由默认的创建变量 修改为 获取已存在的指定变量
input_tf2 = tf.get_variable(name='input', shape=[2, 3], initializer=initializer)
print('input_tf1 shape:', input_tf1.name)
print('input_tf2 shape:', input_tf2.name)
print('A_tf1 == A_tf2 ? ', input_tf1 == input_tf2)
# 输出为:
# reuse = False
# reuse = True
# input_tf1 shape: input:0
# input_tf2 shape: input:0
# A_tf1 == A_tf2 ? True
除调用reuse_variable()函数设置reuse=True, 还可以通过创建tf.Variable_scope 对象的方式,在构造函数里指定reuse属性
import tensorflow as tf
def get_var(name, reuse):
input = [[1, 2, 3],
[4, 5, 6]]
initializer = tf.constant_initializer(input)
with tf.variable_scope("my_scope", reuse=tf.AUTO_REUSE):
return tf.get_variable(name=name, shape=[2, 3], initializer=initializer)
input_tf1 = get_var('input', reuse=False)
input_tf2 = get_var('input', reuse=True)
input_tf3 = get_var('input', reuse=tf.AUTO_REUSE)
print('input_tf1 shape:', input_tf1.name)
print('input_tf2 shape:', input_tf2.name)
print('input_tf3 shape:', input_tf3.name)
print('input_tf1 == input_tf2 ? ', input_tf1 == input_tf2)
print('input_tf1 == input_tf3 ? ', input_tf1 == input_tf3)
# 输出为:
# input_tf1 shape: my_scope/input:0
# input_tf2 shape: my_scope/input:0
# input_tf3 shape: my_scope/input:0
# input_tf1 == input_tf2 ? True
# input_tf1 == input_tf3 ? True