TensorFlow中的Siamese神经网络

BiB*_*iBi 21 neural-network deep-learning lstm tensorflow

我正试图在TensorFlow中实现一个Siamese神经网络,但我无法在互联网上找到任何有用的例子(参见Yann LeCun论文).

在此输入图像描述

我正在尝试构建的体系结构将包含两个共享权重的LSTM,并且仅在网络末端连接.

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

谢谢 :)

编辑:我实现了一个连体网络的简单工作示例这里上MNIST.

Oli*_*rot 13

用.更新 tf.layers

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

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
Run Code Online (Sandbox Code Playgroud)

老答案 tf.get_variable

您可以尝试使用该功能tf.get_variable().(参见教程)

使用变量范围实现第一个网络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
Run Code Online (Sandbox Code Playgroud)

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

with tf.variable_scope('Inference', reuse=True):
    weights_2 = tf.get_variable('weights')
    output_2 = weights_2 * input_2
Run Code Online (Sandbox Code Playgroud)

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

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

  • 您还可以一次定义所有变量,例如`weights = tf.Variable(...)`,然后在每个推论中使用这些变量,即output_1 = weights * input_1和output_2 = weights * input_2`。与共享变量一样,这里的变量weights将接收两个渐变和两个渐变更新。 (2认同)