Implementando una Red Siamesa en Tensor Flow

Quiero implementar una red neuronal convolucional siamesa, donde dos imágenes comparten pesos en las capas convolucionales, y luego se concatenan antes de pasar a través de las capas completamente conectadas. He intentado una implementación, pero parece más bien una solución "pirateada". En particular, he definido una operación en tensores como simplemente una función de Python, y no estoy seguro de si esto está permitido.

Aquí está el código que he probado:

images = tf.placeholder(tf.float32, shape=[None, 64 * 64])
# Convolutional layers
# ...
# ...
# Results in pool3_flat, which is the flattened output of the third convolutional layer
pool3_flat = tf.reshape(pool3, [-1, 8 * 8 * 128])

# Now, merge the image pairs, where each pair is composed of adjacent images in the batch, with a stride of 2
def merge_pairs():
  # Create a tensor to store the merged image pairs
  # The batch size is 128, therefore there will be 64 pairs (64 in the first dimension of this tensor)
  merged_pairs = tf.Variable(tf.zeros([64, 8 * 8 * 128]))
  # Split the images into 64 pairs
  pairs = tf.split(0, 64, pool3_flat)
  # For each pair, concatenate the two images across dimension 1, and set this tensor in the appropriate row of merged_pairs
  for pair_num, pair in enumerate(pairs):
      merged_pair = tf.concat(1, pair)
      merged_pairs[pair_num] = merged_pair
  return merged_pairs


# Proceed with operations on the merged_pair tensor, as if the batch size is 64
fc4 = tf.matmul(merge_pairs(), weights4)
# ...
# ...

Si bien esto se compila y parece funcionar bien, los resultados no son realmente los esperados. Entonces, me pregunto si hay una mejor manera de implementar una red siamesa utilizando operaciones integradas en TensorFlow.

Respuestas a la pregunta(1)

Su respuesta a la pregunta