一.決策樹
決策樹原理 : 通過對一系列問題進行if/else的推導,最終實現決策.
1.決策樹的構建
############################# 決策樹的構建 ####################################### #導入numpy import numpy as np #導入畫圖工具 import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap #導入tree模型和數據集加載工具 from sklearn import tree,datasets #導入數據集拆分工具 from sklearn.model_selection import train_test_split wine = datasets.load_wine() #只選取數據集的前兩個特征 X = wine.data[:,:2] y = wine.target #將數據集拆分為訓練集和測試集 X_train,X_test,y_train,y_test = train_test_split(X,y)
#設定決策樹分類器最大深度為1 clf = tree.DecisionTreeClassifier(max_depth=1) #擬合訓練數據集 clf.fit(X_train,y_train)
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=1,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort=False, random_state=None,
splitter='best')
2.圖示max_depth = 1 時的分類結果
#定義圖像中分區的顏色和散點的顏色
cmap_light = ListedColormap(['#FFAAAA','#AAFFAA','#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000','#00FF00','#0000FF'])
#分別用樣本的兩個特征值創建圖像和橫軸和縱軸
x_min,x_max = X_train[:, 0].min() - 1,X_train[:, 0].max() + 1
y_min,y_max = X_train[:, 1].min() - 1,X_train[:, 1].max() + 1
xx,yy = np.meshgrid(np.arange(x_min,x_max, .02),np.arange(y_min,y_max, .02))
Z = 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,edgecolor='k',s=20)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
plt.title("Classifier:(max_depth = 1)")
plt.show()

3.圖示max_depth = 3 時的分類結果
#設定決策樹最大深度為3 clf2 = tree.DecisionTreeClassifier(max_depth=3) #重新擬合數據 clf2.fit(X_train,y_train)
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=3,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort=False, random_state=None,
splitter='best')
#定義圖像中分區的顏色和散點的顏色
cmap_light = ListedColormap(['#FFAAAA','#AAFFAA','#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000','#00FF00','#0000FF'])
#分別用樣本的兩個特征值創建圖像和橫軸和縱軸
x_min,x_max = X_train[:, 0].min() - 1,X_train[:, 0].max() + 1
y_min,y_max = X_train[:, 1].min() - 1,X_train[:, 1].max() + 1
xx,yy = np.meshgrid(np.arange(x_min,x_max, .02),np.arange(y_min,y_max, .02))
Z = clf2.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,edgecolor='k',s=20)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
plt.title("Classifier:(max_depth = 3)")
plt.show()

4.圖示max_depth = 5 時的分類結果
#設定決策樹最大深度為5 clf3 = tree.DecisionTreeClassifier(max_depth=5) #重新擬合數據 clf3.fit(X_train,y_train)
DecisionTreeClassifier(class_weight=None, criterion='gini', max_depth=5,
max_features=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, presort=False, random_state=None,
splitter='best')
#定義圖像中分區的顏色和散點的顏色
cmap_light = ListedColormap(['#FFAAAA','#AAFFAA','#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000','#00FF00','#0000FF'])
#分別用樣本的兩個特征值創建圖像和橫軸和縱軸
x_min,x_max = X_train[:, 0].min() - 1,X_train[:, 0].max() + 1
y_min,y_max = X_train[:, 1].min() - 1,X_train[:, 1].max() + 1
xx,yy = np.meshgrid(np.arange(x_min,x_max, .02),np.arange(y_min,y_max, .02))
Z = clf3.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,edgecolor='k',s=20)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
plt.title("Classifier:(max_depth = 3)")
plt.show()

5.決策樹的工作過程
'''
#導入graphviz工具
import graphviz
#導入決策樹中輸出graphviz的接口
from sklearn.tree import export_graphviz
#選擇最大深度為3的分類模型
export_graphviz(clf2,out_file="wine.dot",class_name=wine.target_names,feature_anmes=wine.feature_names[:2],impurity=False,filled=True)
#打開一個dot文件
with open("wine.dot") as f:
dot_graph = f.read()
#顯示dot文件中的圖形
graphviz.Source(dot_graph)
'''
二.隨機森林
隨機森林有時候又被稱為隨機決策森林,是一種集合學習的方法,既可以用於分類,也可以用於回歸.
1.隨機森林的構建
############################# 隨機森林的構建 ####################################### #導入numpy import numpy as np #導入畫圖工具 import matplotlib.pyplot as plt #導入隨機森林模型 from sklearn.ensemble import RandomForestClassifier #導入數據集拆分工具 from sklearn.model_selection import train_test_split #載入紅酒數據集 from sklearn.datasets import load_wine from matplotlib.colors import ListedColormap #sklearn的datasets模塊載入數據集 datasets = load_wine() wine = datasets #選擇數據集前兩個特征 X = wine.data[:,:2] y = wine.target #將數據集拆分為訓練集和數據集 X_train,X_test,y_train,y_test = train_test_split(X,y) #設定隨機森林中有6棵樹 forest = RandomForestClassifier(n_estimators=6,random_state=3) #使用模型擬合數據 forest.fit(X_train,y_train)
RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
max_depth=None, max_features='auto', max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
min_samples_leaf=1, min_samples_split=2,
min_weight_fraction_leaf=0.0, n_estimators=6, n_jobs=None,
oob_score=False, random_state=3, verbose=0, warm_start=False)
2.構圖表現隨機森林對酒的數據集進行的分類
#定義圖像中分區的顏色和散點的顏色
cmap_light = ListedColormap(['#FFAAAA','#AAFFAA','#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000','#00FF00','#0000FF'])
#分別用樣本的兩個特征值創建圖像和橫軸和縱軸
x_min,x_max = X_train[:, 0].min() - 1,X_train[:, 0].max() + 1
y_min,y_max = X_train[:, 1].min() - 1,X_train[:, 1].max() + 1
xx,yy = np.meshgrid(np.arange(x_min,x_max, .02),np.arange(y_min,y_max, .02))
Z = forest.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,edgecolor='k',s=20)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
plt.title("Classifier:RandomForest")
plt.show()

總結:
決策樹:
1.如果使用決策樹算法的話,我們幾乎不需要對數據進行預處理,這是決策樹的優點.
2.即便我們在建模的時候使用類似max_depth或是max_leaf_nodes等參數對決策樹預處理,但是其還是不可避免的出現了過擬合問題.
隨機森林:
1.和決策樹一樣,隨機森林也不需要數據預處理.
2.隨機森林在並行處理超大數據集時能提供良好的性能表現.
3.為了避免決策樹的過擬合問題,所以我們選擇了隨機森林模型
線性模型與隨機森林的對比:
隨機森林更消耗內存,虛度也比線性模型慢,所以如果希望節省內存和時間,選擇線性模型會更好一點.
在處理如:超高維數據集,稀疏數據集等隨機森林的表現就不怎么好了,這時線性模型比隨機森林表現要好一點.
文章引自:《深入淺出python機器學習》
