use*_*879 2 share tensorflow convolutional-neural-network
我已经使用 tf.layers.conv2d 层构建了一个自动编码器,并希望分阶段训练它。即先训练外层,然后训练中层,然后训练内层。我知道这可以使用 tf.nn.conv2d,因为权重是使用 tf.get_variable 声明的,但我认为这也应该可以使用 tf.layers.conv2d。
如果我输入一个不同于原始图的新变量范围来更改卷积层的输入(即在阶段 1 期间跳过内层),我将无法重用权重。如果我不输入新的变量范围,我将无法冻结我不想在此阶段训练的权重。
基本上我想在这里使用 Aurélien Géron 的训练方法https://github.com/ageron/handson-ml/blob/master/15_autoencoders.ipynb
除了我想使用 cnn 而不是密集层。怎么做?
无需手动创建变量。这也同样有效:
import tensorflow as tf
inputs_1 = tf.placeholder(tf.float32, (None, 512, 512, 3), name='inputs_1')
inputs_2 = tf.placeholder(tf.float32, (None, 512, 512, 3), name='inputs_2')
with tf.variable_scope('conv'):
out_1 = tf.layers.conv2d(inputs_1, 32, [3, 3], name='conv_1')
with tf.variable_scope('conv', reuse=True):
out_2 = tf.layers.conv2d(inputs_2, 32, [3, 3], name='conv_1')
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(tf.trainable_variables())
Run Code Online (Sandbox Code Playgroud)
如果您给出tf.layers.conv2d相同的名称,它将使用相同的权重(假设为reuse=True,否则将有一个ValueError)。
在 Tesorflow 2.0 中: tf.layers被 keras 层取代,其中变量通过使用相同的层对象重用:
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, 3, activation='relu',
input_shape=(512, 512, 3)),
])
@tf.function
def f1(x):
return model(x)
@tf.function
def f2(x):
return model(x)
Run Code Online (Sandbox Code Playgroud)
双方f1并f2会使用具有相同的变量层
| 归档时间: |
|
| 查看次数: |
6036 次 |
| 最近记录: |