使用keras部署深度學(xué)習(xí)模型(rest api)

參考 building-a-simple-keras-deep-learning-rest-api

文章中比較重要的代碼是2個地方
1. 模型加載
這里貌似是通過網(wǎng)絡(luò)下載的,所以可能加載比較慢

def load_model():
    # load the pre-trained Keras model (here we are using a model
    # pre-trained on ImageNet and provided by Keras, but you can
    # substitute in your own networks just as easily)
    global model
    model = ResNet50(weights="imagenet")

2.模型調(diào)用
通過post請求上傳圖片。
調(diào)用模型就一行代碼

model.predict(image)

if flask.request.method == "POST":
        if flask.request.files.get("image"):
            # read the image in PIL format
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            # preprocess the image and prepare it for classification
            image = prepare_image(image, target=(224, 224))

            # classify the input image and then initialize the list
            # of predictions to return to the client
            preds = model.predict(image)
            results = imagenet_utils.decode_predictions(preds)
            data["predictions"] = []

            # loop over the results and add them to the list of
            # returned predictions
            for (imagenetID, label, prob) in results[0]:
                r = {"label": label, "probability": float(prob)}
                data["predictions"].append(r)

            # indicate that the request was a success
            data["success"] = True

但我在實際操作時,就遇到了問題。
首先,不知道keras版本是多少。還好到文章中給出的github鏈接找到了依賴:

Keras 2.2.4
TF 1.13.1

其次,跑起來報錯:

 Tensor is not an element of this graph

還是通過文章中給出的github鏈接當(dāng)中,找到了 解決辦法,看來是并發(fā)導(dǎo)致的問題。
最后的代碼改動點在這里,注意加粗部分:

def my_load_model():
# load the pre-trained Keras model (here we are using a model
# pre-trained on ImageNet and provided by Keras, but you can
# substitute in your own networks just as easily)
global model
model = ResNet50(weights="imagenet")
global graph
graph = tf.get_default_graph()

def predict():
# initialize the data dictionary that will be returned from the
# view
data = {"success": False}
global graph
with graph.as_default():
# ensure an image was properly uploaded to our endpoint
if flask.request.method == "POST":

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容