01_決策樹案例一:鳶尾花數據分類

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import warnings
from sklearn import tree #決策樹
from sklearn.tree import DecisionTreeClassifier #分類樹
from sklearn.model_selection  import train_test_split#測試集和訓練集
from sklearn.pipeline import Pipeline #管道
from sklearn.feature_selection import SelectKBest #特徵選擇
from sklearn.feature_selection import chi2 #卡方統計量
from sklearn.preprocessing import MinMaxScaler  #數據歸一化
from sklearn.decomposition import PCA #主成分分析
from sklearn.model_selection import GridSearchCV #網格搜索交叉驗證,用於選擇最優的參數
## 設置屬性防止中文亂碼
mpl.rcParams['font.sans-serif'] = [u'SimHei']
mpl.rcParams['axes.unicode_minus'] = False
warnings.filterwarnings('ignore', category=FutureWarning)
iris_feature_E = 'sepal length', 'sepal width', 'petal length', 'petal width'
iris_feature_C = '花萼長度', '花萼寬度', '花瓣長度', '花瓣寬度'
iris_class = 'Iris-setosa', 'Iris-versicolor', 'Iris-virginica'
#讀取數據
path = './datas/iris.data'  
data = pd.read_csv(path, header=None)
x=data[list(range(4))]#獲取X變量
y=pd.Categorical(data[4]).codes#把Y轉換成分類型的0,1,2
print("總樣本數目:%d;特徵屬性數目:%d" % x.shape)
總樣本數目:150;特徵屬性數目:4
data.head(5)
0 1 2 3 4
0 5.1 3.5 1.4 0.2 Iris-setosa
1 4.9 3.0 1.4 0.2 Iris-setosa
2 4.7 3.2 1.3 0.2 Iris-setosa
3 4.6 3.1 1.5 0.2 Iris-setosa
4 5.0 3.6 1.4 0.2 Iris-setosa
#數據進行分割(訓練數據和測試數據)
x_train1, x_test1, y_train1, y_test1 = train_test_split(x, y, train_size=0.8, random_state=14)
x_train, x_test, y_train, y_test = x_train1, x_test1, y_train1, y_test1
print ("訓練數據集樣本數目:%d, 測試數據集樣本數目:%d" % (x_train.shape[0], x_test.shape[0]))
y_train = y_train.astype(np.int)
y_test = y_test.astype(np.int)
訓練數據集樣本數目:120, 測試數據集樣本數目:30
y_train
array([0, 1, 1, 0, 1, 0, 2, 1, 2, 1, 2, 0, 0, 1, 2, 2, 0, 0, 0, 1, 0, 0,
       2, 2, 1, 2, 2, 0, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 2,
       2, 0, 0, 2, 0, 2, 0, 0, 2, 1, 0, 1, 2, 2, 2, 1, 1, 2, 1, 2, 2, 2,
       0, 2, 1, 1, 0, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 2, 2, 0, 2, 0, 1,
       2, 0, 1, 0, 0, 2, 2, 2, 0, 2, 2, 1, 1, 0, 2, 2, 0, 2, 1, 0, 2, 0,
       0, 0, 2, 1, 2, 2, 1, 0, 1, 2])
#數據標準化
#StandardScaler (基於特徵矩陣的列,將屬性值轉換至服從正態分佈)
#標準化是依照特徵矩陣的列處理數據,其通過求z-score的方法,將樣本的特徵值轉換到同一量綱下
#常用與基於正態分佈的算法,比如迴歸

#數據歸一化
#MinMaxScaler (區間縮放,基於最大最小值,將數據轉換到0,1區間上的)
#提升模型收斂速度,提升模型精度
#常見用於神經網絡

#Normalizer (基於矩陣的行,將樣本向量轉換爲單位向量)
#其目的在於樣本向量在點乘運算或其他核函數計算相似性時,擁有統一的標準
#常見用於文本分類和聚類、logistic迴歸中也會使用,有效防止過擬合

ss = MinMaxScaler ()
#用標準化方法對數據進行處理並轉換
x_train = ss.fit_transform(x_train)
x_test = ss.transform(x_test)
print ("原始數據各個特徵屬性的調整最小值:",ss.min_)
print ("原始數據各個特徵屬性的縮放數據值:",ss.scale_)
原始數據各個特徵屬性的調整最小值: [-1.19444444 -0.83333333 -0.18965517 -0.04166667]
原始數據各個特徵屬性的縮放數據值: [0.27777778 0.41666667 0.17241379 0.41666667]
#特徵選擇:從已有的特徵中選擇出影響目標值最大的特徵屬性
#常用方法:{ 分類:F統計量、卡方係數,互信息mutual_info_classif
        #{ 連續:皮爾遜相關係數 F統計量 互信息mutual_info_classif
