На данный момент я тестирую глубокое обучение с помощью 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 ("density_2 / Sigmoid: 0", shape = (?, 1), dtype = float32) не является элементом этого графа.