參考 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":