18

APScheduler定时任务中调用keras模型异常报错的解决方法

 4 years ago
source link: https://zmister.com/archives/1368.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

最近借助Keras训练了一个用于识别图片验证码的模型,后期需要使用APScheduler模块来实现定时任务,在任务中会调用训练好的Keras模型。

在正常情况下,调用任务方法,执行没有问题:

if __name__ == '__main__':
    # scheduler = BlockingScheduler()
    # scheduler.add_job(func=main,trigger='cron',hour='7',minute=20,misfire_grace_time=300)
    # scheduler.add_job(func=main,trigger='interval',minute=60)
    # scheduler.start()
    main()

一旦使用apscheduler创建添加定时任务,到了指定的时间允许,就会出现下面的异常报错:

ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 28), dtype=float32) is not an element of this graph.

出现这种异常报错,我们只需要多添加一行代码即可解决。

在正常情况下,我们的模型通过Keras的models模块中的load_model()方法进行加载:

from keras.models import load_model
# 加载训练好的神经网络
model = load_model(MODEL_FILENAME)

这在APScheduler的定时任务中,使用model的predict()方法进行预测结果时,就会出现上述的异常报错。我们在加载完模型之后,再显式地声明一下模型的predict功能函数就可以了,代码如下所示:

from keras.models import load_model
# 加载训练好的神经网络
model = load_model(MODEL_FILENAME)
model._make_predict_function()

这样,APScheduler的定时任务在执行的时候就不会出现上面的异常报错了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK