Scikit Learn 中的 RandomizedSearchCV
让我们练习使用 Scikit Learn 构建一个 RandomizedSearchCV 对象。
超参数网格应包含 max_depth(从 5 到 25,包含边界)和 max_features('auto' 和 'sqrt')。
该 RandomizedSearchCV 对象的设定如下:
- 使用
n_estimators为 80 的 RandomForestClassifier 作为估计器。 - 3 折交叉验证(
cv) - 使用
roc_auc来对模型进行评分 - 使用 4 个内核并行处理(
n_jobs) - 重新拟合最优模型并返回训练评分
- 为提高效率,仅采样 5 组超参数(
n_iter)
X_train 和 y_train 数据集已为您加载。
请记住,所选超参数可在 cv_results_ 中按列给出。比如超参数 criterion 的列名为 param_criterion。
本练习是课程的一部分
Python 中的超参数调优
练习说明
- 按以上说明创建超参数网格。
- 按以上说明创建一个
RandomizedSearchCV对象。 - 将该
RandomizedSearchCV对象拟合到训练数据上。 - 访问
cv_results_对象,打印建模过程中为两个超参数(max_depth和max_features)所选择的取值。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create the parameter grid
param_grid = {'max_depth': list(range(____,26)), 'max_features': [____ , ____]}
# Create a random search object
random_rf_class = RandomizedSearchCV(
estimator = ____(n_estimators=____),
param_distributions = ____, n_iter = ____,
scoring=____, n_jobs=____, cv = ____, refit=____, return_train_score = ____ )
# Fit to the training data
____.fit(X_train, y_train)
# Print the values used for both hyperparameters
print(random_rf_class.cv_results_[____])
print(random_rf_class.cv_results_[____])