首页 > 解决方案 > 如何在flask中同时预测由tensorflow(.pb)模型和keras模型(.h5)组成的多个模型?

问题描述

我试图完整地描述这些情况。但由于我的语言能力,可能会有一些不清楚的陈述。请告诉我。我将尝试解释我的意思。

最近想将facenet(我是说davisking在github上的项目)应用到我的项目中。因此,我写了一个类

class FacenetEmbedding:
def __init__(self, model_path):
    self.sess = tf.InteractiveSession()
    self.sess.run(tf.global_variables_initializer())
    # Load the model
    facenet.load_model(model_path)
    # Get input and output tensors
    self.images_placeholder = tf.get_default_graph().get_tensor_by_name("input:0")
    self.tf_embeddings = tf.get_default_graph().get_tensor_by_name("embeddings:0")
    self.phase_train_placeholder = tf.get_default_graph().get_tensor_by_name("phase_train:0")

def get_embedding(self, images):
    feed_dict = {self.images_placeholder: images, self.phase_train_placeholder: False}
    embedding = self.sess.run(self.tf_embeddings, feed_dict=feed_dict)
    return embedding

def free(self):
    self.sess.close()

我可以在烧瓶中独立使用这个类。

model_path = "models/20191025-223514/"
fe = FacenetEmbedding(model_path)

但后来我有不同的要求。我使用 keras 训练了两个模型。我想用它们(.h5 模型)和上面的 facenet 模型来预测。我先加载它们。

modelPic = load_model('models/pp.h5')
lePic = pickle.loads(open('models/pp.pickle', "rb").read())
print(modelPic.predict(np.zeros((1, 128, 128, 3))))

modelM = load_model('models/pv.h5')
leM = pickle.loads(open('models/pv.pickle', "rb").read())
print(modelM.predict(np.zeros((1, 128, 128, 3))))

我打印假图像来测试模型。它似乎可以正常工作。但是当我运行烧瓶服务器并尝试将图像发布到此 api 时,会弹出消息并且预测不起作用。

Tensor input_1_3:0, specified in either feed_devices or fetch_devices was not found in the Graph
Exception ignored in: <bound method BaseSession._Callable.__del__ of <tensorflow.python.client.session.BaseSession._Callable object at 0x7ff27d0f0dd8>>
Traceback (most recent call last):
  File "/home/idgate/.virtualenvs/Line_POC/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1455, in __del__
    self._session._session, self._handle, status)
  File "/home/idgate/.virtualenvs/Line_POC/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 528, in __exit__
    c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: No such callable handle: 140675571821088

我尝试使用这两个 keras 模型而不在烧瓶服务器中加载 facenet 模型。它工作正常。我认为它必须与某些东西(可能是关于会话?)发生冲突,以使这三个模型不能同时工作。但我不知道如何解决这个问题。请帮我!提前致谢。

标签: tensorflowflaskkeras

解决方案


推荐阅读