在训练期间的张量流恒定层

时间:2018-01-05 10:56:17

标签: python tensorflow

我有一个小型的神经网络,用tf.layers创建:

# The neural network 
input = tf.placeholder(dtype=tf.float32, shape=(None,5,5,1), name="input")
conv_layer_1 = tf.layers.conv2d(input, 3,        (1,1), activation=tf.nn.leaky_relu, name="conv_1")
conv_layer_2 = tf.layers.conv2d(conv_layer_1, 3, (1,1), activation=tf.nn.leaky_relu, name="conv_2")
conv_layer_3 = tf.layers.conv2d(conv_layer_2, 1, (1,1), activation=tf.nn.leaky_relu, name="conv_3")


# Trainingsstuff
prediction = tf.placeholder(dtype= tf.float32, shape = (None, 5,5,1))
loss = tf.losses.mean_squared_error(conv_layer_3, prediction)
train_step = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)

这个网络我想训练。在几个步骤之后,我需要 conv_layer_2 保持不变。有没有办法将conv_layer_2设置为常量?

编辑:这个问题不够准确。

1 个答案:

答案 0 :(得分:2)

更新

所以你需要的是训练所有变量一段时间,然后让其中一个层得到修复。遗憾的是,没有直接这样做,因为当您定义优化操作时,它本质上与它更新的变量相关联。但是你可以做以下事情:

# The neural network 
input = tf.placeholder(dtype=tf.float32, shape=(None,5,5,1), name="input")
conv_layer_1 = tf.layers.conv2d(input, 3,        (1,1), activation=tf.nn.leaky_relu, name="conv_1")
conv_layer_2 = tf.layers.conv2d(conv_layer_1, 3, (1,1), activation=tf.nn.leaky_relu, name="conv_2")
conv_layer_3 = tf.layers.conv2d(conv_layer_2, 1, (1,1), activation=tf.nn.leaky_relu, name="conv_3")

# Training stuff
prediction = tf.placeholder(dtype= tf.float32, shape = (None, 5,5,1))
loss = tf.losses.mean_squared_error(conv_layer_3, prediction)
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
train_step_all = optimizer.minimize(loss)
# Now you remove the weights of conv_layer_2 from the trainable variables
trainable_vars = tf.get_collection_ref(GraphKeys.TRAINABLE_VARIABLES)
for var in conv_layer_2.variables:
    try:
        trainable_vars.remove(var)
    except ValueError: pass
# This op will train only the remaining layers
train_step_some = optimizer.minimize(loss)

然后,您需要根据需要设计逻辑以使用train_step_alltrain_step_some。另一种方法是将var_list参数传递给minimize方法,其中包含您希望在每种情况下更新的所有变量(您还可以使用自定义图形集合在构建图形时保存它们)。

旧答案(仅供参考)

如果您查看the docs,您会看到trainable参数可以设置为False,以防止在培训期间更新图层权重(更具体地说,相关变量将不会添加到默认情况下优化程序使用的标准可训练变量集中。请注意,除非手动或从检查点加载某些特定值,否则它们将具有初始化时给出的值。