gpt4 book ai didi

tensorflow - 如何使用 tf.layers.conv2d 共享权重

转载 作者:行者123 更新时间:2023-12-01 22:08:29 24 4
gpt4 key购买 nike

我已经使用 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())

如果你给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)

f1f2 都将使用具有相同变量的图层

关于tensorflow - 如何使用 tf.layers.conv2d 共享权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50030163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com