问题描述
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的函数式模型的model时
import keras
keras.backend.clear_session()
当然这似乎不是一种正常的解决思路。
方法二:
加载模型后,先执行一次model.predict()操作,之后的调用就不会出问题了
model = load_model(filepath=model_path)
y = model.predict(x)
因此,在大多数的建立模型立即predict的demo测试中,并不出现问题。
这似乎也不是一种正常的解决思路。
方法三:
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()
参考文章
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模型时出现的ValueError("Tensor %s is not an element of this graph." % obj)问题
https://blog.csdn.net/weixin_30034903/article/details/106144194
https://blog.csdn.net/xxzhix/article/details/81983982