Как загрузить модель предсказания один раз, а не при каждом вызове скрипта?
У меня есть очень простой API, который предсказывает наличие или отсутствие небезопасного поведения водителя. Помимо определения нерегулярности поведения, API позволяет охарактеризовать совершенное нарушение.
API также позволяет генерировать тепловую карту, чтобы определить, какая часть изображения позволила моделям сделать свои прогнозы.
Пока что API загружает модель ClassificationModel каждый раз, когда мы запрашиваем ее на изображении, переданном через скрипт. Как загрузить модель только один раз?
main.py
from model import ClassificationModel
import argparse
import os
def predict_img(img_path, with_heatmap=False):
model = ClassificationModel() <--- Aqui descargo el modelo cada vez que llamo a predict_img
row = model.predict(img_path=img_path, row=None, img=None, load=True, original_image_path=img_path,
print_heatmap=with_heatmap)
results = row.to_json()
print(results)
return results
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--path", "-p", help="path of the image", required=True)
parser.add_argument("--heatmap", "-heat", help="generate heatmap or not", required=True)
args = parser.parse_args()
if not(os.path.exists(args.path)):
raise FileNotFoundError("{} does not exist.".format(args.path))
elif args.path.split(".")[-1] not in ["png", "jpg", "jpeg"]:
raise TypeError("The file is not a valid image file.")
if args.heatmap.upper() == "TRUE":
args.heatmap = True
else:
args.heatmap = False
result = predict_img(img_path=args.path, with_heatmap=args.heatmap)
model.py
import numpy as np
np.random.seed(40)
from keras_preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import load_model
import settings as st
from predict import Predict
class ClassificationModel(Predict):
def __init__(self):
self.list_pos = [
"safe driving",
"texting - right",
"talking to the phone - right",
"texting - left",
"talking on the phone - left",
"operating the radio",
"drinking",
"reaching behind",
"hair and makeup",
"talking to passenger"
]
self.image_size = 384
self.generator = ImageDataGenerator(brightness_range=[0.7, 1.5],
rotation_range=35,
fill_mode='nearest',
zoom_range=0.125,
rescale=1. / 255)
self.model = load_model(st.model_path)
self.threshold = 0.5
self.n_step = 5
self.normal_index = 0
settings.py
model_path = "./model/classification.h5"
th = [0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5]
Я думал о том, чтобы сделать цикл while с самого начала. Мне посоветовали сделать систему, которая ждет некоторых входных данных через http/sockets но я не знаю, как это сделать.