Last active
July 20, 2020 09:19
-
-
Save Breta01/cabbb5c7d9bbd3d9b4ec404828ac24bb to your computer and use it in GitHub Desktop.
Class for importing multiple TensorFlow graphs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
class ImportGraph(): | |
""" Importing and running isolated TF graph """ | |
def __init__(self, loc): | |
# Create local graph and use it in the session | |
self.graph = tf.Graph() | |
self.sess = tf.Session(graph=self.graph) | |
with self.graph.as_default(): | |
# Import saved model from location 'loc' into local graph | |
saver = tf.train.import_meta_graph(loc + '.meta', | |
clear_devices=True) | |
saver.restore(self.sess, loc) | |
# There are TWO options how to get activation operation: | |
# FROM SAVED COLLECTION: | |
self.activation = tf.get_collection('activation')[0] | |
# BY NAME: | |
self.activation = self.graph.get_operation_by_name('activation_opt').outputs[0] | |
def run(self, data): | |
""" Running the activation operation previously imported """ | |
# The 'x' corresponds to name of input placeholder | |
return self.sess.run(self.activation, feed_dict={"x:0": data}) | |
### Using the class ### | |
data = 50 # random data | |
model = ImportGraph('models/model_name') | |
result = model.run(data) | |
print(result) |
Very helpful! Thanks!
I updated the code to also demonstrate the option of getting operation by name:
self.activation = self.graph.get_operation_by_name('activation_opt').outputs[0]
May I ask which version of tf you are using? Thank you
@Shawn617 I am using TensorFlow 1.5. DId you encounter some problems?
I have 100 models, is this method works? Thank you.
@ynuwm It should work. I am not sure if this is the most effective way for so many models.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
great work