【问题标题】:Tensorflow 2.0 How make share parameters among convolutional layers?Tensorflow 2.0 如何在卷积层之间共享参数?
【发布时间】:2019-11-15 06:15:02
【问题描述】:

我正在尝试在 Tensorflow 2.0 中重新实现 Multi-View CNN (MVCNN)。但是,据我所见,keras 层没有 tf.layers 中的选项reuse=True|False。有什么方法可以定义使用新 API 共享参数的层?或者我需要以 TFv1 方式构建模型?

非常感谢!

【问题讨论】:

    标签: tensorflow keras keras-layer tensorflow2.0 multiview


    【解决方案1】:

    要共享模型的参数,您只需使用相同的模型。这是 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))
    
    

    【讨论】:

    • 谢谢@nessuno!因此,例如,在多视图模型的情况下,我想重用模型的前半部分从多个输入中提取特征,后半部分用于组合它们的连接特征。我需要将模型分成 2 个吗?
    • 你必须定义一个带有 2 个输出的 Keras 模型 :) 看看功能性 keras API tensorflow.org/beta/guide/keras/functional
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2021-11-05
    • 2014-09-10
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 2018-05-25
    相关资源
    最近更新 更多