Tensorflow 2.0 如何在卷积层之间共享参数?
Tensorflow 2.0 How make share parameters among convolutional layers?
我正在尝试在 Tensorflow 2.0 中重新实现 Multi-View CNN (MVCNN)。但是,据我所知,keras 层没有 tf.layers 中那样的选项 reuse=True|False。有什么方法可以定义使用新的 API 共享参数的图层?或者我需要以 TFv1 方式构建我的模型?
非常感谢!
要共享模型的参数,您只需使用相同的模型即可。这是 TensorFlow 2.0 引入的新范式;
在 TF 1.xt 中,我们使用了 graph-oriented 方法,我们需要 re-use 相同的图形来共享变量,但现在我们可以 re-use 相同的 [=11] =] 具有不同输入的对象。
是携带自身变量的对象
使用 Keras 模型和 tf.GradientTape
您可以轻松训练共享变量的模型,如下例所示。
# This is your model definition
model = tf.keras.Sequential(...)
#input_1,2 are model different inputs
with tf.GradientTape() as tape:
a = model(input_1)
b = model(input_2)
# you can just copute the loss
loss = a + b
# Use the tape to compute the gradients of the loss
# w.r.t. the model trainable variables
grads = tape.gradient(loss, model.trainable_varibles)
# Opt in an optimizer object, like tf.optimizers.Adam
# and you can use it to apply the update rule, following the gradient direction
opt.apply_gradients(zip(grads, model.trainable_variables))
我正在尝试在 Tensorflow 2.0 中重新实现 Multi-View CNN (MVCNN)。但是,据我所知,keras 层没有 tf.layers 中那样的选项 reuse=True|False。有什么方法可以定义使用新的 API 共享参数的图层?或者我需要以 TFv1 方式构建我的模型?
非常感谢!
要共享模型的参数,您只需使用相同的模型即可。这是 TensorFlow 2.0 引入的新范式; 在 TF 1.xt 中,我们使用了 graph-oriented 方法,我们需要 re-use 相同的图形来共享变量,但现在我们可以 re-use 相同的 [=11] =] 具有不同输入的对象。
是携带自身变量的对象
使用 Keras 模型和 tf.GradientTape
您可以轻松训练共享变量的模型,如下例所示。
# This is your model definition
model = tf.keras.Sequential(...)
#input_1,2 are model different inputs
with tf.GradientTape() as tape:
a = model(input_1)
b = model(input_2)
# you can just copute the loss
loss = a + b
# Use the tape to compute the gradients of the loss
# w.r.t. the model trainable variables
grads = tape.gradient(loss, model.trainable_varibles)
# Opt in an optimizer object, like tf.optimizers.Adam
# and you can use it to apply the update rule, following the gradient direction
opt.apply_gradients(zip(grads, model.trainable_variables))