QuestionsStackOverflow QuestionsStackOverflow - 1 year ago 146
Python Question

Save ft.tensor array with np.savetxt - Python/TensorFlow

I created this function in order to save all values of the variable layer in an external file:

# Counter for total number of iterations performed so far
total_iterations = 0

def test_save(num_iterations):
# Ensure we update the global variable rather than a local copy
global total_iterations

for i in range(total_iterations, total_iterations + num_iterations):

x_batch, y_true_batch = next_batch_size(train_batch_size)

feed_dict_train = {x: x_batch, y_true: y_true_batch}

# Message for printing
msg = " Iteration: {0:>6}"

# Print it
print(msg.format(i + 1))

test = session.run(layer, feed_dict=feed_dict_train)

print 'test',test

store_all = []

store_all.append(test)

np.savetxt('test.txt', store_all, fmt='%5s')

# Call function
test_save(300)


But it seems that my append is not working, because when I open my test.txt file there is only 1 layer and not the 300 results.

My placeholders are:

# Placeholder variable for the input images
x = tf.placeholder(tf.float32, shape=[None, img_size_flat], name='x')

# Reshape 'x'
x_image = tf.reshape(x, [-1, img_size, img_size, num_channels])

# Placeholder variable for the true labels associated with the images
y_true = tf.placeholder(tf.float32, shape=[None, num_classes], name='y_true')


And my layer are:

<tf.Tensor 'Conv2D_1:0' shape=(?, 16, 16, 1) dtype=float32>

Answer Source

You initializied an empty list at each iteration of your loop. Just put it outside :

# Counter for total number of iterations performed so far
total_iterations = 0

def test_save(num_iterations):
    # Ensure we update the global variable rather than a local copy
    global total_iterations

    store_all = []

    for i in range(total_iterations, total_iterations + num_iterations):

        x_batch, y_true_batch = next_batch_size(train_batch_size)

        feed_dict_train = {x: x_batch, y_true: y_true_batch}

        # Message for printing
        msg = " Iteration: {0:>6}"

        # Print it
        print(msg.format(i + 1))

        test = session.run(layer, feed_dict=feed_dict_train)

        print 'test',test

        store_all.append(test)

    np.savetxt('test.txt', store_all, fmt='%5s')

# Call function
test_save(300)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download