【问题标题】:keras unable to call model.predict_classes for multiple timeskeras 无法多次调用 model.predict_classes
【发布时间】:2019-04-21 03:06:54
【问题描述】:
def predictOne(imgPath):

    model = load_model("withImageMagic.h5")
    image = read_image(imgPath)
    test_sample = preprocess(image)
    predicted_class = model.predict_classes(([test_sample]))
    return predicted_class

我已经训练了一个模型。在这个函数中,我加载我的模型,读取一张新图像,进行一些预处理,最后预测它的标签。

当我运行我的 main.py 文件时,这个函数被调用并且一切顺利。然而,几秒钟后,这个函数将被另一个图像再次调用,我得到这个错误:

'Cannot interpret feed_dict key as Tensor: ' + e.args[0])

TypeError:无法将 feed_dict 键解释为 Tensor:Tensor Tensor("Placeholder:0", shape=(5, 5, 1, 32), dtype=float32) 不是此图的元素。

这个功能只在第一次起作用,这很奇怪。我测试了多张图片并得到了相同的行为。

Windows 10 - 带有 keras 的 tensorflow-gpu

【问题讨论】:

  • 尝试从函数外部的文件中加载模型,并将model 对象作为函数def predictOne(imgPath, model) 的参数。这也会快得多。如果要在函数内部继续加载模型,请在加载模型之前使用from keras import backend as K; K.clear_session()
  • 成功了。将其发布为答案,以便我接受它
  • 好的,太好了!我发布了答案。

标签: python tensorflow machine-learning keras prediction


【解决方案1】:

尝试从函数外部的文件中加载模型,并将模型对象作为函数def predictOne(imgPath, model) 的参数。这也会快得多,因为每次需要预测时都不需要从磁盘加载权重。

如果要在函数内部继续加载模型,请导入后端:

from keras import backend as K

然后

K.clear_session() 

在加载模型之前。

【讨论】:

    【解决方案2】:
    class one_model:
        session = None
        graph = None 
        loadModel = None
        __instance = None
        @staticmethod
        def getInstance(modelPath):
            """ Static access method. """
            if one_model.__instance == None:
                one_model.__instance = one_model(modelPath)
            return one_model.__instance
            
        def __init__(self, modelPath):
            self.modelPath = modelPath
            self.session = tf.Session(graph=tf.Graph())
            self.loadOneModel()
                
        def loadOneModel(self):
            try:
                with self.session.graph.as_default():
                    K.set_session(self.session)
                    self.loadModel = keras.models.load_model(self.modelPath)               
            except Exception as e:
                logging.error(str(e))
                print(str(e))
                            
        def getPredictionOne(self, input_file_path): 
            #Predict the data once the model is loaded
            if self.loadModel is not None and self.session is not None: 
                try:
                    image = load_img(input_file_path, target_size=inputShape)
                    image = img_to_array(image)
                    image = np.expand_dims(image, axis=0)
                    image = preprocess(image)
                    with self.session.graph.as_default():
                        K.set_session(self.session)
                        preds = self.loadModel.predict(image)
                        return preds
                except Exception as e:
                    logging.error(str(e))
            
            return -1
    
    
    if __name__== "__main__": 
        #First Model 
        data = web.input()
            fileapth = data.imagefilepath  
            modelfilepath = data.modelfilepath
            one_modelObj = one_model.getInstance(modelfilepath)        
            value = one_modelObj.getPredictionOne(fileapth) 
    

    【讨论】:

    • 虽然这段代码 sn-p 可以解决问题,但它没有解释为什么或如何回答这个问题。请include an explanation for your code,因为这确实有助于提高您的帖子质量。请记住,您正在为将来的读者回答问题,而这些人可能不知道您的代码建议的原因。您可以使用edit 按钮改进此答案以获得更多选票和声誉!
    猜你喜欢
    • 1970-01-01
    • 2019-10-27
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多