ValueError:Tensor不是此图的元素

Tri*_*s95 0 python watchdog keras tensorflow

目前,我正在使用TensorFlow和Keras测试一些深度学习。现在,我想评估图片。因此,我需要借助看门狗类来了解是否在文件夹中创建了新图像。在这种情况下,我想做一个预测。因此,我需要首先从.json文件加载训练有素的深度学习模型,并使用.h5文件的权重对其进行初始化。此步骤需要一些时间。因此,我计划一次加载模型,随后我想做许多预测。不幸的是,我收到以下错误消息,并且我建议使用load_model出错。如果我为每个预测加载它,就没有问题,但是这种方式不是我想要的。

#####     Prediction-Class     #####

#Import
from keras.models import model_from_json
import numpy as np
from keras.preprocessing import image
from PIL import Image


class PredictionClass():
    #loaded_model = self.LoadModel()
    counter = 0

    def Load_Model(self):
        modelbez = 'modelMyTest30'
        gewichtsbez = 'weightsMyTest30'

        # load json and create model
        print("Loading...")
        json_file = open(modelbez + '.json', 'r')
        loading_model_json = json_file.read()
        json_file.close()
        loading_model = model_from_json(loading_model_json)
        # load weights into new model
        loading_model.load_weights(gewichtsbez + ".h5")
        print('Loaded model from disk:' + 'Modell: ' + modelbez + 'Gewichte: ' + gewichtsbez)

        loading_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
        return loading_model

    def Predict(path, loaded_model):
         test_image = image.load_img(path, target_size = (64, 64))
         test_image = image.img_to_array(test_image)
         test_image = np.expand_dims(test_image, axis = 0)

         # This step causes the error
         result = loaded_model.predict(test_image)
         print('Prediction successful')

         if result[0][0] == 1:
            prediction = 'schlecht'
            img = Image.open(path)
            img.save(path, "JPEG", quality=80, optimize=True, progressive=True)
            #counterschlecht = counterschlecht +1

         else:
            prediction = 'gut'
            img = Image.open(path)
            img.save(path, "JPEG", quality=80, optimize=True, progressive=True)
            #countergut = countergut +1  

         print("Image "+" contains: " + prediction);


#####     FileSystemWatcher     #####

#Import
import time
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer  

#Class-Definition "MyFileSystemHandler"
class MyFileSystemHandler(FileSystemEventHandler):
    def __init__(self, PredictionClass, loaded_model_Para):
        self.predictor = PredictionClass
        self.loaded_model= loaded_model_Para

    def on_created(self, event):
        #Without this wait-Step I got an Error "Permission denied
        time.sleep(10)
        PredictionClass.Predict(event.src_path, self.loaded_model)
        print('Predict')


#####     MAIN     #####

predictor = PredictionClass()
print('Class instantiated')
loaded_model_Erg = predictor.Load_Model()
print('Load Model')

if __name__ == "__main__":
    event_handler = MyFileSystemHandler(predictor, loaded_model_Erg)

    observer = Observer()
    observer.schedule(event_handler, path='C:\\Users\\...\\Desktop', recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(0.1)
    except KeyboardInterrupt:
        #Press Control + C to stop the FileSystemWatcher
        observer.stop()

    observer.join()
Run Code Online (Sandbox Code Playgroud)

错误:

ValueError:Tensor Tensor(“ dense_2 / Sigmoid:0”,shape =(?, 1),dtype = float32)不是此图的元素。

Mit*_*iku 5

如果要使用keras模型从多个线程进行预测,则应先调用model._make_predict_function函数再进行线程化。你可以找到更多在这里和github上的问题在这里

predictor = PredictionClass()
print('Class instantiated')
loaded_model_Erg = predictor.Load_Model()
loaded_model_Erg._make_predict_function()
print('Load Model')
Run Code Online (Sandbox Code Playgroud)