本文将會通過一個有趣的 Python 庫,快速将圖像分類的功能搭建在雲函數上,并且和 API 網關結合,對外提供 API 功能,實作一個 Serverless 架構的“圖像分類 API”。

前言
圖像分類是人工智能領域的一個熱門話題。通俗解釋就是,根據各自在圖像資訊中所反映的不同特征,把不同類别的目标區分開來的圖像處理方法。
它利用計算機對圖像進行定量分析,把圖像或圖像中的每個像元或區域劃歸為若幹個類别中的某一種,以代替人的視覺判讀。
圖像分類在實際生産生活中也是經常遇到的,而且針對不同領域或者需求有着很強的針對性。例如通過拍攝花朵識别花朵資訊、通過人臉比對人物資訊等。
通常情況下,這些圖像識别或者分類的工具,都是在用戶端進行資料采集,在服務端進行運算獲得結果,也就是說一般情況下都是有專門的 API 實作圖像識别的。例如各大雲廠商都會為我們有償提供類似的能力:
阿裡雲圖像識别頁面:
華為雲圖像識别頁面:
首先和大家介紹一下需要的依賴庫:ImageAI。通過該依賴的官方文檔我們可以看到這樣的描述:
ImageAI 是一個 python 庫,旨在使開發人員能夠使用簡單的幾行代碼建構具有包含深度學習和計算機視覺功能的應用程式和系統。
ImageAI 本着簡潔的原則,支援最先進的機器學習算法,用于圖像預測、自定義圖像預測、物體檢測、視訊檢測、視訊對象跟蹤和圖像預測訓練。ImageAI 目前支援使用在 ImageNet-1000 資料集上訓練的 4 種不同機器學習算法進行圖像預測和訓練。ImageAI 還支援使用在 COCO 資料集上訓練的 RetinaNet 進行對象檢測、視訊檢測和對象跟蹤。最終,ImageAI 将為計算機視覺提供更廣泛和更專業化的支援,包括但不限于特殊環境和特殊領域的圖像識别。
也就是說這個依賴庫,可以幫助我們完成基本的圖像識别和視訊的目标提取,雖然他給了一些資料集和模型,但是我們也可以根據自身需要對其進行額外的訓練,進行定制化拓展。通過官方給的代碼,我們可以看到一個簡單的 Demo:
# -*- coding: utf-8 -*-
from imageai.Prediction import ImagePrediction
# 模型加載
prediction = ImagePrediction()
prediction.setModelTypeAsResNet()
prediction.setModelPath("resnet50_weights_tf_dim_ordering_tf_kernels.h5")
prediction.loadModel()
predictions, probabilities = prediction.predictImage("./picture.jpg", result_count=5 )
for eachPrediction, eachProbability in zip(predictions, probabilities):
print(str(eachPrediction) + " : " + str(eachProbability))
當我們指定的 picture.jpg 圖檔為:
我們在執行之後的結果是:
laptop : 71.43893241882324
notebook : 16.265612840652466
modem : 4.899394512176514
hard_disc : 4.007557779550552
mouse : 1.2981942854821682
如果在使用過程中覺得模型 resnet50_weights_tf_dim_ordering_tf_kernels.h5 過大,耗時過長,可以按需求選擇模型:
- SqueezeNet(檔案大小:4.82 MB,預測時間最短,精準度适中)
- ResNet50 by Microsoft Research (檔案大小:98 MB,預測時間較快,精準度高)
- InceptionV3 by Google Brain team (檔案大小:91.6 MB,預測時間慢,精度更高)
- DenseNet121 by Facebook AI Research (檔案大小:31.6 MB,預測時間較慢,精度最高)
模型下載下傳位址可參考 Github 位址:
https://github.com/OlafenwaMoses/ImageAI/releases/tag/1.0
或者參考 ImageAI 官方文檔:
https://imageai-cn.readthedocs.io/zh_CN/latest/ImageAI_Image_Prediction.html
項目 Serverless 化
将項目按照函數計算的需求,編寫好入口方法,以及做好項目初始化,同時在目前項目下建立檔案夾 model,并将模型檔案拷貝到該檔案夾:
項目整體流程:
實作代碼:
# -*- coding: utf-8 -*-
from imageai.Prediction import ImagePrediction
import json
import uuid
import base64
import random
# Response
class Response:
def __init__(self, start_response, response, errorCode=None):
self.start = start_response
responseBody = {
'Error': {"Code": errorCode, "Message": response},
} if errorCode else {
'Response': response
}
# 預設增加uuid,便于後期定位
responseBody['ResponseId'] = str(uuid.uuid1())
print("Response: ", json.dumps(responseBody))
self.response = json.dumps(responseBody)
def __iter__(self):
status = '200'
response_headers = [('Content-type', 'application/json; charset=UTF-8')]
self.start(status, response_headers)
yield self.response.encode("utf-8")
# 随機字元串
randomStr = lambda num=5: "".join(random.sample('abcdefghijklmnopqrstuvwxyz', num))
# 模型加載
print("Init model")
prediction = ImagePrediction()
prediction.setModelTypeAsResNet()
print("Load model")
prediction.setModelPath("/mnt/auto/model/resnet50_weights_tf_dim_ordering_tf_kernels.h5")
prediction.loadModel()
print("Load complete")
def handler(environ, start_response):
try:
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
except (ValueError):
request_body_size = 0
requestBody = json.loads(environ['wsgi.input'].read(request_body_size).decode("utf-8"))
# 圖檔擷取
print("Get pucture")
imageName = randomStr(10)
imageData = base64.b64decode(requestBody["image"])
imagePath = "/tmp/" + imageName
with open(imagePath, 'wb') as f:
f.write(imageData)
# 内容預測
print("Predicting ... ")
result = {}
predictions, probabilities = prediction.predictImage(imagePath, result_count=5)
print(zip(predictions, probabilities))
for eachPrediction, eachProbability in zip(predictions, probabilities):
result[str(eachPrediction)] = str(eachProbability)
return Response(start_response, result)
所需要的依賴:
tensorflow==1.13.1
numpy==1.19.4
scipy==1.5.4
opencv-python==4.4.0.46
pillow==8.0.1
matplotlib==3.3.3
h5py==3.1.0
keras==2.4.3
imageai==2.1.5
編寫部署所需要的配置檔案:
ServerlessBookImageAIDemo:
Component: fc
Provider: alibaba
Access: release
Properties:
Region: cn-beijing
Service:
Name: ServerlessBook
Description: Serverless圖書案例
Log: Auto
Nas: Auto
Function:
Name: serverless_imageAI
Description: 圖檔目标檢測
CodeUri:
Src: ./src
Excludes:
- src/.fun
- src/model
Handler: index.handler
Environment:
- Key: PYTHONUSERBASE
Value: /mnt/auto/.fun/python
MemorySize: 3072
Runtime: python3
Timeout: 60
Triggers:
- Name: ImageAI
Type: HTTP
Parameters:
AuthType: ANONYMOUS
Methods:
- GET
- POST
- PUT
Domains:
- Domain: Auto
在代碼與配置中,可以看到有目錄:/mnt/auto/ 的存在,該部分實際上是 nas 挂載之後的位址,隻需提前寫入到代碼中即可,下一個環節會進行 nas 的建立以及挂載點配置的具體操作。
項目部署與測試
在完成上述步驟之後,可以通過:
s deploy
進行項目部署,部署完成可以看到結果:
完成部署之後,可以通過:
s install docker
進行依賴的安裝:
依賴安裝完成可以看到在目錄下生成了 .fun 的目錄,該目錄就是通過 docker 打包出來的依賴檔案,這些依賴正是我們在 requirements.txt 檔案中聲明的依賴内容。
完成之後,我們通過:
s nas sync ./src/.fun
将依賴目錄打包上傳到 nas,成功之後再将 model 目錄打包上傳:
s nas sync ./src/model
完成之後可以通過:
s nas ls --all
檢視目錄詳情:
完成之後,我們可以編寫腳本進行測試,同樣适用剛才的測試圖檔,通過代碼:
import json
import urllib.request
import base64
import time
with open("picture.jpg", 'rb') as f:
data = base64.b64encode(f.read()).decode()
url = 'http://35685264-1295939377467795.test.functioncompute.com/'
timeStart = time.time()
print(urllib.request.urlopen(urllib.request.Request(
url=url,
data=json.dumps({'image': data}).encode("utf-8")
)).read().decode("utf-8"))
print("Time: ", time.time() - timeStart)
可以看到結果:
{"Response": {"laptop": "71.43893837928772", "notebook": "16.265614330768585", "modem": "4.899385944008827", "hard_disc": "4.007565602660179", "mouse": "1.2981869280338287"}, "ResponseId": "1d74ae7e-298a-11eb-8374-024215000701"}
Time: 29.16020894050598
可以看到,函數計算順利地傳回了預期結果,但是整體耗時卻超乎想象,有近 30s,此時我們再次執行一下測試腳本:
{"Response": {"laptop": "71.43893837928772", "notebook": "16.265614330768585", "modem": "4.899385944008827", "hard_disc": "4.007565602660179", "mouse": "1.2981869280338287"}, "ResponseId": "4b8be48a-298a-11eb-ba97-024215000501"}
Time: 1.1511380672454834
可以看到,再次執行的時間僅有 1.15 秒,比上次整整提升了 28 秒之多。
項目優化
在上一輪的測試中可以看到,項目首次啟動和二次啟動的耗時差距,其實這個時間差,主要是函數在加載模型的時候浪費了極長的時間。
即使在本地,我們也可以簡單測試:
# -*- coding: utf-8 -*-
import time
timeStart = time.time()
# 模型加載
from imageai.Prediction import ImagePrediction
prediction = ImagePrediction()
prediction.setModelTypeAsResNet()
prediction.setModelPath("resnet50_weights_tf_dim_ordering_tf_kernels.h5")
prediction.loadModel()
print("Load Time: ", time.time() - timeStart)
timeStart = time.time()
predictions, probabilities = prediction.predictImage("./picture.jpg", result_count=5)
for eachPrediction, eachProbability in zip(predictions, probabilities):
print(str(eachPrediction) + " : " + str(eachProbability))
print("Predict Time: ", time.time() - timeStart)
執行結果:
Load Time: 5.549695014953613
laptop : 71.43893241882324
notebook : 16.265612840652466
modem : 4.899394512176514
hard_disc : 4.007557779550552
mouse : 1.2981942854821682
Predict Time: 0.8137111663818359
可以看到,在加載 imageAI 子產品以及加載模型檔案的過程中,一共耗時 5.5 秒,在預測部分僅有不到 1 秒鐘的時間。而在函數計算中,機器性能本身就沒有我本地的性能高,此時為了避免每次裝載模型導緻的響應時間過長,在部署的代碼中,可以看到模型裝載過程實際上是被放在了入口方法之外。這樣做的一個好處是,項目每次執行的時候,不一定會有冷啟動,也就是說在某些複用的前提下是可以複用一些對象的,即無需每次都重新加載模型、導入依賴等。
是以在實際項目中,為了避免頻繁請求,執行個體重複裝載、建立某些資源,我們可以将部分資源放在初始化的時候進行。這樣可以大幅度提高項目的整體性能,同時配合廠商所提供的預留能力,可以基本上杜絕函數冷啟動帶來的負面影響。
總結
近年來,人工智能與雲計算的發展突飛猛進,在 Serverless 架構中,如何運作傳統的人工智能項目已經逐漸成為很多人所需要了解的事情。本文主要介紹了通過一個已有的依賴庫(ImageAI)實作一個圖像分類和預測的接口。借助這個例子,其實有幾個事情是可以被明确的:
- Serverless 架構可以運作人工智能相關項目;
- Serverless 可以很好地相容 Tensorflow 等機器學習/深度學習的工具;
- 雖然說函數計算本身有空間限制,但是實際上增加了硬碟挂載能力之後,函數計算本身的能力将會得到大幅度的拓展。
當然,本文也算是抛磚引玉,希望讀者在本文之後,可以發揮自己的想象,将更多的 AI 項目與 Serverless 架構進行進一步結合。