【问题标题】:Tensorflow share layers between two modelsTensorFlow 在两个模型之间共享层
【发布时间】:2020-07-30 09:38:13
【问题描述】:

让我们的模型成为几个全连接层:

我想共享中间层并使用两个具有相同权重的模型,如下所示:

我可以用 Tensorflow 做这个吗?

【问题讨论】:

  • 简短的回答是,这是可能的。如果您对两个模型使用相同的tf.Graph,则可以通过重用变量范围来实现此行为。您能否提供您尝试过的代码 sn-p 吗?

标签: python tensorflow


【解决方案1】:

是的,您可以共享图层! TensorFlow 官方教程是here

在您的情况下,可以使用可变范围实现层共享

#Create network starts, which are not shared
start_of_net1 = create_start_of_net1(my_inputs_for_net1)
start_of_net2 = create_start_of_net2(my_inputs_for_net2)

#Create shared middle layers
#Start by creating a middle layer for one of the networks in a variable scope
with tf.variable_scope("shared_middle", reuse=False) as scope:
    middle_of_net1 = create_middle(start_of_net1)
#Share the variables by using the same scope name and reuse=True
#when creating those layers for your other network
with tf.variable_scope("shared_middle", reuse=True) as scope:
    middle_of_net2 = create_middle(start_of_net2)

#Create end layers, which are not shared
end_of_net1 = create_end_of_net1(middle_of_net1)
end_of_net2 = create_end_of_net2(middle_of_net2)

在变量范围内创建层后,您可以根据需要多次重复使用该层中的变量。在这里,我们只重用它们一次。

【讨论】:

  • 我认为这个答案在 Tensorflow 2 中不再适用。你能更新一下吗?谢谢!
  • @becko 我仍在使用 tensorflow 1.7,但是,accepted answer 可能会有所帮助。在 tensorflow 2 中,您可以声明模型的某些部分,例如要重用的函数。如果您使用的是 tensorflow 1.x,Sonnet 提供了类似的变量共享。
猜你喜欢
  • 1970-01-01
  • 2010-10-22
  • 2016-06-15
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 2015-09-30
  • 2019-12-06
相关资源
最近更新 更多