ランダムサーチを活かしたベイズ最適化のコードくれ

以下は、ランダムサーチの結果を初期値としてベイズ最適化を行うためのサンプルコードです。ここでは、scikit-optimizeライブラリを使用しています。

python
from skopt import BayesSearchCV from skopt.space import Real, Categorical, Integer # ベイズ最適化用の探索空間を定義 param_space = { 'n_estimators': Integer(100, 1000), 'max_depth': Integer(3, 10), 'learning_rate': Real(0.01, 0.3), 'subsample': Real(0.6, 1.0), 'colsample_bytree': Real(0.6, 1.0), } # ベイズ最適化を行う bayes_search = BayesSearchCV( estimator=xgb_model, search_spaces=param_space, n_iter=50, # ベイズ最適化のイテレーション数 cv=3, scoring='accuracy', n_jobs=-1, optimizer_kwargs={'base_estimator': 'RF'}, # ランダムフォレストを基底推定器として使用 random_state=42 ) # ベイズ最適化を実行 bayes_search.fit(X_train, y_train_encoded) # 最適なモデルを取得 best_model_bayes = bayes_search.best_estimator_ # 最適なモデルで予測を行う y_pred_encoded_bayes = best_model_bayes.predict(X_test) # モデルの評価 accuracy_bayes = accuracy_score(y_test_encoded, y_pred_encoded_bayes) precision_bayes = precision_score(y_test_encoded, y_pred_encoded_bayes, average='weighted') recall_bayes = recall_score(y_test_encoded, y_pred_encoded_bayes, average='weighted') f1_bayes = f1_score(y_test_encoded, y_pred_encoded_bayes, average='weighted') roc_auc_bayes = roc_auc_score(y_test_encoded, best_model_bayes.predict_proba(X_test), multi_class='ovr') print("Best Parameters (Bayesian Optimization):", bayes_search.best_params_) print("Accuracy (Bayesian Optimization):", accuracy_bayes) print("Precision (Bayesian Optimization):", precision_bayes) print("Recall (Bayesian Optimization):", recall_bayes) print("F1 Score (Bayesian Optimization):", f1_bayes) print("ROC AUC Score (Bayesian Optimization):", roc_auc_bayes)

このコードでは、skoptライブラリのBayesSearchCVクラスを使用しています。param_spaceで探索するハイパーパラメータの範囲を定義し、n_iterでベイズ最適化のイテレーション数を指定します。また、optimizer_kwargsでベイズ最適化のための基底推定器を設定しています。

未分類

Posted by ぼっち