機器學習之決策樹
決策樹理論
參考:https://www.cnblogs.com/fm-yangon/p/14072896.html
決策樹的sklearn實現
決策樹模型(分類與迴歸引數方法屬性一致):
from sklearn.tree import DecisionTreeClassifier from sklearn.tree import DecisionTreeRegressor DecisionTreeClassifier(criterion='gini' , splitter='best' , max_features=None , max_depth=None , max_leaf_nodes=None , min_samples_split=2 , min_impurity_split=1e-07 , min_samples_leaf=1 , class_weight=None)
引數:
criterion:特徵選擇的標準,可以選擇gini或者entropy,前者代表基尼係數,後者代表資訊增益。預設為基尼係數,cart,ID3或者C4.5改用entropy。
splitter:特徵劃分點選擇標準。可以選擇best或者random ,前者代表每次按照特徵選擇標準選擇最優劃分,後者表示在部分劃分點中隨機地找區域性最優劃分點。預設為best,當資料量較大時,為了加快訓練速度,可以選擇使用random。
max_features:劃分時考慮的最大特徵數。可以選擇None 、log2 、sqrt 、auto,預設為None ,表示劃分時選擇所有特徵。選擇log2表示劃分是最多考慮log2N個特徵數,選擇sqrt或者auto,表示劃分時最多考慮sqrt(N)個特徵。
max_depth:決策樹最大深度,預設不輸入,表示決策樹在建立子樹時不會限制子樹的深度,常用取值在10-100之間。
max_leaf_nodes:最大葉子節點數,預設為None,不限制最大的葉子節點數量。特徵數量較多時,限制葉子節點數防止過擬合。
min_samples_split:內部節點劃分所需要的最小樣本數,如果某節點的樣本數小於設定的min_samples_split時,則不會繼續分叉子樹。預設是2,一般設定在30以上。
min_impurity_split:節點劃分的最小不純度。該值用來限制決策樹的分叉,如果某節點的不純度(資訊增益,資訊增益比,gini係數,標準差)小於這個閾值,則該節點不再分叉成子節點,直接作為葉子節點。
min_samples_leaf:葉子節點最少樣本數。如果某樣本中葉子節點的數目小於設定的min_samples_leaf的閾值,則會和兄弟節點一起被剪枝,預設為1。
class_weight:所屬型別的權重。該引數僅存在分類樹中,預設為None。當訓練集資料類別分佈非常不均衡時,建議使用該引數來防止模型過於偏向樣本多的類別。
屬性:
feature_importances_:給出各個特徵的重要程度,值越大表示對應的特徵越重要
tree_:底層的樹物件
方法:
fit(X_train ,y_train):進行模型訓練
score(X_test ,y_test):返回模型在測試集上的預測準確率
predict(X):用訓練好的模型來預測待預測資料集X,返回資料為預測集對應的預測結果yˆ
predict_proba(X):返回一個數組,陣列元素依次為預測集X屬於各個類別的概率
predict_log_proba(X):返回一個數組,陣列的元素依次是預測集X屬於各個類別的對數概率,迴歸樹沒有該方法
決策樹案例之鳶尾花:
from sklearn import datasets import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.tree import DecisionTreeClassifier iris = datasets.load_iris() X = iris.data[:,:2] y = iris.target cmap_light = ListedColormap(['#FFAAAA' ,'#AAFFAA' ,'#AAAAFF']) cmap_bold = ListedColormap(['#FF0000' ,'#00FF00' ,'#0000FF']) dc_clf = DecisionTreeClassifier() dc_clf.fit(X ,y) x_min ,x_max = X[:,0].min() - 1 ,X[:,0].max() + 1 y_min ,y_max = X[:,1].min() - 1 ,X[:,1].max() + 1 xx ,yy = np.meshgrid(np.arange(x_min ,x_max , 0.02) ,np.arange(y_min ,y_max , 0.02)) z = dc_clf.predict(np.c_[xx.ravel() ,yy.ravel()]) z = z.reshape(xx.shape) plt.figure() plt.pcolormesh(xx ,yy ,z ,cmap = cmap_light) plt.scatter(X[:,0] ,X[:,1] ,c= y ,cmap = cmap_bold) plt.xlim(xx.min() ,xx.max()) plt.ylim(yy.min() ,yy.max()) plt.title("decision tree default parameter") plt.show()
結果比較準確
from sklearn import datasets import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score from sklearn.metrics import classification_report ,confusion_matrix iris = datasets.load_iris() X = iris.data y = iris.target X_train ,X_test ,y_train ,y_test = train_test_split(X ,y ,train_size = 0.7) dc_clf = DecisionTreeClassifier() dc_clf.fit(X_train ,y_train) y_pred = dc_clf.predict(X_test) def cm_plot(y, yp): cm = confusion_matrix(y, yp) #混淆矩陣 import matplotlib.pyplot as plt #匯入作相簿 plt.matshow(cm ,cmap=plt.cm.Greens) #畫混淆矩陣圖,配色風格使用cm.Greens,更多風格請參考官網。 plt.colorbar() #顏色標籤 for x in range(len(cm)): #資料標籤 for y in range(len(cm)): plt.annotate(cm[x,y], xy=(x, y), horizontalalignment='center', verticalalignment='center') plt.ylabel('True label') #座標軸標籤 plt.xlabel('Predicted label') #座標軸標籤 plt.title('confusion_matrix') return plt print('交叉驗證結果:') print(cross_val_score(dc_clf ,X_test ,y_test ,cv = 5)) print("查準率、查全率、F1分值:") print(classification_report(y_test ,y_pred ,target_names=None)) print("混淆矩陣:") cm_plot(y_test,y_pred)
決策樹小結:
1、優點:
1、簡單且易於理解。對決策樹模型進行視覺化後可以很清楚地看到每一顆樹分支的引數,而且很容易理解背後的邏輯。
2、可以同時處理類別型和數值型資料。
3、可以處理多分類和非線性分類問題。
4、模型訓練好之後進行預測時執行速度很快。決策樹模型一經訓練之後,後面預測過程只是對各個待預測樣本從樹的根節點往下找到一條符合特徵約束的路徑,因此預測速度很快。
5、方便做整合。樹模型的精度很高,雖然存在過擬合的風險,但是可以通過整合來改善,隨機森林和GBDT等整合模型都是使用決策樹作為基學習器。
2、缺點:
1、決策樹模型對噪聲比較敏感。在訓練集噪聲比較大時得到的模型容易過擬合(可以通過剪枝和整合來改善)。
2、在處理特徵關聯性較強的資料時表現的不好。