我尝试在Django中使用Keras模型返回预测来编写REST api。然而,load_model()
函数需要一些时间来加载模型,我不希望我的用户不得不等待这么久(每次模型初始化)。初始化模型的正确方法是什么,以便加载一次,并使用同一模型进行预测?在Django中正确加载Keras模型,支持多租户
在一个侧面说明,我认为冷是可能的一个方法是在初始化如下settings.py模型:
settings.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
然后在我的意见。 PY我使用这个变量模型为:
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)]]
我应该如何正确地加载模型,以便它可以同时访问?
谢谢你的时间。
你知道如何解决它吗? – streamride
@streamride你可以为你的views.py中需要的每个实例做一个copy.copy(模型)并安全地使用它。我使用它修复了我的项目 –
https://stackoverflow.com/questions/47295025/valueerror-at-image-tensor-tensoractivation-5-softmax0-shape-4-dtyp/47300005?noredirect=1#comment81555441_47300005任何帮助 –