Tensorflow在两个模型之间共享层

时间:2018-12-15 13:51:58

标签: python tensorflow

让我们的模型成为几个完全连接的层: enter image description here 我想共享中间层,并使用具有相同权重的两个模型,例如: enter image description here 我可以用Tensorflow做到吗?

1 个答案:

答案 0 :(得分: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)

一旦在变量作用域中创建了一个图层,您就可以随意重复使用该图层中的变量。在这里,我们只重复使用一次。