张量不是这个图的一个元素 - 一个项目中使用的两个模型



我在项目中使用了两个模型。我以这种方式实例化它们:

models.py:

import keras
def CNN_answer_from_model():
return keras.models.load_model('./KerasModels/CNN_answer.h5')
def CNN_student_index_from_model():
return keras.models.load_model('./KerasModels/CNN_student_index.h5')

DNNApi.py:

import Src.Net.model as model
import tensorflow as tf
class DNNApi:
def __init__(self):
self.CNN_student_index_model = model.CNN_student_index_from_model()
self.CNN_answer_model = model.CNN_answer_from_model()
def evaluate_index(self, img):
required_height = 290
required_width = 60
for img_index_column in get_index_column(img, required_height, required_width):
self.CNN_student_index_model._make_predict_function()
graph = tf.get_default_graph()
with graph.as_default():
value = self.CNN_student_index_model.predict(img_index_column)
...
def evaluate_answers(self, img):
# iterate over all AnswerContainer class objects
for answer_container, img in get_answer_row(img):
self.CNN_answer_model._make_predict_function()
graph = tf.get_default_graph()
with graph.as_default():
predict = self.CNN_answer_model.predict(img)
...

我所做的是首先从图像中评估学生指数,然后回答

计算索引很好,整个函数正确执行,但随后调用evaluate_answers,完全符合self.CNN_answer_model._make_predict_function()失败,并出现此错误:

Tensor Tensor("activation_11/Sigmoid:0", shape=(?, 4), dtype=float32) is not an element of this graph.

我已经尝试了我找到的所有解决方案,但他们几乎没有说明原因,主要是我这样做了 [...],它有帮助,这就是为什么我默认图形并进行预测函数调用。它对我没有帮助。

在以前的版本中,每次评估任何东西时我都会创建模型,它工作正常,但非常慢且内存耗尽,这就是我尝试将其更改为此方法的原因,无论如何这意味着它不是保存的模型错误。

我应该更改什么?原因是什么?我在项目中的任何地方都使用 Keras,而不是tf.keras或其他任何东西。tf.keras曾经在那里使用过一次,只是为了检查它是否会以某种方式帮助我。

在那里找到了一个解决方案:Keras github问题

现在 DNNApi 初始化看起来像这样:

from tensorflow import Graph, Session
...
def __init__(self):
self.graph_student_index = Graph()
with self.graph_student_index.as_default():
self.session_student_index = Session()
with self.session_student_index.as_default():
self.CNN_student_index_model = model.CNN_student_index_from_model()
self.graph_answer = Graph()
with self.graph_answer.as_default():
self.session_answer = Session()
with self.session_answer.as_default():
self.CNN_answer_model = model.CNN_answer_from_model()

和示例预测:

with self.graph_student_index.as_default():
with self.session_student_index.as_default():
for img_index_column in get_index_column(img, required_height, required_width):
value = self.CNN_student_index_model.predict(img_index_column)

最新更新