目前我正在使用TensorFlow和Keras测试一些深度学习。现在我想评估图片。因此,如果在文件夹中创建了新图像,我需要在监视程序类的帮助下知道。在这种情况下,我想做一个预测。因此,我需要先从.json文件加载训练有素的深度学习模型,然后使用.h5文件中的权重对其进行初始化。这一步需要一些时间。因此我计划加载模型一次,然后我想做很多预测。不幸的是我收到以下错误消息,我建议与loaded_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()
错误:
ValueError:Tensor Tensor(“dense_2 / Sigmoid:0”,shape =(?,1),dtype = float32)不是此图的元素。