1.编写机器学习代码
(1)新建一个 mlmodel.py
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import joblib
# Load sample dataset
iris = load_iris()
X = iris.data
y = iris.target
# Split into features and target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Train a Logistic Regression model
model = LogisticRegression(max_iter=200)
model.fit(X_train,y_train)
# Evaluate the model
y_pred=model.predict(X_test)
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
joblib.dump(model,'logistic_regression_model.pkl')
执行上述代码,生成模型文件;
2. 编写机器学习服务
在mlmodel.py同级目录下,新建一个app.py文件,插入如下内容:
from flask import Flask,request, jsonify
import joblib
model = joblib.load('logistic_regression_model.pkl')
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json()
prediction = model.predict([data['features']])
return jsonify({'prediction': int(prediction[0])})
if __name__ == '__main__':
app.run(debug=True,port=6000,host="0.0.0.0")
注意这里host必须设置为0.0.0.0
3.编写Dockerfile文件
在app.py同级目录下,新建一个Dockerfile文件,插入如下内容:
FROM python:3.9-slim
WORKDIR /app
COPY . /app
RUN pip install -r requirements.txt
EXPOSE 6000
CMD ["python", "app.py"]
4.编写依赖文件
在app.py同级目录下,新建一个requirements.txt文件,插入如下内容(该文件包含app.py运行所需要的库):
flask
joblib
scikit-learn
5.构建Docker镜像和运行容器
打开终端,进入app.py同级目录下,
(1) 构建Docker镜像
docker build -t ml-model-api .
(2)运行Docker容器
docker run -p 5000:5000 ml-model-api
到此,你就可以通过api工具,如:apifox,去调用你的docker服务了。