文章目錄[隱藏]
決(jue) 策樹是一種用於(yu) 分類和回歸的監督學習(xi) 方法。決(jue) 策樹目標是創建一個(ge) 模型,通過學習(xi) 從(cong) 數據特征推斷出的簡單決(jue) 策規則來預測目標變量的值。
決策樹優缺點
決(jue) 策樹的一些優(you) 點是:
- 易於理解和解釋。樹可以被可視化。
- 需要很少的訓練數據
- 能處理數值和類別數據
- 能夠處理多輸出問題
決(jue) 策樹的一些缺點是:
- 深度太深,很容易過擬合
- 決策樹可能不穩定
- 決策樹的預測結果不是連續的
- 決策樹節點分裂過程是貪心的
sklearn 決策樹API
DecisionTreeClassifier
https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.htm
二分類或多分類、多標簽分類
from sklearn.datasets import load_iris from sklearn.model_selection import cross_val_score from sklearn.tree import DecisionTreeClassifier clf = DecisionTreeClassifier(random_state=0) iris = load_iris() cross_val_score(clf, iris.data, iris.target, cv=10)
DecisionTreeRegressor
https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeRegressor.html
回歸、多標簽回歸
from sklearn.datasets import load_diabetes from sklearn.model_selection import cross_val_score from sklearn.tree import DecisionTreeRegressor X, y = load_diabetes(return_X_y=True) regressor = DecisionTreeRegressor(random_state=0) cross_val_score(regressor, X, y, cv=10)
sklearn 底層樹結構
樹結構
決(jue) 策分類器有一個(ge) 名為(wei) 的屬性tree_,它允許訪問低級屬性,例如node_count(節點總數),和max_depth(樹的最大深度),它還存儲(chu) 整個(ge) 二叉樹結構,表示為(wei) 多個(ge) 並行數組。
- children_left[i]: 節點的左子節點的 idi,如果是葉節點則為 -1
- children_right[i]: 節點右子節點的idi,如果是葉節點則為-1
- feature[i]: 用於分裂節點的特征i
- threshold[i]:節點的閾值i
- n_node_samples[i]:到達節點的訓練樣本數i
- impurity[i]:節點處的雜質i
iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0)
clf.fit(X_train, y_train)
n_nodes = clf.tree_.node_count
children_left = clf.tree_.children_left
children_right = clf.tree_.children_right
feature = clf.tree_.feature
threshold = clf.tree_.threshold
決(jue) 策路徑
decision_path方法輸出一個(ge) 指示矩陣,允許檢索感興(xing) 趣的樣本遍曆的節點。位置處的指示矩陣中的非零元素表示樣本經過節點。
apply方法返回樣本所達到的葉id,得到樣本所達到的葉子節點 ID 的數組,這可以用對樣本進行編碼,也可以用於(yu) 特征工程。
iris = load_iris() X = iris.data y = iris.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = DecisionTreeClassifier(max_leaf_nodes=3, random_state=0)
clf.fit(X_train, y_train)
node_indicator = clf.decision_path(X_test)
leaf_id = clf.apply(X_test)
參考資料
- https://scikit-learn.org/stable/modules/tree.html
- https://scikit-learn.org/stable/auto_examples/tree/plot_unveil_tree_structure.html
- https://scikit-learn.org/stable/auto_examples/tree/
評論已經被關(guan) 閉。