Question
How to load data into placeholder for once, and then run multiple computations on data in the placeholder?
Use case
- I have 100 numpy arrays (A1, ..., A100) with the same shape.
- The objective function depends on both the input data and an array of variables B.
- For example, the loss function for A1 can be `loss_1 = np.sum(A_1) + np.sum(B_1).
- For each An, I want to find the array of variables Bn that minimize the corresponding loss function lossn.
- The result should be 100 arrays of variables, which are: B1,...,B100
I want to load A1, find B1, and then repeat for the rest of the A arrays.
Attempt 1
Loading the A arrays with tf.constant
would lead to out of memory. After I load A1 and find B1. When I load A2, A1 will still stay in the memory of the GPU. After a while, the program will use up all memory of the GPU.
Attempt 2
Use placeholder, and load the same data in every step of the minimization. That will be slow because transferring data to the GPU is slow.
import tensorflow as tf
x = tf.placeholder("float", None)
y = x * 2
with tf.Session() as session:
for j in range(100): # Iterate over the 100 A arrays
A_n = [1, 2, 3] # The 100 different A arrays.
for i in range(300): # Steps of one minimization
# Why do I have to feed the same data for 300 times??
result = session.run(y, feed_dict={x: A_n})
print(result)