使用 RandomizedSearchCV 进行超参数调优
正如您所见,GridSearchCV 的计算开销可能很大,尤其是在搜索空间很大时。此时可以使用 RandomizedSearchCV,它会从给定的概率分布中抽取固定数量的超参数组合进行测试。
来自 diabetes_df 的训练集和测试集已为您预加载为 X_train、X_test、y_train 和 y_test,目标变量为 "diabetes"。已经创建了一个逻辑回归模型并存为 logreg,以及一个 KFold 变量并存为 kf。
您将定义一组超参数范围,并使用已从 sklearn.model_selection 导入的 RandomizedSearchCV,在这些选项中寻找最优超参数。
本练习是课程的一部分
使用 scikit-learn 的监督学习
练习说明
- 创建
params:将"l1"和"l2"作为penalty的取值,将C设为0.1到1.0之间的50个浮点数范围,并将class_weight设为"balanced"或包含0:0.8, 1:0.2的字典。 - 创建 Randomized Search CV 对象,传入模型与参数,并将
cv设为kf。 - 将
logreg_cv拟合到训练数据。 - 打印模型的最优参数和准确率分数。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create the parameter space
params = {"penalty": ["____", "____"],
"tol": np.linspace(0.0001, 1.0, 50),
"C": np.linspace(____, ____, ____),
"class_weight": ["____", {0:____, 1:____}]}
# Instantiate the RandomizedSearchCV object
logreg_cv = ____(____, ____, cv=____)
# Fit the data to the model
logreg_cv.____(____, ____)
# Print the tuned parameters and score
print("Tuned Logistic Regression Parameters: {}".format(____.____))
print("Tuned Logistic Regression Best Accuracy Score: {}".format(____.____))