Created
May 17, 2017 15:00
-
-
Save krosaen/fa9d84400d7119d161aba159ea835e38 to your computer and use it in GitHub Desktop.
exploring feeding values into a graph with and without queues
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
def test_feed_independent_graph(): | |
""" | |
Example of a computation graph that depends on a placeholder. | |
How can we feed in values from a queue? As it turns out, you need separate | |
sess.run calls to deq and then feed the graph. | |
""" | |
# simple graph: adds together numbers in a pair | |
pair = tf.placeholder(tf.int32, [2], name='pair') | |
plus = pair[0] + pair[1] | |
with tf.Session() as sess: | |
print("feeding a tuple directly: 3 + 4 = {}".format(sess.run(plus, feed_dict={pair: [3, 4]}))) | |
# a queue of tuples | |
q = tf.FIFOQueue(10, tf.int32) | |
enq_tuple = tf.placeholder(tf.int32, [2]) | |
enq = q.enqueue(enq_tuple) | |
deq = q.dequeue() | |
print("attempting to add directly rom dequeue operation") | |
with tf.Session() as sess: | |
sess.run(enq, feed_dict={enq_tuple: [3, 4]}) | |
try: | |
sess.run(plus, feed_dict={pair: deq}) | |
except TypeError as e: | |
print("failed to feed in pair from deq: {}".format(e)) | |
with tf.Session() as sess: | |
sess.run(enq, feed_dict={enq_tuple: [3, 4]}) | |
sess.run(enq, feed_dict={enq_tuple: [5, 7]}) | |
next_item = sess.run(deq) | |
print("can feed tuple after it's been dequeued: {} + {} = {}".format( | |
next_item[0], next_item[1], | |
sess.run(plus, feed_dict={pair: next_item}))) | |
next_item = sess.run(deq) | |
print("can feed tuple after it's been dequeued: {} + {} = {}".format( | |
next_item[0], next_item[1], | |
sess.run(plus, feed_dict={pair: next_item}))) | |
def test_queue_baked_into_graph(): | |
""" | |
Example where we bake a queue into the computation graph | |
""" | |
q = tf.FIFOQueue(10, tf.int32) | |
enq_tuple = tf.placeholder(tf.int32, [2]) | |
enq = q.enqueue(enq_tuple) | |
deq = q.dequeue() | |
plus = deq[0] + deq[1] | |
with tf.Session() as sess: | |
sess.run(enq, feed_dict={enq_tuple: [3, 4]}) | |
sess.run(enq, feed_dict={enq_tuple: [5, 7]}) | |
# note: running `deq` just so we can inspect its value | |
print("adding together {} yields {}".format(*sess.run([deq, plus]))) | |
print("adding together {} yields {}".format(*sess.run([deq, plus]))) | |
def format_fn_doc(fn): | |
d = fn.__doc__.strip() | |
dls = ["***"] + d.split("\n") + ["***"] | |
return "\n{}\n".format("\n".join([l.strip() for l in dls])) | |
print(format_fn_doc(test_feed_independent_graph)) | |
test_feed_independent_graph() | |
print(format_fn_doc(test_queue_baked_into_graph)) | |
test_queue_baked_into_graph() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output from running this: