開始使用免費開始

正規化

正規化是指替模型加入額外資訊,以避免過度擬合。這能幫助提升你在本章前面看到的評估指標。在本練習中,你將調整決策樹的最大深度參數,觀察分類結果如何改變。

你的工作環境中已提供 X_trainy_trainX_testy_testpandas(作為 pd)、numpy(作為 np)與 sklearn 也都可用。此外,sklearn.metrics 中的 confusion_matrix()precision_score()recall_score() 亦可使用。

本練習屬於課程

用 Python 透過機器學習預測 CTR

檢視課程

練習說明

  • 透過調整每棵樹的最大深度,建立多個不同的決策樹。
  • 對每棵樹,在測試資料上進行擬合並產生預測。
  • 評估每棵樹的混淆矩陣、精確率(precision)與召回率(recall)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Iterate over different levels of max depth
for max_depth_val in [2, 3, 5, 10, 15, 20]:
  # Create and fit model
  clf = ____(____ = max_depth_val)
  print("Evaluating tree with max_depth = %s" %(max_depth_val))
  y_pred = clf.fit(____, ____).predict(____) 
  
  # Evaluate confusion matrix, precision, recall
  print("Confusion matrix: ")
  print(____(y_test, y_pred))
  prec = ____(____, ____, average = 'weighted')
  recall = ____(____, ____, average = 'weighted')
  print("Precision: %s, Recall: %s" %(prec, recall))
編輯並執行程式碼