Teywazz
Teywazz

Reputation: 131

Tensorflow: How to use a trained model in a application?

I have trained a Tensorflow Model, and now I want to export the "function" to use it in my python program. Is that possible, and if yes, how? Any help would be nice, could not find much in the documentation. (I dont want to save a session!)

I have now stored the session as you suggested. I am loading it now like this:

f = open('batches/batch_9.pkl', 'rb')
input = pickle.load(f)
f.close()
sess = tf.Session()

saver = tf.train.Saver()
saver.restore(sess, 'trained_network.ckpt')
y_pred = []

sess.run(y_pred, feed_dict={x: input})

print(y_pred)

However, I get the error "no Variables to save" when I try to initialize the saver.

What I want to do is this: I am writing a bot for a board game, and the input is the situation on the board formatted into a tensor. Now I want to return a tensor which gives me the best position to play next, i.e. a tensor with 0 everywhere and a 1 at one position.

Upvotes: 13

Views: 18778

Answers (2)

Freeman
Freeman

Reputation: 6216

To load a model, or train and save the model if it does not exit

if os.path.exists('MNIST.h5'):
    model = tf.keras.models.load_model('MNIST.h5')
else:
    model.fit(train_X,train_y, epochs=30)
    model.save('MNIST.h5')

Upvotes: 0

aseipel
aseipel

Reputation: 728

I don't know if there is any other way to do it, but you can use your model in another Python program by saving your session:

Your training code:

# build your model

sess = tf.Session()
# train your model
saver = tf.train.Saver()
saver.save(sess, 'model/model.ckpt')

In your application:

# build your model (same as training)
sess = tf.Session()
saver = tf.train.Saver()
saver.restore(sess, 'model/model.ckpt')

You can then evaluate any tensor in your model using a feed_dict. This obviously depends on your model. For example:

#evaluate tensor
sess.run(y_pred, feed_dict={x: input_data})

Upvotes: 9

Related Questions