2022-02-112.创建变量的三种方式:tf., tf., tf.
从以上实验结果来看,这三种方法定义的变量类型相同。并且只会发生由 tf.() 创建的变量之间的命名冲突。在实际使用中,这三种创建变量的方法的目的也很明确。其中
3. 探索和
tf.() 对 tf.() 创建的变量没有任何影响。
tf.() 主要用于管理命名空间,这使得我们的整个模型更有条理。 tf.()的作用是实现变量共享,it和tf.()完成变量共享的功能。
简要总结
1. 使用 tf.() 时,tf.() 和 tf.() 都会在 name 属性前加上 op.
2. 当使用 tf.() 时,tf.() 不会为 tf.() 创建的任何内容添加前缀。但是 tf.() 创建的会受到影响。
它可以用来做什么
通常可能有数千个节点,数量之多以至于很难一次看到它们,甚至很难使用标准图表工具进行显示。为简单起见,我们限定了操作/名称,可视化使用此信息在图中的节点上定义层次结构。默认情况下,仅显示顶级节点。以下示例使用 tf.在命名域下定义了三个操作:
import tensorflow as tf with tf.name_scope('hidden') as scope: a = tf.constant(5, name='alpha') W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0), name='weights') b = tf.Variable(tf.zeros([1]), name='biases') print a.name print W.name print b.name
结果是以下三个操作名:
/阿尔法
/
/
是加前缀,是给()创建的变量名加前缀。
tf.有时也处理命名冲突
import tensorflow as tf
def test(name=None):
with tf.variable_scope(name, default_name="scope") as scope:
w = tf.get_variable("w", shape=[2, 10])
test()
test()
ws = tf.trainable_variables()
for w in ws:
print(w.name)
#scope/w:0
#scope_1/w:0
#可以看出,如果只是使用default_name这个属性来创建variable_scope
#的时候,会处理命名冲突
共享变量
共享变量有两种方式:
虽然显式传递变量的代码非常清晰,但有时编写在实现中隐式使用变量的函数会很方便。 tf.layer 和所有 tf.layer 中的大多数功能层。和其他一些库工具使用这种方法。
变量作用域允许您在调用隐式创建和使用变量的函数时控制变量重用。范围还允许您以分层且易于理解的方式命名变量。
例如,假设我们编写一个函数来创建卷积/relu 层:
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_initializer(0.0))
conv = tf.nn.conv2d(input, weights,
strides=[1, 1, 1, 1], padding='SAME')
return tf.nn.relu(conv + biases)
此函数使用短名称 and ,有助于清楚地区分两者。但是,在真实的模型中,我们需要很多这样的卷积层,重复调用这个函数是行不通的:
input1 = tf.random_normal([1,10,10,32])
input2 = tf.random_normal([1,20,20,32])
x = conv_relu(input1, kernel_shape=[5, 5, 32, 32], bias_shape=[32])
x = conv_relu(x, kernel_shape=[5, 5, 32, 32], bias_shape = [32]) # This fails.
将失败,因为预期的操作不清楚(创建一个新变量或重用现有变量?)。但是,在不同的范围内调用可能表明我们要创建一个新变量:
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])
如果要共享变量,有两种选择。首先,您可以使用 :reuse=True 创建一个同名作用域:
with tf.variable_scope("model"):
output1 = my_image_filter(input1)
with tf.variable_scope("model", reuse=True):
output2 = my_image_filter(input2)
你也可以调用scope.()来触发重用:
with tf.variable_scope("model") as scope:
output1 = my_image_filter(input1)
scope.reuse_variables()
output2 = my_image_filter(input2)
因为根据作用域的具体字符串名称来初始化一个变量作用域是很危险的,所以也可以根据另一个作用域来初始化:
with tf.variable_scope("model") as scope:
output1 = my_image_filter(input1)
with tf.variable_scope(scope, reuse=True):
output2 = my_image_filter(input2)
分类:
技术要点:
相关文章:
暂无评论内容