开始使用免费开始使用

使用 RandomizedSearchCV 进行超参数调优

正如您所见,GridSearchCV 的计算开销可能很大,尤其是在搜索空间很大时。此时可以使用 RandomizedSearchCV,它会从给定的概率分布中抽取固定数量的超参数组合进行测试。

来自 diabetes_df 的训练集和测试集已为您预加载为 X_trainX_testy_trainy_test,目标变量为 "diabetes"。已经创建了一个逻辑回归模型并存为 logreg,以及一个 KFold 变量并存为 kf

您将定义一组超参数范围,并使用已从 sklearn.model_selection 导入的 RandomizedSearchCV,在这些选项中寻找最优超参数。

本练习是课程的一部分

使用 scikit-learn 的监督学习

查看课程

练习说明

  • 创建 params:将 "l1""l2" 作为 penalty 的取值,将 C 设为 0.11.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(____.____))
编辑并运行代码