決策樹
你的任務是使用 scikit-learn 的 DecisionTreeClassifier,在隨附於 scikit-learn 的 breast cancer 資料集上建立一棵簡單的決策樹。
此資料集包含乳房切片檢查中,各個腫瘤的多種數值量測(例如周長與紋理)以及單一的結果值(腫瘤為惡性或良性)。
我們已將樣本(量測值)載入到 X,並將每個腫瘤的目標值載入到 y。現在,你需要將完整資料集切分為訓練集與測試集,接著訓練一個 DecisionTreeClassifier。你會指定一個名為 max_depth 的參數。此模型還有許多其他可調參數,你可以在這裡查看全部。
本練習屬於課程
使用 XGBoost 的極端梯度提升
練習說明
- 匯入:
- 從
sklearn.model_selection匯入train_test_split。 - 從
sklearn.tree匯入DecisionTreeClassifier。
- 從
- 建立訓練集與測試集,讓 20% 的資料用於測試。使用
random_state為123。 - 建立一個名為
dt_clf_4的DecisionTreeClassifier,並將max_depth設為4。此參數用來指定在到達葉節點前,最多允許連續的分割次數。 - 將分類器擬合到訓練集,並預測測試集的標籤。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the necessary modules
____
____
# Create the training and test sets
X_train, X_test, y_train, y_test = ____(____, ____, test_size=____, random_state=____)
# Instantiate the classifier: dt_clf_4
dt_clf_4 = ____
# Fit the classifier to the training set
____
# Predict the labels of the test set: y_pred_4
y_pred_4 = ____
# Compute the accuracy of the predictions: accuracy
accuracy = float(np.sum(y_pred_4==y_test))/y_test.shape[0]
print("accuracy:", accuracy)