模型挑選
正規化與交叉驗證都是進行模型挑選的有力工具。正規化可以幫助避免過度擬合,而交叉驗證能確保你的模型被正確評估。在本練習中,你會同時使用正規化與交叉驗證,並檢查模型之間是否有顯著差異。你只需要計算 precision,但同樣的方法也能輕鬆套用到 recall 與其他評估指標。
X_train、y_train、X_test、y_test 已經在你的工作環境中可用。pandas 命名為 pd、numpy 命名為 np,以及 sklearn 也都可用。sklearn.metrics 中的 precision_score() 與 recall_score() 可用,sklearn.model_selection 中的 KFold() 與 cross_val_score() 也可使用。
本練習屬於課程
用 Python 透過機器學習預測 CTR
練習說明
- 使用
n_splits設定為 4 來建立 K 折交叉驗證,並指定給k-fold。 - 建立一個決策樹分類器。
- 使用
k_fold執行交叉驗證,並在指定的max_depth值下評估決策樹模型的 precision 與 recall。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Iterate over different levels of max depth and set up k-fold
for max_depth_val in [3, 5, 10]:
k_fold = ____(____ = 4, random_state = 0, shuffle = True)
clf = ____(____ = max_depth_val)
print("Evaluating Decision Tree for max_depth = %s" %(max_depth_val))
y_pred = clf.fit(____, ____).predict(____)
# Calculate precision for cross validation and test
cv_precision = ____(
____, X_train, y_train, cv = k_fold, scoring = 'precision_weighted')
precision = ____(y_test, y_pred, average = 'weighted')
print("Cross validation Precision: %s" %(cv_precision))
print("Test Precision: %s" %(precision))