#SelectKBest(卡方係數)
ch2 = SelectKBest(chi2,k=3)#在當前的案例中,使用SelectKBest這個方法從4個原始的特徵屬性,選擇出來3個
#K默認爲10
#如果指定了,那麼就會返回你所想要的特徵的個數
x_train = ch2.fit_transform(x_train, y_train)#訓練並轉換
x_test = ch2.transform(x_test)#轉換
select_name_index = ch2.get_support(indices=True)
print ("對類別判斷影響最大的三個特徵屬性分佈是:",ch2.get_support(indices=False))
print(select_name_index)
對類別判斷影響最大的三個特徵屬性分佈是: [ True False  True  True]
[0 2 3]
#降維:對於數據而言,如果特徵屬性比較多,在構建過程中,會比較複雜,這個時候考慮將多維(高維)映射到低維的數據
#常用的方法:
#PCA:主成分分析(無監督)
#LDA:線性判別分析(有監督)類內方差最小,人臉識別,通常先做一次pca

pca = PCA(n_components=2)#構建一個pca對象,設置最終維度是2維
# #這裏是爲了後面畫圖方便,所以將數據維度設置了2維,一般用默認不設置參數就可以

x_train = pca.fit_transform(x_train)#訓練並轉換
x_test = pca.transform(x_test)#轉換
#模型的構建
model = DecisionTreeClassifier(criterion='entropy',random_state=0)#另外也可選gini 
#模型訓練
model.fit(x_train, y_train)
#模型預測
y_test_hat = model.predict(x_test) 
#模型結果的評估
y_test2 = y_test.reshape(-1)
result = (y_test2 == y_test_hat)
print ("準確率:%.2f%%" % (np.mean(result) * 100))
#實際可通過參數獲取
print ("Score:", model.score(x_test, y_test))#準確率
print ("Classes:", model.classes_)
準確率:96.67%
Score: 0.9666666666666667
Classes: [0 1 2]
#畫圖
N = 100  #橫縱各採樣多少個值
x1_min = np.min((x_train.T[0].min(), x_test.T[0].min()))
x1_max = np.max((x_train.T[0].max(), x_test.T[0].max()))
x2_min = np.min((x_train.T[1].min(), x_test.T[1].min()))
x2_max = np.max((x_train.T[1].max(), x_test.T[1].max()))

t1 = np.linspace(x1_min, x1_max, N)
t2 = np.linspace(x2_min, x2_max, N)
x1, x2 = np.meshgrid(t1, t2)  # 生成網格採樣點
x_show = np.dstack((x1.flat, x2.flat))[0] #測試點

y_show_hat = model.predict(x_show) #預測值

y_show_hat = y_show_hat.reshape(x1.shape)  #使之與輸入的形狀相同
print(y_show_hat.shape)
y_show_hat[0]
(100, 100)





array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
#畫圖
plt_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
plt_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])

plt.figure(facecolor='w')
plt.pcolormesh(x1, x2, y_show_hat, cmap=plt_light) 
plt.scatter(x_test.T[0], x_test.T[1], c=y_test.ravel(), edgecolors='k', s=150, zorder=10, cmap=plt_dark, marker='*')  # 測試數據
plt.scatter(x_train.T[0], x_train.T[1], c=y_train.ravel(), edgecolors='k', s=40, cmap=plt_dark)  # 全部數據
plt.xlabel(u'特徵屬性1', fontsize=15)
plt.ylabel(u'特徵屬性2', fontsize=15)
plt.xlim(x1_min, x1_max)
plt.ylim(x2_min, x2_max)
plt.grid(True)
plt.title(u'鳶尾花數據的決策樹分類', fontsize=18)
plt.show()

在這裏插入圖片描述

#參數優化
pipe = Pipeline([
            ('mms', MinMaxScaler()),
            ('skb', SelectKBest(chi2)),
            ('pca', PCA()),
            ('decision', DecisionTreeClassifier(random_state=0))
        ])

# 參數
parameters = {
    "skb__k": [1,2,3,4],
    "pca__n_components": [0.5,0.99],#設置爲浮點數代表主成分方差所佔最小比例的閾值,這裏不建議設置爲數值,思考一下?
    "decision__criterion": ["gini", "entropy"],
    "decision__max_depth": [1,2,3,4,5,6,7,8,9,10]
}
#數據
x_train2, x_test2, y_train2, y_test2 = x_train1, x_test1, y_train1, y_test1
#模型構建:通過網格交叉驗證,尋找最優參數列表, param_grid可選參數列表,cv:進行幾折交叉驗證
gscv = GridSearchCV(pipe, param_grid=parameters,cv=3)
#模型訓練
gscv.fit(x_train2, y_train2)
#算法的最優解
print("最優參數列表:", gscv.best_params_)
print("score值:",gscv.best_score_)
#預測值
y_test_hat2 = gscv.predict(x_test2)
最優參數列表: {'decision__criterion': 'gini', 'decision__max_depth': 4, 'pca__n_components': 0.99, 'skb__k': 3}
score值: 0.95
#應用最優參數看效果
mms_best = MinMaxScaler()
skb_best = SelectKBest(chi2, k=3)
pca_best = PCA(n_components=0.99)
decision3 = DecisionTreeClassifier(criterion='gini', max_depth=4)
#構建模型並訓練模型
x_train3, x_test3, y_train3, y_test3 = x_train1, x_test1, y_train1, y_test1
x_train3 = pca_best.fit_transform(skb_best.fit_transform(mms_best.fit_transform(x_train3), y_train3))
x_test3 = pca_best.transform(skb_best.transform(mms_best.transform(x_test3)))
decision3.fit(x_train3, y_train3)

print("正確率:", decision3.score(x_test3, y_test3))
正確率: 0.9666666666666667
#基於原始數據前3列比較一下決策樹在不同深度的情況下錯誤率
x_train4, x_test4, y_train4, y_test4 = train_test_split(x.iloc[:, :2], y, train_size=0.7, random_state=14)

depths = np.arange(1, 15)
err_list = []
for d in depths:
    clf = DecisionTreeClassifier(criterion='entropy', max_depth=d)#僅設置了這二個參數,沒有對數據進行特徵選擇和降維,所以跟前面得到的結果不同
    clf.fit(x_train4, y_train4)
    
    score = clf.score(x_test4, y_test4)
    err = 1 - score
    err_list.append(err)
    print("%d深度,正確率%.5f" % (d, score))

## 畫圖
plt.figure(facecolor='w')
plt.plot(depths, err_list, 'ro-', lw=3)
plt.xlabel(u'決策樹深度', fontsize=16)
plt.ylabel(u'錯誤率', fontsize=16)
plt.grid(True)
plt.title(u'決策樹層次太多導致的擬合問題(欠擬合和過擬合)', fontsize=18)
plt.show()
1深度,正確率0.57778
2深度,正確率0.71111
3深度,正確率0.75556
4深度,正確率0.75556
5深度,正確率0.71111
6深度,正確率0.66667
7深度,正確率0.66667
8深度,正確率0.66667
9深度,正確率0.71111
10深度,正確率0.66667
11深度,正確率0.66667
12深度,正確率0.66667
13深度,正確率0.66667
14深度,正確率0.66667

在這裏插入圖片描述

# GridSearchCV 模型保存和加載
from sklearn.externals import joblib
best_gcsv_model = gscv.best_estimator_
joblib.dump(best_gcsv_model, "gscv.model")
best_gcsv_model2 = joblib.load("gscv.model") # 直接加載模型就表示可以用了,不需要重新訓練了
print(best_gcsv_model2.predict(x_test2))
print(y_test_hat2)
[0 0 0 1 2 1 0 1 0 1 1 0 2 2 0 1 0 2 2 1 0 0 0 1 0 2 0 1 1 0]
[0 0 0 1 2 1 0 1 0 1 1 0 2 2 0 1 0 2 2 1 0 0 0 1 0 2 0 1 1 0]
# 方式一:輸出形成dot文件,然後使用graphviz的dot命令將dot文件轉換爲pdf
from sklearn import tree
with open('iris.dot', 'w') as f:
    f = tree.export_graphviz(model, out_file=f)
# 命令行執行dot命令: dot -Tpdf iris.dot -o iris.pdf
# 方式二:直接使用pydotplus插件生成pdf文件
from sklearn import tree
import pydotplus 
dot_data = tree.export_graphviz(model, out_file=None) 
graph = pydotplus.graph_from_dot_data(dot_data) 
# graph.write_pdf("iris2.pdf") 
graph.write_png("0.png")
True
# 方式三:直接生成圖片
from sklearn import tree
from IPython.display import Image
import pydotplus
dot_data = tree.export_graphviz(model, out_file=None, 
                         feature_names=['sepal length', 'sepal width', 'petal length', 'petal width'],  
                         class_names=['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'],  
                         filled=True, rounded=True,  
                         special_characters=True)  
graph = pydotplus.graph_from_dot_data(dot_data)  
Image(graph.create_png()) 

在這裏插入圖片描述
`

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章