簡體   English   中英

正確加載支持多租戶的Django中的Keras模型

[英]Correctly loading Keras model in Django that supports multi-tenancy

我嘗試在django中編寫一個REST api,它使用Keras模型返回預測。 但是load_model()函數需要一些時間來加載模型,我不希望我的用戶必須等待這么久(每次初始化模型時)。 初始化模型的正確方法是什么,以便加載一次,並使用相同的模型完成預測?

另外,我認為可以冷卻的一種方法是在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

然后在我的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)]]

我應該如何正確加載模型,以便可以同時訪問它?

感謝您的時間。

請看這里請https://github.com/keras-team/keras/issues/2397#issuecomment-254919212

例如。 在Django設置中構建模型...

modelFile = 'path_to_my_model.h5'    
pipe = joblib.load(modelFile.replace('.h5','.pkl'))
model = models.load_model(modelFile)
pipe.steps.append(('nn', model))    
graph = tensorflow.get_default_graph()

然后在Django REST方法中重用如下:

import myDjango.settings as sett
# ...

@csrf_exempt
def evaluate(request):
    """
    Do the evaluation.
    """
    if request.method == 'POST':
        data = JSONParser().parse(request)
        i = data['inputs']

        outputs = MyMlClass.PredictArray( sett.graph, sett.pipe , i, 'model.h5' )

        return JsonResponse(outputs, status=201, safe=False)

非常適合我(VisualStudio Django項目,Python 3.6)。 不推薦在REST處理程序中構建模型,事實上它不起作用 - 它只在第一次調用時才起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM