聊天視窗

數據洞察實戰:從數據採集到模型部署的完整路徑 - 第 6 章

第六章:模型部署與運營自動化

發布於 2026-02-27 22:23

## 第六章:模型部署與運營自動化 ### 6.1 何謂「可持續部署」 在前章我們已經完成了模型的訓練、驗證與再訓練,現在面臨的挑戰是將模型安全、可擴充地推送到生產環境。傳統的手動流程往往耗時且易出錯,**可持續部署**(Continuous Delivery)則以 CI/CD 的概念把這個過程「自動化」成一條流水線,從版本控制到雲端推送再到實時監控,全部能在一次提交後自動完成。 > **關鍵要點**: > 1. 版本化:模型與依賴關係同時被打包。 > 2. 隔離:容器化確保環境一致。 > 3. 觀察:即時指標與日誌可追蹤回饋。 ### 6.2 Docker 化模型 #### 6.2.1 Dockerfile 範例 ```dockerfile # 基底映像,使用官方的 Python 3.10 FROM python:3.10-slim AS builder # 設定工作目錄 WORKDIR /app # 安裝系統依賴 RUN apt-get update && \ apt-get install -y --no-install-recommends build-essential \ && rm -rf /var/lib/apt/lists/* # 複製需求檔 COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # 複製模型檔案 COPY model.pkl . COPY app.py . # 壓縮依賴層,節省映像大小 RUN pip cache purge # 生產階段 FROM python:3.10-slim WORKDIR /app COPY --from=builder /app /app EXPOSE 8000 ENTRYPOINT ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"] ``` #### 6.2.2 FastAPI 服務示範 ```python # app.py from fastapi import FastAPI, HTTPException from pydantic import BaseModel import joblib import numpy as np app = FastAPI(title="CTR 預測 API") model = joblib.load("model.pkl") class PredictRequest(BaseModel): features: list[float] @app.post("/predict") def predict(req: PredictRequest): if len(req.features) != model.n_features_in_: raise HTTPException(status_code=400, detail="特徵數量不符") X = np.array(req.features).reshape(1, -1) prob = model.predict_proba(X)[0, 1] return {"ctr": float(prob)} ``` > **備註**:將模型和依賴打包至單一映像,確保跨環境一致。 ### 6.3 CI/CD 流程設計 | 階段 | 工具 | 主要職責 | |---|---|---| | **代碼管理** | GitHub | 版本控制、Pull Request 審核 | | **測試 & 建構** | GitHub Actions | 單元測試、Docker 建構 | | **容器註冊** | Docker Hub / GitHub Packages | 存儲映像 | | **部署** | ArgoCD / Helm | 自動同步至 Kubernetes | | **監控** | Prometheus + Grafana | 收集指標、可視化 | | **回饋** | Sentry | 日誌聚合與錯誤追蹤 | #### 6.3.1 GitHub Actions 範例 ```yaml name: CI/CD Pipeline on: push: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: 3.10 - name: Install dependencies run: pip install -r requirements.txt - name: Run tests run: pytest tests/ - name: Build Docker image run: | docker build -t myregistry.com/ctr-model:${{ github.sha }} . - name: Push image run: | echo ${{ secrets.REGISTRY_PASSWORD }} | docker login myregistry.com -u ${{ secrets.REGISTRY_USER }} --password-stdin docker push myregistry.com/ctr-model:${{ github.sha }} - name: Deploy to K8s run: | kubectl set image deployment/ctr-deploy ctr=myregistry.com/ctr-model:${{ github.sha }} ``` ### 6.4 監控指標與告警 | 指標 | 來源 | 目標範圍 | 告警條件 | |---|---|---|---| | **Request Latency** | Prometheus | 0–200 ms | >200 ms持續5分鐘 | | **CPU Usage** | Prometheus | 0–80% | >80%持續10分鐘 | | **CTR Drift** | 自訂 | 0–5% | >5%持續30分鐘 | | **Error Rate** | Sentry | 0–0.5% | >0.5%持續2分鐘 | > **提醒**:將告警發送到 Slack 或 PagerDuty,確保運維團隊即時獲知。 ### 6.5 雲端彈性擴容 #### 6.5.1 Horizontal Pod Autoscaler(HPA) ```yaml apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: name: ctr-hpa spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: ctr-deploy minReplicas: 2 maxReplicas: 10 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70 ``` #### 6.5.2 事件觸發式擴容(KEDA) 利用 Kafka、RabbitMQ 或 Cloud Pub/Sub 的訊息量作為擴容指標,讓模型推斷能力隨流量自動調整。 ### 6.6 實戰:從模型到業務 KPI 的迴圈 1. **模型推斷**:每次點擊預測被送入 10 ms 內,確保使用者體驗。 2. **A/B 測試**:在 2‑week 週期內對 30% 轉換流量使用新模型,並對照舊模型 KPI。 3. **結果彙整**:使用 Tableau 連接到 ClickHouse,生成「CTR 變動 Dashboard」。 4. **回饋迴圈**:若新模型 CTR 提升 >5%,即觸發自動再訓練;若下降,立即回退。 > **結語**:部署不是終點,而是一個「即時回饋」的起點。只要在模型部署後不斷收集指標、執行 A/B 測試,並結合容器化與自動擴容,您就能把資料洞察轉化為可持續的商業價值。