我尝试在 django 中编写一个 REST api,它使用 Keras 模型返回预测。但是,那load_model()
函数需要一些时间来加载模型,我不希望我的用户必须等待这么长时间(每次初始化模型时)。初始化模型的正确方法是什么,以便加载一次并使用同一模型完成预测?
另一方面,我认为冷可能的一种方法是在 settings.py 中初始化模型,如下所示:
设置.py
json_file=open("model.json","r")
loaded_json=json_file.read()
json_file.close()
model=model_from_json(loaded_json)
model.load_weights("model.h5")
MODEL=model
然后在我的views.py中我使用这个变量MODEL作为:
views.py
from django.conf import settings
model=settings.MODEL
def index():
print "Predicting"
res=model.predict(numpy.stack([test_img]))
print res
如果一次只有一个用户处于活动状态(模型初始化一次,并且所有后续预测都使用该模型完成),那么这非常有效。但是,如果多个用户同时处于活动状态,那么它对于第一个调用来说效果很好,但后一个调用会给出错误
'NoneType' object has no attribute 'shape'
Apply node that caused the error: ConvOp{('imshp', (31, 31, 32)),('kshp', (3, 3)),('nkern', 64),('bsize', None),('dx', 1),('dy', 1),('out_mode', 'valid'),('unroll_batch', None),('unroll_kern', None),('unroll_patch', True),('imshp_logical', (31, 31, 32)),('kshp_logical', (3, 3)),('kshp_logical_top_aligned', True)}(InplaceDimShuffle{0,2,3,1}.0, InplaceDimShuffle{3,2,0,1}.0)
Toposort index: 13
Inputs types: [TensorType(float32, 4D), TensorType(float32, 4D)]
Inputs shapes: [(1L, 31L, 31L, 32L), 'No shapes']
Inputs strides: [(123008L, 124L, 4L, 3844L), 'No strides']
Inputs values: ['not shown', None]
Outputs clients: [[Elemwise{Composite{(i0 * ((i1 + i2) + Abs((i1 + i2))))}}[(0, 1)](TensorConstant{(1L, 1L, 1..1L) of 0.5}, ConvOp{('imshp', (31, 31, 32)),('kshp', (3, 3)),('nkern', 64),('bsize', None),('dx', 1),('dy', 1),('out_mode', 'valid'),('unroll_batch', None),('unroll_kern', None),('unroll_patch', True),('imshp_logical', (31, 31, 32)),('kshp_logical', (3, 3)),('kshp_logical_top_aligned', True)}.0, InplaceDimShuffle{x,0,x,x}.0)]]
我应该如何正确加载模型以便可以同时访问它?
感谢您的时间。