Skip to content

Instantly share code, notes, and snippets.

@Breta01
Last active July 20, 2020 09:19
Show Gist options
  • Select an option

  • Save Breta01/cabbb5c7d9bbd3d9b4ec404828ac24bb to your computer and use it in GitHub Desktop.

Select an option

Save Breta01/cabbb5c7d9bbd3d9b4ec404828ac24bb to your computer and use it in GitHub Desktop.
Class for importing multiple TensorFlow graphs.
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)
@jasonk33

Copy link
Copy Markdown

great work

@dancasas

Copy link
Copy Markdown

Very helpful! Thanks!

@Breta01

Breta01 commented Mar 6, 2018

Copy link
Copy Markdown
Author

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]

@Shawn617

Copy link
Copy Markdown

May I ask which version of tf you are using? Thank you

@Breta01

Breta01 commented May 30, 2018

Copy link
Copy Markdown
Author

@Shawn617 I am using TensorFlow 1.5. DId you encounter some problems?

@ynuwm

ynuwm commented Jul 11, 2019

Copy link
Copy Markdown

I have 100 models, is this method works? Thank you.

@Breta01

Breta01 commented Jul 11, 2019

Copy link
Copy Markdown
Author

@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