假设我创建了一个RandomizedSearchCV
,如下所示:
searcher = model_selection.RandomizedSearchCV(estimator = RandomForestClassifier(),
param_distributions = random_grid,
n_iter = 20, # Number of parameter combinations to try
cv = 3, # Number of folds for k-fold validation
n_jobs = -1) # Use all processors to compute in parallel
search = searcher.fit(x_train, y_train)
search.best_params_
n_iter
告诉我们搜索将测试多少种组合。对我来说,非常重要的是要知道,作为20个组合的一部分或除此之外,还包括默认的模型参数。有人知道这是真是假吗?
它们是而不是(可以说,如果是这样的话,那会很奇怪(。
尝试的参数组合的详细值在拟合的RandomizedSearchCV
对象的属性cv_results_
中返回。根据文档中的示例(使用默认的n_iter = 10
(,我们得到:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import uniform
iris = load_iris()
logistic = LogisticRegression(solver='saga', tol=1e-2, max_iter=200,
random_state=0)
distributions = dict(C=uniform(loc=0, scale=4),
penalty=['l2', 'l1'])
clf = RandomizedSearchCV(logistic, distributions, random_state=0)
search = clf.fit(iris.data, iris.target)
search.cv_results_
您可以直接检查search.cv_results_
返回的字典,也可以将其导入pandas数据帧以获得更紧凑的表示:
import pandas as pd
df = pd.DataFrame.from_dict(search.cv_results_)
df['params']
# result:
0 {'C': 2.195254015709299, 'penalty': 'l1'}
1 {'C': 3.3770629943240693, 'penalty': 'l1'}
2 {'C': 2.1795327319875875, 'penalty': 'l1'}
3 {'C': 2.4942547871438894, 'penalty': 'l2'}
4 {'C': 1.75034884505077, 'penalty': 'l2'}
5 {'C': 0.22685190926977272, 'penalty': 'l2'}
6 {'C': 1.5337660753031108, 'penalty': 'l2'}
7 {'C': 3.2486749151019727, 'penalty': 'l2'}
8 {'C': 2.2721782443757292, 'penalty': 'l1'}
9 {'C': 3.34431505414951, 'penalty': 'l2'}
从中可以清楚地看出,LogisticRegression
的C=1.0
的默认值是而不是包括在搜索网格中。
如果你有任何理由用默认参数来评估模型的性能,你应该单独进行——可以说这非常简单(只有2行代码(。