我正在尝试重新实现 Multi-View CNN (MVCNN)在 Tensorflow 2.0 中。但是,据我所知,keras 层没有像 tf.layers 中那样的选项重用=真|假。有什么方法可以定义使用新 API 共享参数的层?或者我需要以 TFv1 方式构建我的模型?
非常感谢!
最佳答案
要共享模型的参数,您只需使用相同的模型。这是 TensorFlow 2.0 中引入的新范式;
在 TF 1.xt 中,我们使用了面向图的方法,我们需要重用相同的图来共享变量,但现在我们可以重用相同的 tf.keras.Model
具有不同输入的对象。
是携带自己变量的对象。
使用 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 如何在卷积层之间共享参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56889038/