开始使用免费开始使用

绘制 AUC 曲线

前向逐步变量选择会给出一个最优的变量加入顺序。为了决定在何处截断变量,您可以绘制训练集和测试集的 AUC 曲线。这些曲线展示了当模型使用前 1 个、前 2 个、前 3 个……变量时,训练集和测试集的 AUC。

在本练习中,您将学习如何绘制这些 AUC 曲线。用于计算 AUC 的方法 auc_train_test 已为您实现,可按如下方式使用:

auc_train, auc_test = auc_train_test(variables, target, train, test)

其中,variables 是用于逻辑回归模型的变量集合,target 是包含目标名的列表,traintest 分别是训练集和测试集的基表。

按前向逐步法排序的变量保存在列表 variables 中。您可以在控制台中查看。此外,还为您预先定义了 3 个空列表:

  • auc_values_train:用于保存每次迭代时模型在训练集上的 AUC 值
  • auc_values_test:用于保存每次迭代时模型在测试集上的 AUC 值
  • variables_evaluate:用于保存每次迭代时被评估的变量

本练习是课程的一部分

Python 预测分析入门

查看课程

练习说明

  • 遍历各个变量。
  • 在每次迭代中,将 variables 中的下一个变量添加到 variables_evaluate
  • 在每次迭代中,使用 auc_train_test 方法计算训练集和测试集的 AUC。DataFrame traintest 分别包含训练集和测试集。
  • 在每次迭代中,将计算得到的数值添加到 auc_values_trainauc_values_test 中。

交互式实操练习

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

# Keep track of train and test AUC values
auc_values_train = []
auc_values_test = []
variables_evaluate = []

# Iterate over the variables in variables
for v in ____:
  
    # Add the variable
    variables_evaluate.append(____)
    
    # Calculate the train and test AUC of this set of variables
    auc_train, auc_test = ____(____, ["target"], ____, ____)
    
    # Append the values to the lists
    auc_values_train.append(____)
    auc_values_test.append(____)
    
# Make plot of the AUC values
import matplotlib.pyplot as plt
import numpy as np

x = np.array(range(0,len(auc_values_train)))
y_train = np.array(auc_values_train)
y_test = np.array(auc_values_test)
plt.xticks(x, variables, rotation = 90)
plt.plot(x,y_train)
plt.plot(x,y_test)
plt.ylim((0.6, 0.8))
plt.show()
编辑并运行代码