作者|Aparna Dhinakaran
編譯|Flin
來源|towardsdatascience

部署健壯的、可擴展的機器學習解決方案仍然是一個非常復雜的程序,需要大量的人力參與,并做出很多努力,因此,新產品和服務需要很長時間才能上市,或者在原型狀態下就被放棄,從而降低了行業內的對它的興趣,那么,我們如何才能促進將機器學習模型投入生產的程序呢?
Cortex是一個將機器學習模型部署為生產網路服務的開源平臺,它利用強大的AWS生態系統,根據需要部署、監視和擴展與框架無關的模型,其主要特點概括如下:
-
框架無關:Cortex支持任何python代碼;與其他python腳本一樣,TensorFlow、PyTorch、scikit-learn、XGBoost都是由該庫支持的,
-
自動縮放:Cortex自動縮放你的api,以處理生產負載,
-
CPU / GPU支持:使用AWS IaaS作為底層基礎架構,Cortex可以在CPU或GPU環境下運行,
-
Spot實體:Cortex支持EC2 Spot實體來降低成本,
-
滾動更新:Cortex對模型應用任何更新,沒有任何停機時間,
-
日志流:Cortex使用類似docker的語法將部署模型中的日志保存下來,并將其流式傳輸到CLI,
-
預測監測:Cortex監測網路指標并跟蹤預測,
-
最小配置:Cortex部署配置被定義為一個簡單的YAML檔案,
在本文中,我們使用Cortex將一個影像分類模型作為web服務部署到AWS上,那么,言歸正傳,讓我們來介紹一下Cortex,
將模型部署為Web服務
在這個例子中,我們使用fast.ai庫(https://pypi.org/project/fastai/) ,并從相關MOOC的第一個課程中(https://course.fast.ai/) 借用pets分類模型,以下各節介紹了Cortex的安裝和pets分類模型作為web服務的部署,
安裝
如果還沒有安裝,首先應該在AWS上創建一個具有編程訪問權限的新用戶帳戶,為此,請選擇IAM服務,然后從右側面板中選擇Users,最后按Add User按鈕,為用戶指定一個名稱并選擇Programmatic access,

接下來,在Permissions 螢屏中,選擇Attach existing policies directly選項卡,然后選擇AdministratorAccess,

你可以將標記頁留空,查看并創建用戶,最后,注意訪問密鑰ID和密鑰訪問密鑰,
在AWS控制臺上,你還可以創建一個S3 bucket來存盤經過訓練的模型和代碼可能生成的任何其他人工制品,你可以隨意命名這個bucket,只要它是一個唯一的名字,在這里,我們創建了一個名為cortex-pets-model的bucket,
下一步,我們必須在系統上安裝Cortex CLI并啟動Kubernetes集群,要安裝Cortex CLI,請運行以下命令:
bash -c “$(curl -sS https://raw.githubusercontent.com/cortexlabs/cortex/0.14/get-cli.sh)"
通過訪問相應的檔案部分(https://www.cortex.dev/) ,檢查你是否正在安裝最新版本的Cortex CLI,
我們現在準備建立集群,使用Cortex創建Kubernetes集群是很簡單的,只需執行以下命令:
cortex cluster up
Cortex會要求你提供一些資訊,比如你的AWS密鑰、你想使用的區域、你想啟動的計算實體以及它們的數量,Cortex也會讓你知道你會花多少錢來使用你選擇的服務,整個程序可能需要20分鐘,

訓練你的模型
Cortex并不關心你如何創建或訓練你的模型,在本例中,我們使用fast.ai庫和Oxford IIIT Pet資料集,這個資料集包含37種不同的狗和貓,因此,我們的模型應該將每個影像分為這37類,
創建一個類似下面的trainer.py檔案
import boto3
import pickle
from fastai.vision import *
# initialize boto session
session = boto3.Session(
aws_access_key_id=<your_accress_key_id>,
aws_secret_access_key='<your_secret_access_key>',
)
# get the data
path = untar_data(URLs.PETS, dest='sample_data')
path_img = path/'images'
fnames = get_image_files(path_img)
# process the data
bs = 64
pat = r'/([^/]+)_\d+.jpg$'
data = https://www.cnblogs.com/panchuangai/p/ImageDataBunch.from_name_re(path_img, fnames, pat,
ds_tfms=get_transforms(), size=224, bs=bs) /
.normalize(imagenet_stats)
# create, fit and save the model
learn = cnn_learner(data, models.resnet18, metrics=accuracy)
learn.fit_one_cycle(4)
with open('model.pkl', 'wb') as handle:
pickle.dump(learn.model, handle)
# upload the model to s3
s3 = session.client('s3')
s3.upload_file('model.pkl', 'cortex-pets-model', 'model.pkl')
與其他python腳本一樣,在本地運行該腳本:python trainer.py
但是,請確保提供你的AWS憑據和S3 bucket名稱,這個腳本獲取資料,處理它們,適合一個預先訓練好的ResNet模型并將其上傳到S3,當然,你可以使用幾種技術(更復雜的體系結構、有區別的學習率、面向更多時代的訓練)來擴展此腳本以使模型更精確,但是這與我們的目標無關,如果你想進一步了解ResNet體系結構,請參閱下面的文章,
https://towardsdatascience.com/xresnet-from-scratch-in-pytorch-e64e309af722
部署模型
現在我們已經訓練了模型并將其存盤在S3中,下一步是將其作為web服務部署到生產環境中,為此,我們創建了一個名為predictor.py的python腳本,像下圖:
import torch
import boto3
import pickle
import requests
from PIL import Image
from io import BytesIO
from torchvision import transforms
# initialize boto session
session = boto3.Session(
aws_access_key_id='<your_access_key_id>',
aws_secret_access_key='<your_secret_access_key>',
)
# define the predictor
class PythonPredictor:
def __init__(self, config):
s3 = session.client('s3')
s3.download_file(config['bucket'], config['key'], 'model.pkl')
self.model = pickle.load(open('model.pkl', 'rb'))
self.model.eval()
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
self.preprocess = transforms.Compose(
[transforms.Resize(224), transforms.ToTensor(), normalize]
)
self.labels = ['Abyssinian', 'Bengal', 'Birman', 'Bombay', 'British_Shorthair',
'Egyptian_Mau', 'Maine_Coon', 'Persian', 'Ragdoll', 'Russian_Blue',
'Siamese', 'Sphynx', 'american_bulldog', 'american_pit_bull_terrier',
'basset_hound', 'beagle', 'boxer', 'chihuahua', 'english_cocker_spaniel',
'english_setter', 'german_shorthaired', 'great_pyrenees', 'havanese',
'japanese_chin', 'keeshond', 'leonberger', 'miniature_pinscher', 'newfoundland',
'pomeranian', 'pug', 'saint_bernard', 'samoyed', 'scottish_terrier', 'shiba_inu',
'staffordshire_bull_terrier', 'wheaten_terrier', 'yorkshire_terrier']
self.device = config['device']
def predict(self, payload):
image = requests.get(payload["url"]).content
img_pil = Image.open(BytesIO(image))
img_tensor = self.preprocess(img_pil)
img_tensor.unsqueeze_(0)
img_tensor = img_tensor.to(self.device)
with torch.no_grad():
prediction = self.model(img_tensor)
_, index = prediction[0].max(0)
return self.labels[index]
這個檔案定義了一個預測器類,在實體化它時,它從S3中檢索模型,將其加載到記憶體中,并定義一些必要的轉換和引數,在推理期間,它從給定的URL中讀取影像并回傳預測的類的名稱,一個用于初始化的方法__init__和一個用于接收有效負載并回傳結果的預測方法predict,
預測器腳本有兩個附帶的檔案,一個記錄庫依賴項的requirements.txt檔案(如pytorch、fastai、boto3等)和一個YAML組態檔,最小配置如下:
- name: pets-classifier
predictor:
type: python
path: predictor.py
config:
bucket: cortex-pets-model
key: model.pkl
device: cpu
在這個YAML檔案中,我們定義了運行哪個腳本進行推理,在哪個設備(例如CPU)上運行,以及在哪里找到訓練好的模型,檔案中提供了更多的選項,
最后,專案的結構應該遵循下面的層次結構,請注意,這是最低限度的要求,但是如果你有一個可以部署的模型,那么你可以提交train .py,
- Project name
|----trainer.py
|----predictor.py
|----requirements.txt
|----cortex.yaml
有了所有這些,你只需運行cortex deploy,幾秒鐘之內,你的新端點就可以接受請求了,執行corted get pets-classifier來監視端點并查看其他詳細資訊,
status up-to-date requested last update avg request 2XX
live 1 1 13m - -
endpoint: http://a984d095c6d3a11ea83cc0acfc96419b-1937254434.us-west-2.elb.amazonaws.com/pets-classifier
curl: curl http://a984d095c6d3a11ea83cc0acfc96419b-1937254434.us-west-2.elb.amazonaws.com/pets-classifier?debug=true -X POST -H "Content-Type: application/json" -d @sample.json
configuration
name: pets-classifier
endpoint: /pets-classifier
predictor:
type: python
path: predictor.py
config:
bucket: cortex-pets-model
device: cpu
key: model.pkl
compute:
cpu: 200m
autoscaling:
min_replicas: 1
max_replicas: 100
init_replicas: 1
workers_per_replica: 1
threads_per_worker: 1
target_replica_concurrency: 1.0
max_replica_concurrency: 1024
window: 1m0s
downscale_stabilization_period: 5m0s
upscale_stabilization_period: 0s
max_downscale_factor: 0.5
max_upscale_factor: 10.0
downscale_tolerance: 0.1
upscale_tolerance: 0.1
update_strategy:
max_surge: 25%
max_unavailable: 25%
剩下的就是用curl和pomeranian的影像來測驗它:
curl http://a984d095c6d3a11ea83cc0acfc96419b-1937254434.us-west-2.elb.amazonaws.com/pets-classifier -X POST -H "Content-Type: application/json" -d '{"url": "https://i.imgur.com/HPRQ28l.jpeg"}'
釋放資源
當我們完成服務和集群時,我們應該釋放資源以避免額外的成本,Cortex很容易做到:
cortex delete pets-classifier
cortex cluster down
結論
在這篇文章中,我們看到了如何使用Cortex,一個開源平臺,來將機器學習模型部署為生產web服務,我們訓練了一個影像分類器,將其部署到AWS上,監控其性能并進行測驗,
有關更高級的概念,如預測監視、滾動更新、集群配置、自動縮放等,請訪問官方檔案站點(https://www.cortex.dev/) 和專案的GitHub頁面(https://github.com/cortexlabs/cortex),
原文鏈接:https://towardsdatascience.com/deploy-monitor-and-scale-machine-learning-models-on-aws-408dfd397422
歡迎關注磐創AI博客站:
http://panchuang.net/
sklearn機器學習中文官方檔案:
http://sklearn123.com/
歡迎關注磐創博客資源匯總站:
http://docs.panchuang.net/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/194791.html
標籤:其他
上一篇:機器學習模型的度量選擇一
下一篇:在深度學習中對正則化的直觀認識
