實戰:最佳化求解 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