I have a CNN model written using tensorflow for python, the model is for classifying lung CT images (cancer/no-cancer), after training the model with training and validation data and get a reasonable accuracy, after all, that I need to test the model with test data, but I don't know how to do that? how to save the model and using it for testing?


1 Answer 1


You can find the details in this tutorial: Save CNN model

To summarize:

Tensorflow variables are only alive inside a session. So, you have to save the model inside a session by calling save method on saver object.

import tensorflow as tf
saver = tf.train.Saver()
sess = tf.Session()
saver.save(sess, 'my_test_model')

For saving the model after 1000 iterations, call save by passing the step count:

saver.save(sess, 'my_test_model',global_step=1000)

To use pre-trained model for fine-tuning:

with tf.Session() as sess:    
    saver = tf.train.import_meta_graph('my-model-1000.meta')
##Model has been restored. Above statement will print the saved value of w1.

To add more operations to the graph by adding more layers and then train it.

#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')

# Now, let's access and create placeholders variables and
# create feed-dict to feed new data

graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}

#Now, access the op that you want to run. 
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")

#Add more to the current graph
add_on_op = tf.multiply(op_to_restore,2)

print sess.run(add_on_op,feed_dict)
#This will print 120.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.