Python 列车运行期间的张量流量恒定层

Python 列车运行期间的张量流量恒定层,python,tensorflow,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.

我有一个小的神经网络,它是用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设置为常量


编辑:这个问题不够准确

更新

因此,您需要的是对所有变量进行一段时间的训练,然后确定其中一个层。不幸的是,这样做并不简单,因为当您定义一个优化操作时,它本质上与它更新的变量相关联。但是,您可以执行以下操作:

# 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\u step\u all
train\u step\u some
。另一种方法是将
var_list
参数传递给
minimize
方法,并在每种情况下更新所有变量(也可以在构建图形时使用自定义图形集合保存它们)


旧答覆(供参考)


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

我需要图层是可变的和恒定的。此标志看起来只是常量或变量。可训练:布尔值,如果为真,还可以将变量添加到图形集合GraphKeys.trainable_变量(请参阅tf.Variable)。@SebastianH是,请参阅我编辑的答案。该图集合是优化器用来选择需要优化的变量的集合(除非另有说明)。@SebastianH实际上是一个替代方案(当然不太实用)方法是以某种方式手动选择所有不希望固定的变量,并将其传递给优化器的方法。@SebastianH我想我明白你的意思了,检查更新的答案。非常感谢。这正是我想要的:)