開始使用免費開始

繪製 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()
編輯並執行程式碼