超參數調優

Vibe Prompt

「用遺傳演算法最佳化 Random Forest 的超參數:n_estimators(10-200)、max_depth(3-20)、min_samples_split(2-10),目標最大化交叉驗證準確率。」

import random
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import cross_val_score

data = load_digits()
X, y = data.data, data.target

def evaluate(params):
    n_est, depth, min_split = params
    rf = RandomForestClassifier(
        n_estimators=int(n_est),
        max_depth=int(depth),
        min_samples_split=int(min_split),
        random_state=42, n_jobs=-1
    )
    scores = cross_val_score(rf, X, y, cv=3, scoring='accuracy')
    return scores.mean()

# 簡單遺傳演算法調參
bounds = [(10, 200), (3, 20), (2, 10)]
pop = [[random.uniform(b[0], b[1]) for b in bounds] for _ in range(20)]

for gen in range(20):
    scored = [(evaluate(p), p) for p in pop]
    scored.sort(reverse=True)
    pop = [p for _, p in scored]
    print(f"第 {gen+1} 代最佳: {scored[0][0]:.4f} (n_est={int(scored[0][1][0])}, depth={int(scored[0][1][1])})")
    
    next_pop = pop[:2]
    while len(next_pop) < 20:
        p1, p2 = random.choices(pop[:10], k=2)
        child = [random.choice([p1[i], p2[i]]) for i in range(3)]
        child = [c + random.uniform(-5, 5) for c in child]
        child = [max(b[0], min(b[1], child[i])) for i, b in enumerate(bounds)]
        next_pop.append(child)
    pop = next_pop

print(f"\n最佳參數: n_est={int(pop[0][0])}, depth={int(pop[0][1])}, min_split={int(pop[0][2])}")

本章總結

  • 理解核心概念與原理
  • 掌握實作方法與技巧
  • 熟悉常見問題與解決方案
  • 能夠應用於實際專案

延伸閱讀

  • 官方文件與 API 參考
  • GitHub 開源專案範例
  • 相關技術書籍與課程
  • 社群討論與技術部落格

實作範例

基礎範例

# 本節提供一個完整的實作範例
# 讓你能夠將所學應用到實際專案中

步驟說明

  1. 初始化:設定開發環境與必要工具
  2. 資料準備:收集與整理所需資料
  3. 核心實作:實作主要功能與邏輯
  4. 測試驗證:確保功能正確運作
  5. 最佳化:調整效能與使用者體驗

常見錯誤

| 錯誤類型 | 可能原因 | 解決方法 | |---------|---------|---------| | 編譯錯誤 | 語法問題 | 檢查程式碼語法 | | 執行錯誤 | 環境問題 | 確認相依套件已安裝 | | 邏輯錯誤 | 演算法問題 | 逐步除錯與測試 | | 效能問題 | 效率問題 | 使用效能分析工具 |

程式碼範例

# 範例程式碼
import sys

def main():
    # 主程式邏輯
    print("Hello, World!")

if __name__ == "__main__":
    main()

相關資源

  • 官方文件
  • API 參考手冊
  • 開源專案範例
  • 技術社群討論

完全なチュートリアルをロック解除

このチャプターは有料コンテンツです。プロジェクトに参加して、10以上の神レベルのPromptや実際のソースコード例を含む、5000字以上の深い分析をロック解除してください!