确定最优的 L1 惩罚系数
现在,您将调优 L1 正则化的 C 参数,找到既能降低模型复杂度又能保持良好性能指标的取值。您将对一系列可能的 C 值运行 for 循环,在每个取值上训练逻辑回归模型,并计算性能指标。
我们已创建包含候选取值的列表 C。数组 l1_metrics 已构建为包含 3 列:第一列为 C 值,后两列分别作为非零系数数量和模型召回率的占位符。已加载过标准化的特征与目标变量:训练集为 train_X、train_Y,测试集为 test_X、test_Y。
已加载 numpy 与 pandas(分别为 np 和 pd),同时从 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=___))