Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject values into the middle of TensorFlow graph?

Consider the following code:

x = tf.placeholder(tf.float32, (), name='x')
z = x + tf.constant(5.0)
y = tf.mul(z, tf.constant(0.5))

with tf.Session() as sess:
    print(sess.run(y, feed_dict={x: 30}))

The resulting graph is x -> z -> y. Sometimes I'm interested in computing y all the way from from x but sometimes I have z to start and would like inject this value into the graph. So the z needs to behave like a partial placeholder. How can I do that?

(For anyone interested why I need this. I am working with an autoencoder network which observes an image x, generates an intermediate compressed representation z, then computes reconstruction of image y. I'd like to see what the network reconstructs when I inject different values for z.)

like image 334
iramusa Avatar asked Jan 12 '17 19:01

iramusa


1 Answers

Use placeholder with default in the following way:

x = tf.placeholder(tf.float32, (), name='x')
# z is a placeholder with default value
z = tf.placeholder_with_default(x+tf.constant(5.0), (), name='z')
y = tf.mul(z, tf.constant(0.5))

with tf.Session() as sess:
    # and feed the z in
    print(sess.run(y, feed_dict={z: 5}))

Silly me.

like image 87
iramusa Avatar answered Sep 18 '22 22:09

iramusa