开始使用免费开始使用

确定最优的 L1 惩罚系数

现在,您将调优 L1 正则化的 C 参数,找到既能降低模型复杂度又能保持良好性能指标的取值。您将对一系列可能的 C 值运行 for 循环,在每个取值上训练逻辑回归模型,并计算性能指标。

我们已创建包含候选取值的列表 C。数组 l1_metrics 已构建为包含 3 列:第一列为 C 值,后两列分别作为非零系数数量和模型召回率的占位符。已加载过标准化的特征与目标变量:训练集为 train_Xtrain_Y,测试集为 test_Xtest_Y

已加载 numpypandas(分别为 nppd),同时从 sklearn 导入了 recall_score 函数。

本练习是课程的一部分

Python 营销中的机器学习

查看课程

练习说明

  • 对从 0 到列表 C 长度的区间运行 for 循环。
  • 对每个 C 备选值,初始化并拟合逻辑回归模型,并在测试数据上预测流失。
  • 对每个 C 备选值,将非零系数数量与召回率分别存入 l1_metrics 的第 2、3 列。
  • l1_metrics 转换为 pandas 的 DataFrame,并使用合适的列名。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Run a for loop over the range of C list length
for index in ___(0, len(C)):
  # Initialize and fit Logistic Regression with the C candidate
  logreg = ___(penalty='l1', C=C[___], solver='liblinear')
  logreg.fit(___, train_Y)
  # Predict churn on the testing data
  pred_test_Y = logreg.___(test_X)
  # Create non-zero count and recall score columns
  l1_metrics[index,1] = np.___(logreg.coef_)
  l1_metrics[index,2] = recall_score(___, pred_test_Y)

# Name the columns and print the array as pandas DataFrame
col_names = ['C','Non-Zero Coeffs','Recall']
print(pd.DataFrame(l1_metrics, columns=___))
编辑并运行代码