注意
前往結尾以下載完整的範例程式碼。或透過 JupyterLite 或 Binder 在您的瀏覽器中執行此範例
連續減半迭代#
此範例說明了連續減半搜尋(HalvingGridSearchCV
和 HalvingRandomSearchCV
)如何從多個候選者中迭代選擇最佳參數組合。
# 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)
我們現在可以使用搜尋估算器的 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()

每次迭代的候選者數量和資源量#
在第一次迭代中,使用少量的資源。此處的資源是估算器所訓練的樣本數量。評估所有候選者。
在第二次迭代中,僅評估最佳一半的候選者。分配的資源數量加倍:在兩倍的樣本上評估候選者。
重複此過程直到最後一次迭代,其中僅剩下 2 個候選者。最佳候選者是在最後一次迭代中得分最高的候選者。
腳本總執行時間:(0 分鐘 5.725 秒)
相關範例