Tensorflow 2.0 如何在卷积层之间共享参数?

标签 tensorflow keras keras-layer tensorflow2.0 multiview

我正在尝试重新实现 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/

相关文章:

python - 使用 Tensorflow 2.0 并在没有 Keras 的情况下立即执行

python - 如何将验证数据合并到 Keras 的 datagen.flow 中?

python - Keras 功能 API 多输入模型

python-3.x - 预期输入有 4 个维度,但得到了具有形状的数组

tensorflow - 如何在tensorflow中设置keras子类模型的输入?

tensorflow - 在 Keras 中使用 Tensorflow 层

python - 如何在不同的平台/技术中使用经过训练的神经网络?

python - 无效参数错误 : input_1_1:0 is both fed and fetched

python - 如何使用tensorflow读取Excel文件?

python - keras中如何将cifar10输入inceptionv3