buydadip
buydadip

Reputation: 9437

How to save a numpy array as a Tensorflow Variable

I am doing some calculation, and I want to store the resulting matrix as a Variable that I can restore and re-use it elsewhere. Here is my calculation...

# Initializing the variables.
init = tf.global_variables_initializer()

saver = tf.train.Saver()

with tf.Session() as sess:

    sess.run(init)

    total_batch = int(features.train.num_examples/100)

    train_images = []

    for i in range(total_batch):

        batch_xs, batch_ys = features.train.next_batch(100)

        batch_xs = sess.run(tf.reshape(batch_xs, [100, 28, 28, 1]))

        train_images.append(batch_xs)

    train_images = np.array(train_images)

    # save model
    save_path = saver.save(sess, "/tmp/parsed_data.ckpt")

train_images is a numpy array. I want to be able to store this into a Tensorflow Variable and then save the model so that I can use the Variable in another Tensorflow script. How can I do this? An extra note, the shape of the numpy array is (550, 100, 28, 28, 1).

I found this tutorial https://learningtensorflow.com/lesson4/ but it is not very useful because place_holders cannot be saved.

Upvotes: 1

Views: 2215

Answers (1)

Avijit Dasgupta
Avijit Dasgupta

Reputation: 2065

You save the numpy array train_images as numpy first. Use the following code:

np.save('train_image.npy', train_images)

When you are loading the numpy array in another script, use the tf.stack function. An example given below -

import tensorflow as tf
import numpy as np

array = np.load('train_images.npy')
tensor = tf.stack(array)

Upvotes: 8

Related Questions