TensorFlow中的暹罗神经网络

时间:2016-04-25 15:28:47

标签: neural-network tensorflow deep-learning lstm

我试图在TensorFlow中实现一个Siamese神经网络,但我无法在互联网上找到任何有效的例子(见Yann LeCun paper)。

enter image description here

我尝试构建的架构将包含两个共享权重的LSTM,并且仅在网络末端连接。

我的问题是:如何在TensorFlow中构建两个不同的神经网络共享其权重(绑定权重)以及如何在末尾连接它们?

谢谢:)

编辑:我在MNIST上实现了一个简单且有效的网络here的实例。

1 个答案:

答案 0 :(得分:12)

使用tf.layers

进行更新

如果您使用tf.layers模块构建网络,则只需将参数reuse=True用于Siamese网络的第二部分:

x = tf.ones((1, 3))
y1 = tf.layers.dense(x, 4, name='h1')
y2 = tf.layers.dense(x, 4, name='h1', reuse=True)

# y1 and y2 will evaluate to the same values
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(y1))
print(sess.run(y2))  # both prints will return the same values

tf.get_variable

的旧回答

您可以尝试使用tf.get_variable()功能。 (见tutorial

使用reuse=False的变量范围实现第一个网络:

with tf.variable_scope('Inference', reuse=False):
    weights_1 = tf.get_variable('weights', shape=[1, 1],
                              initializer=...)
    output_1 = weights_1 * input_1

然后使用相同的代码实现第二个,除了使用reuse=True

with tf.variable_scope('Inference', reuse=True):
    weights_2 = tf.get_variable('weights')
    output_2 = weights_2 * input_2

第一个实现将创建并初始化LSTM的每个变量,而第二个实现将使用tf.get_variable()来获取第一个网络中使用的相同变量。这样,变量将共享

然后你只需要使用你想要的任何损失(例如你可以使用两个暹罗网络之间的L2距离),渐变将通过两个网络反向传播,用渐变之和更新共享变量