如何在 Tensorflow 中复制操作和占位符

How to duplicate operations & placeholders in Tensorflow

假设我定义了两个神经网络模型,每个模型都有 1 个输入占位符和 1 个输出张量。从这 2 个输出中,我需要 3 个单独的值。

inputs: i1, i2, outputs: o1, o2
a = 1
b = 2

v1 = session.run(o1, feed_dict={i1: a})
v2 = session.run(o1, feed_dict={i1: b})
v3 = session.run(o2, feed_dict={i2: a})

问题是我需要将这 3 个值输入到损失函数中,所以我不能执行上述操作。我需要做

loss = session.run(L, feed_dict={i1: a, i1: b, i2:a })

我认为我做不到,但即使我可以,我在以后的操作中仍然会有歧义,因为输入 i1 的 o1 与输入 i2 的 o1 的使用方式不同。

我认为可以通过在第一个神经网络中设置 2 个输入占位符和 2 个输出来解决这个问题。所以如果我已经有了一个模型,有没有办法重组输入和输出以便我可以适应这个?

视觉上我想转

i1 ---- (model) ----- o1 

进入

i1a                          o1a
  \                         /
   \                       /
    x ----- (model) ----- x        
   /                       \
  /                         \
i1b                          o1b

您的直觉是正确的,您必须为网络 1 创建 2 个不同的占位符 i1a 和 i1b,具有两个输出 o1a 和 o1b。你的视觉效果看起来很棒所以这是我的建议:

i1a  ----- (model) -----  o1a
              |            
        shared weights                                  
              |            
i1b  ----- (model) -----  o1b

正确的方法是使用 tf.get_variable() 为每个带有 reuse=True 的变量复制您的网络。

def create_variables():
  with tf.variable_scope('model'):
    w1 = tf.get_variable('w1', [1, 2])
    b1 = tf.get_variable('b1', [2])

def inference(input):
  with tf.variable_scope('model', reuse=True):
    w1 = tf.get_variable('w1')
    b1 = tf.get_variable('b1')
    output = tf.matmul(input, w1) + b1
  return output

create_variables()

i1a = tf.placeholder(tf.float32, [3, 1])
o1a = inference(i1a)

i1b = tf.placeholder(tf.float32, [3, 1])
o1b = inference(i1b)

loss = tf.reduce_mean(o1a - o1b)


with tf.Session() as sess:
  sess.run(tf.initialize_all_variables())
  sess.run(loss, feed_dict={i1a: [[0.], [1.], [2.]], i1b: [[0.5], [1.5], [2.5]]})