開始使用免費開始

找出最佳的 L1 懲罰係數

你現在要為 L1 正規化微調參數 C,找出能在降低模型複雜度的同時,仍維持良好效能指標的數值。你會對一系列可能的 C 值執行 for 迴圈,對每個值建立邏輯斯回歸模型,並計算效能指標。

已建立包含可能值的清單 Cl1_metrics 陣列包含 3 個欄位,第一個是 C 值,接著兩個是非零係數數量與模型召回率的預留欄位。經過縮放的特徵與目標變數已載入為訓練用的 train_Xtrain_Y,以及測試用的 test_Xtest_Y

numpypandas 分別以 nppd 載入,同時也已從 sklearn 載入 recall_score 函式。

本練習屬於課程

Python 的行銷機器學習

檢視課程

練習說明

  • 針對從 0 到串列 C 長度的 range,執行 for 迴圈。
  • 對每個 C 候選值,初始化並擬合一個 Logistic Regression,並在測試資料上預測流失。
  • 對每個 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=___))
編輯並執行程式碼