TensorFlow——在web.py、Django环境下TensorFlow(Keras、tf.keras)加载和使用多模型失败解决方案
問題描述
Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder_8:0", shape=(3, 3, 128, 256), dtype=float32) is not an element of this graph
ValueError: Variable conv1/weights already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:
Tensor Tensor("Placeholder:0", shape=(3, 3, 3, 32), dtype=float32) is not an element of this graph.?
問題分析
在Tensorflow中,所有操作對象都包裝到相應的Session中的,所以想要使用不同的模型就需要將這些模型加載到不同的Session中并在使用的時候申明是哪個Session,從而避免由于Session和想使用的模型不匹配導致的錯誤。
而使用多個graph,就需要為每個graph使用不同的Session,但是每個graph也可以在多個Session中使用,這個時候就需要在每個Session使用的時候明確申明使用的graph。
解決方案
方法一:
當建立一個from keras.models import Sequential的序貫模型或者是from keras.models import Model的函數(shù)式模型的model時
import keras keras.backend.clear_session()當然這似乎不是一種正常的解決思路。
方法二:
加載模型后,先執(zhí)行一次model.predict()操作,之后的調用就不會出問題了
model = load_model(filepath=model_path) y = model.predict(x)因此,在大多數(shù)的建立模型立即predict的demo測試中,并不出現(xiàn)問題。?
這似乎也不是一種正常的解決思路。?
方法三:
TensorFlow——加載和使用多個模型解決方案
g1 = tf.Graph() # 加載到Session 1的graph g2 = tf.Graph() # 加載到Session 2的graphsess1 = 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(): # 1with 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()參考文章
TensorFlow——加載和使用多個模型解決方案
https://stackoverflow.com/questions/41607144/loading-two-models-from-saver-in-the-same-tensorflow-session
https://stackoverflow.com/questions/39175945/run-multiple-pre-trained-tensorflow-nets-at-the-same-time
Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder_8:0", shape=(3, 3, 128, 256), d
ValueError: Tensor Tensor("Placeholder:0", shape=(3, 3, 1, 32), dtype=float32)
解決在django中應用keras模型時出現(xiàn)的ValueError("Tensor %s is not an element of this graph." % obj)問題
將keras模型在django中應用時出現(xiàn)的小問題
Django使用Keras的幾個坑
解決Django中調用keras的模型出現(xiàn)的問題
https://blog.csdn.net/weixin_30034903/article/details/106144194
https://blog.csdn.net/xxzhix/article/details/81983982
[2020/05/12 更新] Django調用Keras的模型
tensorflow多次restore模型出錯
Keras與Django整合問題(keras反復識別問題)
https://www.freesion.com/article/7982900117/
總結
以上是生活随笔為你收集整理的TensorFlow——在web.py、Django环境下TensorFlow(Keras、tf.keras)加载和使用多模型失败解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TensorFlow——加载和使用多个模
- 下一篇: PyYAML——yaml.load()警