Best Parameters: {‘colsample_bytree’: 0.6431565707973218, ‘learning_rate’: 0.019428755706020276, ‘max_depth’: 9, ‘n_estimators’: 340, ‘subsample’: 0.7257423924305306} これは、ランダムサーチの結果です。このパラメーターをベースにして、グリッドサーチで探索してほしい。

ランダムサーチで得られた最適なパラメーターをベースにして、グリッドサーチを行うコードは以下のようになります。

python
from sklearn.model_selection import GridSearchCV # ベースとなるパラメーターをランダムサーチで得られた最適なパラメーターに設定する base_params = { 'colsample_bytree': 0.6431565707973218, 'learning_rate': 0.019428755706020276, 'max_depth': 9, 'n_estimators': 340, 'subsample': 0.7257423924305306 } # グリッドサーチ用の探索空間を定義 param_grid = { 'n_estimators': [base_params['n_estimators'], base_params['n_estimators'] + 100, base_params['n_estimators'] + 200], 'max_depth': [base_params['max_depth'], base_params['max_depth'] + 1, base_params['max_depth'] + 2], 'learning_rate': [base_params['learning_rate'], base_params['learning_rate'] + 0.01, base_params['learning_rate'] + 0.02], 'subsample': [base_params['subsample'], base_params['subsample'] + 0.05, base_params['subsample'] + 0.1], 'colsample_bytree': [base_params['colsample_bytree'], base_params['colsample_bytree'] + 0.05, base_params['colsample_bytree'] + 0.1], } # グリッドサーチを行う grid_search = GridSearchCV( estimator=xgb_model, param_grid=param_grid, cv=3, scoring='accuracy', verbose=2, n_jobs=-1 ) # グリッドサーチを実行 grid_search.fit(X_train, y_train_encoded) # 最適なモデルを取得 best_model_grid = grid_search.best_estimator_ # 最適なモデルで予測を行う y_pred_encoded_grid = best_model_grid.predict(X_test) # モデルの評価 accuracy_grid = accuracy_score(y_test_encoded, y_pred_encoded_grid) precision_grid = precision_score(y_test_encoded, y_pred_encoded_grid, average='weighted') recall_grid = recall_score(y_test_encoded, y_pred_encoded_grid, average='weighted') f1_grid = f1_score(y_test_encoded, y_pred_encoded_grid, average='weighted') roc_auc_grid = roc_auc_score(y_test_encoded, best_model_grid.predict_proba(X_test), multi_class='ovr') print("Best Parameters (Grid Search):", grid_search.best_params_) print("Accuracy (Grid Search):", accuracy_grid) print("Precision (Grid Search):", precision_grid) print("Recall (Grid Search):", recall_grid) print("F1 Score (Grid Search):", f1_grid) print("ROC AUC Score (Grid Search):", roc_auc_grid)

このコードでは、ランダムサーチで得られた最適なパラメーターをbase_paramsに設定し、それを元にグリッドサーチ用の探索空間を定義しています。そして、GridSearchCVを使用してグリッドサーチを行います。最後に、最適なモデルでの予測と評価を行います。

未分類

Posted by ぼっち