在TensorFlow <2.0中,我们曾经通过将tf.name_scope
或tf.variable_scope
分组来定义图层,尤其是诸如 inception模块之类的更复杂的设置。
利用这些运算符,我们能够方便地构建计算图,从而使TensorBoard的图视图更容易解释。
这对于调试复杂的体系结构非常方便。
不幸的是,tf.keras
似乎忽略了tf.name_scope
,而tf.variable_scope
在TensorFlow> = 2.0中消失了。因此,这样的解决方案...
with tf.variable_scope("foo"):
with tf.variable_scope("bar"):
v = tf.get_variable("v", [1])
assert v.name == "foo/bar/v:0"
...不再可用。有替代品吗?
我们如何在TensorFlow> = 2.0中对图层和整个模型进行分组?如果我们不对图层进行分组,则tf.keras
只会通过将所有内容依次放置在图形视图中,从而给复杂模型带来很大麻烦。
是否有tf.variable_scope
的替代品?到目前为止,我什么都找不到,但是在TensorFlow <2.0中大量使用了该方法。
编辑:我现在为 TensorFlow 2.0 实现了一个示例。这是使用tf.keras
实现的简单GAN:
# Generator
G_inputs = tk.Input(shape=(100,), name=f"G_inputs")
x = tk.layers.Dense(7 * 7 * 16)(G_inputs)
x = tf.nn.leaky_relu(x)
x = tk.layers.Flatten()(x)
x = tk.layers.Reshape((7, 7, 16))(x)
x = tk.layers.Conv2DTranspose(32, (3, 3), padding="same")(x)
x = tk.layers.BatchNormalization()(x)
x = tf.nn.leaky_relu(x)
x = tf.image.resize(x, (14, 14))
x = tk.layers.Conv2DTranspose(32, (3, 3), padding="same")(x)
x = tk.layers.BatchNormalization()(x)
x = tf.nn.leaky_relu(x)
x = tf.image.resize(x, (28, 28))
x = tk.layers.Conv2DTranspose(32, (3, 3), padding="same")(x)
x = tk.layers.BatchNormalization()(x)
x = tf.nn.leaky_relu(x)
x = tk.layers.Conv2DTranspose(1, (3, 3), padding="same")(x)
x = tf.nn.sigmoid(x)
G_model = tk.Model(inputs=G_inputs,
outputs=x,
name="G")
G_model.summary()
# Discriminator
D_inputs = tk.Input(shape=(28, 28, 1), name=f"D_inputs")
x = tk.layers.Conv2D(32, (3, 3), padding="same")(D_inputs)
x = tf.nn.leaky_relu(x)
x = tk.layers.MaxPooling2D((2, 2))(x)
x = tk.layers.Conv2D(32, (3, 3), padding="same")(x)
x = tf.nn.leaky_relu(x)
x = tk.layers.MaxPooling2D((2, 2))(x)
x = tk.layers.Conv2D(64, (3, 3), padding="same")(x)
x = tf.nn.leaky_relu(x)
x = tk.layers.Flatten()(x)
x = tk.layers.Dense(128)(x)
x = tf.nn.sigmoid(x)
x = tk.layers.Dense(64)(x)
x = tf.nn.sigmoid(x)
x = tk.layers.Dense(1)(x)
x = tf.nn.sigmoid(x)
D_model = tk.Model(inputs=D_inputs,
outputs=x,
name="D")
D_model.compile(optimizer=tk.optimizers.Adam(learning_rate=1e-5, beta_1=0.5, name="Adam_D"),
loss="binary_crossentropy")
D_model.summary()
GAN = tk.Sequential()
GAN.add(G_model)
GAN.add(D_model)
GAN.compile(optimizer=tk.optimizers.Adam(learning_rate=1e-5, beta_1=0.5, name="Adam_GAN"),
loss="binary_crossentropy")
tb = tk.callbacks.TensorBoard(log_dir="./tb_tf2.0", write_graph=True)
# dummy data
noise = np.random.rand(100, 100).astype(np.float32)
target = np.ones(shape=(100, 1), dtype=np.float32)
GAN.fit(x=noise,
y=target,
callbacks=[tb])
这些模型在TensorBoard中的图看起来像this。这些图层只是一个完整的混乱,模型“ G”和“ D”(在右侧)涵盖了一些混乱。 “ GAN”完全消失了。训练操作“ Adam”无法正确打开:太多的图层仅从左到右绘制,整个地方都有箭头。这样很难检查GAN的正确性。
虽然同一GAN的 TensorFlow 1.X 实现涵盖了许多“样板代码” ...
# Generator
Z = tf.placeholder(tf.float32, shape=[None, 100], name="Z")
def model_G(inputs, reuse=False):
with tf.variable_scope("G", reuse=reuse):
x = tf.layers.dense(inputs, 7 * 7 * 16)
x = tf.nn.leaky_relu(x)
x = tf.reshape(x, (-1, 7, 7, 16))
x = tf.layers.conv2d_transpose(x, 32, (3, 3), padding="same")
x = tf.layers.batch_normalization(x)
x = tf.nn.leaky_relu(x)
x = tf.image.resize_images(x, (14, 14))
x = tf.layers.conv2d_transpose(x, 32, (3, 3), padding="same")
x = tf.layers.batch_normalization(x)
x = tf.nn.leaky_relu(x)
x = tf.image.resize_images(x, (28, 28))
x = tf.layers.conv2d_transpose(x, 32, (3, 3), padding="same")
x = tf.layers.batch_normalization(x)
x = tf.nn.leaky_relu(x)
x = tf.layers.conv2d_transpose(x, 1, (3, 3), padding="same")
G_logits = x
G_out = tf.nn.sigmoid(x)
return G_logits, G_out
# Discriminator
D_in = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name="D_in")
def model_D(inputs, reuse=False):
with tf.variable_scope("D", reuse=reuse):
with tf.variable_scope("conv"):
x = tf.layers.conv2d(inputs, 32, (3, 3), padding="same")
x = tf.nn.leaky_relu(x)
x = tf.layers.max_pooling2d(x, (2, 2), (2, 2))
x = tf.layers.conv2d(x, 32, (3, 3), padding="same")
x = tf.nn.leaky_relu(x)
x = tf.layers.max_pooling2d(x, (2, 2), (2, 2))
x = tf.layers.conv2d(x, 64, (3, 3), padding="same")
x = tf.nn.leaky_relu(x)
with tf.variable_scope("dense"):
x = tf.reshape(x, (-1, 7 * 7 * 64))
x = tf.layers.dense(x, 128)
x = tf.nn.sigmoid(x)
x = tf.layers.dense(x, 64)
x = tf.nn.sigmoid(x)
x = tf.layers.dense(x, 1)
D_logits = x
D_out = tf.nn.sigmoid(x)
return D_logits, D_out
# models
G_logits, G_out = model_G(Z)
D_logits, D_out = model_D(D_in)
GAN_logits, GAN_out = model_D(G_out, reuse=True)
# losses
target = tf.placeholder(tf.float32, shape=[None, 1], name="target")
d_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=D_logits, labels=target))
gan_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=GAN_logits, labels=target))
# train ops
train_d = tf.train.AdamOptimizer(learning_rate=1e-5, name="AdamD") \
.minimize(d_loss, var_list=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="D"))
train_gan = tf.train.AdamOptimizer(learning_rate=1e-5, name="AdamGAN") \
.minimize(gan_loss, var_list=tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope="G"))
# dummy data
dat_noise = np.random.rand(100, 100).astype(np.float32)
dat_target = np.ones(shape=(100, 1), dtype=np.float32)
sess = tf.Session()
tf_init = tf.global_variables_initializer()
sess.run(tf_init)
# merged = tf.summary.merge_all()
writer = tf.summary.FileWriter("./tb_tf1.0", sess.graph)
ret = sess.run([gan_loss, train_gan], feed_dict={Z: dat_noise, target: dat_target})
...生成的TensorBoard graph看起来更干净。请注意,右上方的“ AdamD”和“ AdamGAN”范围是多么干净。您可以直接检查优化器是否已连接到正确的示波器/渐变。
答案 0 :(得分:1)
根据社区RFC Variables in TensorFlow 2.0:
- 要控制变量命名,用户可以使用tf.name_scope + tf.Variable
实际上,tf.name_scope
在TensorFlow 2.0中仍然存在,因此您可以这样做:
with tf.name_scope("foo"):
with tf.name_scope("bar"):
v = tf.Variable([0], dtype=tf.float32, name="v")
assert v.name == "foo/bar/v:0"
此外,以上几点指出:
- tf 1.0版本的variable_scope和get_variable将保留在tf.compat.v1中
因此,您可以根据需要退回到tf.compat.v1.variable_scope
和tf.compat.v1.get_variable
。
可变作用域和tf.get_variable
可能很方便,但充满了一些小陷阱和极端情况,特别是因为它们的行为类似但不完全像名称作用域,并且实际上是一种并行机制。我认为仅使用名称范围会更加一致和直接。