ベイズ最適化をしてみたい
ベイズ最適化は、ランダムサーチよりも効率的にハイパーパラメータの最適化を行う手法です。ベイズ最適化では、過去の試行結果に基づいてハイパーパラメータの選択を進化させることで、より良い候補を提案します。
以下は、Scikit-optimize(skopt)ライブラリを使用してXGBoostモデルのベイズ最適化を行う例です。
まず、Scikit-optimizeをインストールします。
bash
pip install scikit-optimize
次に、ベイズ最適化を実行するコードを示します。
python
from skopt import BayesSearchCV from sklearn.model_selection import StratifiedKFold # ベイズ最適化の範囲を定義 param_space = { 'n_estimators': (100, 1000), 'max_depth': (3, 10), 'learning_rate': (0.01, 0.3), 'subsample': (0.6, 1.0), 'colsample_bytree': (0.6, 1.0), } # ベイズ最適化を行う bayes_search = BayesSearchCV( estimator=xgb_model, search_spaces=param_space, scoring='accuracy', cv=StratifiedKFold(n_splits=3), n_iter=50, verbose=2, random_state=42, n_jobs=-1 ) # ベイズ最適化を実行 bayes_search.fit(X_train, y_train_encoded) # 最適なモデルを取得 best_model = bayes_search.best_estimator_ # 最適なモデルで予測を行う y_pred_encoded = best_model.predict(X_test) # モデルの評価 accuracy = accuracy_score(y_test_encoded, y_pred_encoded) precision = precision_score(y_test_encoded, y_pred_encoded, average='weighted') recall = recall_score(y_test_encoded, y_pred_encoded, average='weighted') f1 = f1_score(y_test_encoded, y_pred_encoded, average='weighted') roc_auc = roc_auc_score(y_test_encoded, best_model.predict_proba(X_test), multi_class='ovr') print("Best Parameters:", bayes_search.best_params_) print("Accuracy:", accuracy) print("Precision:", precision) print("Recall:", recall) print("F1 Score:", f1) print("ROC AUC Score:", roc_auc)
このコードでは、BayesSearchCVを使用してベイズ最適化を実行し、指定されたパラメータ空間内で最適なハイパーパラメータを探索します。最適なモデルのパラメータと性能指標が出力されます。

ディスカッション
コメント一覧
まだ、コメントがありません