實戰:最佳化求解 API
Vibe Prompt
「幫我用 FastAPI 建立一個通用最佳化 API:使用者輸入目標函數與範圍,後端用模擬退火求解。」
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import random, math
app = FastAPI(title="最佳化求解 API")
class OptimizeRequest(BaseModel):
objective: str # 數學表達式,如 "x**2 + y**2"
bounds: list[list[float]] # [[x_min,x_max], [y_min,y_max]]
algorithm: str = "simulated_annealing"
class OptimizeResponse(BaseModel):
best_solution: list[float]
best_value: float
algorithm: str
iterations: int
@app.post("/optimize", response_model=OptimizeResponse)
def optimize(req: OptimizeRequest):
dim = len(req.bounds)
def objective(x):
# 安全 eval
env = {"x": x} if dim == 1 else {f"x{i}": x[i] for i in range(dim)}
env.update({"sin": math.sin, "cos": math.cos, "sqrt": math.sqrt,
"abs": abs, "sum": sum, "pow": pow})
return eval(req.objective, {"__builtins__": {}}, env)
best = None
best_val = float('inf')
if req.algorithm == "simulated_annealing":
current = [random.uniform(b[0], b[1]) for b in req.bounds]
current_val = objective(current)
temp = 1000
iterations = 0
while temp > 0.01:
neighbor = [current[i] + random.uniform(-1, 1) for i in range(dim)]
neighbor = [max(req.bounds[i][0], min(req.bounds[i][1], neighbor[i]))
for i in range(dim)]
neighbor_val = objective(neighbor)
delta = neighbor_val - current_val
if delta < 0 or random.random() < math.exp(-delta/temp):
current = neighbor
current_val = neighbor_val
if current_val < best_val:
best = current[:]
best_val = current_val
temp *= 0.995
iterations += 1
return OptimizeResponse(
best_solution=best, best_value=round(best_val, 6),
algorithm=req.algorithm, iterations=iterations
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
本日總結
- ✅ 模擬退火
- ✅ 遺傳演算法
- ✅ PSO
- ✅ 超參數調優
- ✅ 最佳化 API
本章總結
- 理解核心概念與原理
- 掌握實作方法與技巧
- 熟悉常見問題與解決方案
- 能夠應用於實際專案
延伸閱讀
- 官方文件與 API 參考
- GitHub 開源專案範例
- 相關技術書籍與課程
- 社群討論與技術部落格
實作範例
基礎範例
# 本節提供一個完整的實作範例
# 讓你能夠將所學應用到實際專案中
步驟說明
- 初始化:設定開發環境與必要工具
- 資料準備:收集與整理所需資料
- 核心實作:實作主要功能與邏輯
- 測試驗證:確保功能正確運作
- 最佳化:調整效能與使用者體驗
常見錯誤
| 錯誤類型 | 可能原因 | 解決方法 | |---------|---------|---------| | 編譯錯誤 | 語法問題 | 檢查程式碼語法 | | 執行錯誤 | 環境問題 | 確認相依套件已安裝 | | 邏輯錯誤 | 演算法問題 | 逐步除錯與測試 | | 效能問題 | 效率問題 | 使用效能分析工具 |
程式碼範例
# 範例程式碼
import sys
def main():
# 主程式邏輯
print("Hello, World!")
if __name__ == "__main__":
main()
相關資源
- 官方文件
- API 參考手冊
- 開源專案範例
- 技術社群討論