開始使用免費開始

交叉驗證

交叉驗證是一種用來檢查模型保留集效能的技巧。這麼做是為了確保測試表現不是因為資料切分的偶然因素所造成。在本練習中,你會使用 sklearn 的實作,透過 KFold() 模組執行 K 折交叉驗證,來評估決策樹的 precision 與 recall。

X_trainy_trainX_testy_test 已提供在你的工作環境中。pandas 作為 pdnumpy 作為 np,以及 sklearn 也都可用。sklearn.model_selection 中的 KFold()cross_val_score() 也都可使用。

本練習屬於課程

用 Python 透過機器學習預測 CTR

檢視課程

練習說明

  • 建立一個決策樹分類器。
  • 設定一個有 4 個分割的 K 折交叉驗證,並指定為 k-fold
  • 使用 k-fold 搭配 cross_val_score() 來執行交叉驗證,評估模型的 precision 與 recall(不要使用 recall_score()precision_score()!)。

動手互動練習

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

# Create model 
clf = ____

# Set up k-fold
k_fold = ____(n_splits = 4, random_state = 0, shuffle = True)

# Evaluate precision and recall for each fold
precision = ____(
  clf, X_train, ____, cv = ____, scoring = 'precision_weighted')
recall = ____(
  clf, X_train, ____, cv = ____, scoring = 'recall_weighted')
print("Precision scores: %s" %(precision)) 
print("Recall scores: %s" %(recall))
編輯並執行程式碼