P.R.
P.R.

Reputation: 3917

Compute value of variable for multiple input values

I have a tensorflow graph which is trained. After training, I want to sample one variable for multiple intermediate values. Simplified:

a = tf.placeholder(tf.float32, [1])
b = a + 10
c = b * 10

Now I want to query c for values of b. Currently, I am using an outer loop

b_values = [0, 1, 2, 3, 4, 5]
samples = []
for b_value in b_values:
    samples += [sess.run(c,
                            feed_dict={b: [b_value]})]

This loop takes quite a bit of time, I think it is because b_values contains 5000 values in my case. Is there a way of running sess.run only once, and passing all b_values at once? I cannot really modify the graph a->b->c, but I could add something to it if that helps.

Upvotes: 0

Views: 39

Answers (1)

Harsha Pokkalla
Harsha Pokkalla

Reputation: 1802

You could do it as follows:

import tensorflow as tf
import numpy as np
import time

a = tf.placeholder(tf.float32, [None,1])
b = a + 10
c = b * 10

sess = tf.Session()
b_values = np.random.randint(500,size=(5000,1))
samples = []
t =  time.time()
for b_value in b_values:
        samples += [sess.run(c,feed_dict={b: [b_value]})]

print time.time()-t
#print samples    

t=time.time()
samples =  sess.run(c,feed_dict={b:b_values})
print time.time()-t
#print samples

Output: (time in seconds)

0.874449968338
0.000532150268555

Hope this helps !

Upvotes: 1

Related Questions