連續減半迭代#

此範例說明了連續減半搜尋(HalvingGridSearchCVHalvingRandomSearchCV)如何從多個候選者中迭代選擇最佳參數組合。

# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.stats import randint

from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
from sklearn.experimental import enable_halving_search_cv  # noqa
from sklearn.model_selection import HalvingRandomSearchCV

我們首先定義參數空間並訓練一個 HalvingRandomSearchCV 實例。

rng = np.random.RandomState(0)

X, y = datasets.make_classification(n_samples=400, n_features=12, random_state=rng)

clf = RandomForestClassifier(n_estimators=20, random_state=rng)

param_dist = {
    "max_depth": [3, None],
    "max_features": randint(1, 6),
    "min_samples_split": randint(2, 11),
    "bootstrap": [True, False],
    "criterion": ["gini", "entropy"],
}

rsh = HalvingRandomSearchCV(
    estimator=clf, param_distributions=param_dist, factor=2, random_state=rng
)
rsh.fit(X, y)
HalvingRandomSearchCV(estimator=RandomForestClassifier(n_estimators=20,
                                                       random_state=RandomState(MT19937) at 0x74B4ABE1BB40),
                      factor=2,
                      param_distributions={'bootstrap': [True, False],
                                           'criterion': ['gini', 'entropy'],
                                           'max_depth': [3, None],
                                           'max_features': <scipy.stats._distn_infrastructure.rv_discrete_frozen object at 0x74b4c2c3d280>,
                                           'min_samples_split': <scipy.stats._distn_infrastructure.rv_discrete_frozen object at 0x74b4aa1d15e0>},
                      random_state=RandomState(MT19937) at 0x74B4ABE1BB40)
在 Jupyter 環境中,請重新執行此儲存格以顯示 HTML 表示法或信任筆記本。
在 GitHub 上,HTML 表示法無法呈現,請嘗試使用 nbviewer.org 加載此頁面。


我們現在可以使用搜尋估算器的 cv_results_ 屬性來檢查和繪製搜尋的演進。

results = pd.DataFrame(rsh.cv_results_)
results["params_str"] = results.params.apply(str)
results.drop_duplicates(subset=("params_str", "iter"), inplace=True)
mean_scores = results.pivot(
    index="iter", columns="params_str", values="mean_test_score"
)
ax = mean_scores.plot(legend=False, alpha=0.6)

labels = [
    f"iter={i}\nn_samples={rsh.n_resources_[i]}\nn_candidates={rsh.n_candidates_[i]}"
    for i in range(rsh.n_iterations_)
]

ax.set_xticks(range(rsh.n_iterations_))
ax.set_xticklabels(labels, rotation=45, multialignment="left")
ax.set_title("Scores of candidates over iterations")
ax.set_ylabel("mean test score", fontsize=15)
ax.set_xlabel("iterations", fontsize=15)
plt.tight_layout()
plt.show()
Scores of candidates over iterations

每次迭代的候選者數量和資源量#

在第一次迭代中,使用少量的資源。此處的資源是估算器所訓練的樣本數量。評估所有候選者。

在第二次迭代中,僅評估最佳一半的候選者。分配的資源數量加倍:在兩倍的樣本上評估候選者。

重複此過程直到最後一次迭代,其中僅剩下 2 個候選者。最佳候選者是在最後一次迭代中得分最高的候選者。

腳本總執行時間:(0 分鐘 5.725 秒)

相關範例

比較網格搜尋和逐次減半

比較網格搜尋和逐次減半

scikit-learn 0.24 的發行重點

scikit-learn 0.24 的發行重點

比較超參數估計的隨機搜尋和網格搜尋

比較超參數估計的隨機搜尋和網格搜尋

使用交叉驗證的網格搜尋自訂重新擬合策略

使用交叉驗證的網格搜尋自訂重新擬合策略

Sphinx-Gallery 產生的圖庫