Tensorflow同时加载使用多个模型

时间:2023-03-10 02:41:16
Tensorflow同时加载使用多个模型

在Tensorflow中,所有操作对象都包装到相应的Session中的,所以想要使用不同的模型就需要将这些模型加载到不同的Session中并在使用的时候申明是哪个Session,从而避免由于Session和想使用的模型不匹配导致的错误。而使用多个graph,就需要为每个graph使用不同的Session,但是每个graph也可以在多个Session中使用,这个时候就需要在每个Session使用的时候明确申明使用的graph。

g1 = tf.Graph() # 加载到Session 1的graph
g2 = tf.Graph() # 加载到Session 2的graph sess1 = tf.Session(graph=g1) # Session1
sess2 = tf.Session(graph=g2) # Session2 # 加载第一个模型
with sess1.as_default():
with g1.as_default():
tf.global_variables_initializer().run()
model_saver = tf.train.Saver(tf.global_variables())
model_ckpt = tf.train.get_checkpoint_state(“model1/save/path”)
model_saver.restore(sess, model_ckpt.model_checkpoint_path)
# 加载第二个模型
with sess2.as_default(): # 1
with g2.as_default():
tf.global_variables_initializer().run()
model_saver = tf.train.Saver(tf.global_variables())
model_ckpt = tf.train.get_checkpoint_state(“model2/save/path”)
model_saver.restore(sess, model_ckpt.model_checkpoint_path) ... # 使用的时候
with sess1.as_default():
with sess1.graph.as_default(): # 2
... with sess2.as_default():
with sess2.graph.as_default():
... # 关闭sess
sess1.close()
sess2.close()

注:1、在1处使用as_default使session在离开的时候并不关闭,在后面可以继续使用知道手动关闭;2、由于有多个graph,所以sess.graph与tf.get_default_value的值是不相等的,因此在进入sess的时候必须sess.graph.as_default()明确申明sess.graph为当前默认graph,否则就会报错。

PS:不同框架的模型(tf, caffe, torch等)在加载的很有可能导致底层的cuDNN分配出现问题从而报错,这种一般可以尝试通过模型的加载顺序来解决。

参考:

https://www.tensorflow.org/api_docs/python/tf/Session

https://*.com/questions/41607144/loading-two-models-from-saver-in-the-same-tensorflow-session