譯者 | 布加迪
審校 | 重樓
開發(fā)機(jī)器學(xué)習(xí)模型只完成了一半工作。除非部署到生產(chǎn)環(huán)境、提供業(yè)務(wù)價值,否則模型仍然毫無用處。
知道如何部署自己的模型已成為任何數(shù)據(jù)科學(xué)家的一項(xiàng)基本技能,許多雇主已經(jīng)要求我們能做到這一點(diǎn)。因此,對于任何級別的數(shù)據(jù)科學(xué)家來說,學(xué)習(xí)如何將模型部署到生產(chǎn)環(huán)境大有助益。
本文探討如何將機(jī)器學(xué)習(xí)模型部署到生產(chǎn)環(huán)境中。
機(jī)器學(xué)習(xí)模型準(zhǔn)備
首先,準(zhǔn)備好部署到生產(chǎn)環(huán)境中的模型。我們先為整個教程設(shè)置虛擬環(huán)境。你可以通過在終端中使用以下代碼來實(shí)現(xiàn)這一點(diǎn)。
python -m venv myvirtualenv
在安裝并激活虛擬環(huán)境之后,你需要安裝所需的軟件包。創(chuàng)建requirements.txt文件,并用下面的庫列表填充它。
pandas
scikit-learn
fastapi
pydantic
uvicorn
streamlit
在requirements.txt準(zhǔn)備就緒之后,我們必須使用以下代碼來安裝它們。
pip install -r requirements.txt
一切準(zhǔn)備就緒,我們將開始開發(fā)機(jī)器學(xué)習(xí)模型。在本教程中,我們將使用來自Kaggle的糖尿病數(shù)據(jù)。把數(shù)據(jù)放在數(shù)據(jù)文件夾中。
然后,在app文件夾中創(chuàng)建一個名為train_model.py的文件。在train_model.py中,我們將使用下面的代碼訓(xùn)練機(jī)器學(xué)習(xí)模型。
import pandas as pd
import joblib
from sklearn.linear_model import LogisticRegression
data = pd.read_csv("data\\diabetes.csv")
X = data.drop('Outcome', axis =1)
y = data['Outcome']
model = LogisticRegression()
model.fit(X, y)
joblib.dump(model, 'models\\logreg_model.joblib')
你可以根據(jù)自己的喜好更改數(shù)據(jù)集的位置和模型路徑。我將把模型放入到模型的文件夾中。
我們將跳過所有的數(shù)據(jù)準(zhǔn)備和模型評估,因?yàn)楸疚牡哪?/span>的是將模型部署到生產(chǎn)環(huán)境中。當(dāng)模型準(zhǔn)備就緒后,我們將準(zhǔn)備部署模型了。
模型部署
在本節(jié)中,我們將為模型預(yù)測創(chuàng)建API,并使用Docker部署它們,同時使用Streamlit前端測試它們。
首先,確保你已經(jīng)安裝了Docker桌面,我們將在本地測試它。
接下來,在app文件夾中創(chuàng)建一個名為main.py的文件,并用以下代碼填充該文件以生成API。
from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import pandas as pd
# Load the logistic regression model
model = joblib.load('../models/logreg_model.joblib')
# Define the input data model
class DiabetesData(BaseModel):
Pregnancies: int
Glucose: int
BloodPressure: int
SkinThickness: int
Insulin: int
BMI: float
DiabetesPedigreeFunction: float
Age: int
app = FastAPI()
# Define prediction endpoint
@app.post("/predict")
def predict(data: DiabetesData):
input_data = {
'Pregnancies': [data.Pregnancies],
'Glucose': [data.Glucose],
'BloodPressure': [data.BloodPressure],
'SkinThickness': [data.SkinThickness],
'Insulin': [data.Insulin],
'BMI': [data.BMI],
'DiabetesPedigreeFunction': [data.DiabetesPedigreeFunction],
'Age': [data.Age]
}
input_df = pd.DataFrame(input_data)
# Make a prediction
prediction = model.predict(input_df)
result = "Diabetes" if prediction[0] == 1 else "Not Diabetes"
return {"prediction": result}
此外,我們會有一個前端web來試一試我們部署的API模型。為此,在app文件夾中創(chuàng)建一個名為frontend.py的文件。然后,用以下代碼填充它們。
import streamlit as st
import requests
import json
API_URL = "http://localhost:8000/predict"
st.title("Diabetes Prediction App")
st.write("Enter the details below to make a prediction.")
pregnancies = st.number_input("Pregnancies", min_value=0, step=1)
glucose = st.number_input("Glucose", min_value=0, step=1)
blood_pressure = st.number_input("Blood Pressure", min_value=0, step=1)
skin_thickness = st.number_input("Skin Thickness", min_value=0, step=1)
insulin = st.number_input("Insulin", min_value=0, step=1)
bmi = st.number_input("BMI", min_value=0.0, step=0.1)
diabetes_pedigree_function = st.number_input("Diabetes Pedigree Function", min_value=0.0, step=0.1)
age = st.number_input("Age", min_value=0, step=1)
if st.button("Predict"):
input_data = {
"Pregnancies": pregnancies,
"Glucose": glucose,
"BloodPressure": blood_pressure,
"SkinThickness": skin_thickness,
"Insulin": insulin,
"BMI": bmi,
"DiabetesPedigreeFunction": diabetes_pedigree_function,
"Age": age
}
response = requests.post(API_URL, data=json.dumps(input_data), headers={"Content-Type": "application/json"})
if response.status_code == 200:
prediction = response.json().get("prediction", "No prediction")
st.success(f"Prediction: {prediction}")
else:
st.error("Error in making prediction. Please check your input data and try again.")
當(dāng)一切準(zhǔn)備就緒后,我們將創(chuàng)建Docker文件作為模型部署的基礎(chǔ)。你應(yīng)該在文件中填寫下面的代碼。
FROM python:3.9-slim
WORKDIR /app
COPY app /app
COPY models /models
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt
EXPOSE 8000 8501
CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port 8000 & streamlit run frontend.py --server.port=8501 --server.enableCORS=false"]
我們將創(chuàng)建Docker文件已準(zhǔn)備就緒的映像,然后通過容器部署模型。為此,在終端中運(yùn)行以下代碼來構(gòu)建映像。
docker build -t diabetes-prediction-app .
上面的代碼為我們的模型容器創(chuàng)建了Docker映像。然后,我們將使用以下代碼為模型部署制作API。
docker run -d -p 8000:8000 -p 8501:8501 --name diabetes-prediction-container diabetes-prediction-app
一切準(zhǔn)備就緒后,確保容器運(yùn)行并使用下面的地址來訪問前端。
你應(yīng)該會看到如下圖所示的前端。
如果一切順利,恭喜你!你剛剛將機(jī)器學(xué)習(xí)模型部署到了生產(chǎn)環(huán)境中。
結(jié)論
在本文中,我們介紹了使用FastAPI和Docker將模型部署到生產(chǎn)環(huán)境中的簡單方法。
當(dāng)然,從維護(hù)模型和監(jiān)測生產(chǎn)環(huán)境中模型的過程中,仍然有很多東西需要學(xué)習(xí)。但愿本文對你有所幫助!
原文標(biāo)題:A Guide to Deploying Machine Learning Models to Production,作者:Cornellius Yudha Wijaya