【模型部署】实例(附代码)

一.模型准备

1.模型训练及测试

from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
from sklearn.datasets import load_iris
import joblib
 
# 加载数据
X, y = load_iris(return_X_y=True)
# 拆分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
# 训练SVM模型
model = SVC(kernel='linear')
model.fit(X_train, y_train)
 
# 预测
y_pred = model.predict(X_test)
# 评估
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')

2.保存模型

# 保存
joblib.dump(model, 'svm_model.pkl')

二.部署

1.Flask

from flask import Flask, request, jsonify
import joblib

# Load the trained model
model = joblib.load('svm_model.pkl')

app = Flask(__name__)

# Define the prediction endpoint
@app.route('/predict', methods=['POST'])
def predict():
    data = request.get_json()  # Get the data sent in the request
    prediction = model.predict([data['features']])
    return jsonify({'prediction': int(prediction[0])})

if __name__ == '__main__':
    app.run(debug=True)

请求测试

curl -X POST http://localhost:5000/predict -H “Content-Type: application/json” -d '{“features”: [5.1, 3.5, 1.4, 0.2]}'

2.Docker

(1)安装docker:详见https://www.runoob.com/docker/docker-tutorial.html

(2)创建 Dockerfile:定义模型的运行环境。

# Use an official Python runtime as a parent image
FROM python:3.9-slim

# 设置工作目录
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install the required packages
RUN pip install -r requirements.txt

# Make the port 5000 available to the world outside this container
EXPOSE 5000

# Run app.py when the container launches
CMD ["python", "app.py"]

(3)构建 Docker 映像

docker build -t ml-model-api .

(4)运行 Docker 容器

docker run -p 5000:5000 ml-model-api

3.AWS Elastic Beanstalk

在AWS Elastic Beanstalk上部署容器化模型。

(1)安装 EB CLI

pip install awsebcli

(2)初始化 EB 环境

eb init

(3)部署应用程序

eb create ml-api-env

三.后期维护

部署后,需要监控模型的性能,处理扩展问题,并在新数据可用时定期更新模型。

监控:使用监控工具跟踪模型在生产中的性能。可以监控延迟、错误率和准确性随时间漂移等指标。

扩展:如果应用程序需要处理大量请求,Kubernetes 或 AWS Auto Scaling 等自动扩展工具可帮助管理负载。

版本控制:保持模型的版本控制。像MLflow和DVC(数据版本控制)可以帮助跟踪模型的不同版本,从而在必要时更容易回滚到之前的版本。

参考:https://mp.weixin.qq.com/s/ksuvqSja9Pix2aERyNwypw

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值