2016-06-11 75 views
1

假设我有两个神经网络模型,每个模型具有1个输入占位符和1个输出张量。从这2个输出我需要3个不同的值。如何在Tensorflow中复制操作和占位符

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为您的网络1,具有两个输出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]]})