決策樹簡單介紹

前言

爲完成每日一更的習慣,今天就從與我們專業比較相關的一些基礎的機器學習基本方法說起,從目前我現在看的文獻來看,用於我們專業的分類算法也就常用的那麼幾種,隨機森林,決策樹,SVM等等,今天也是從常用數據挖掘算法總結及python實現這一書中學習了決策樹部分內容,可以說第一天是收穫滿滿

1決策樹簡介

分類決策樹模型是一種描述對實例進行的形結構。由點和有向邊組成,節點有兩種類型,內部節點與葉節點,內部節點表示特徵或屬性,葉節點表示一個類

1.1決策樹結構

在這裏插入圖片描述

1.2決策樹原理

這裏不過多講數學原理,以及數學公示的推導,講的比較白話文一點呢就是根據已有的數據指標計算每個自變量的統計特徵,根據統計特徵劃分若干的條件來進行決策樹的結構構建,這些統計特徵就包括熵,條件熵,信息增益等等

2代碼實例

2.1數據集

data.txt
1.5 50 thin
1.5 60 fat
1.6 40 thin
1.6 60 fat
1.7 60 thin
1.7 80 fat
1.8 60 thin
1.8 90 fat
1.9 70 thin
1.9 80 fat
樣本數據的第一、二列可視爲自變量爲身高體重,來衡量一個人是fat還是thin

2.2python代碼

# -*- coding: utf-8 -*-
import numpy as np
from sklearn import tree
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
#from sklearn.cross_validation import train_test_split
#因爲python的cross——validation的模塊,全部重構在model_selection下
data=[]
labels=[]
with open(r'C:\Users\asus\Desktop\data.txt') as ifile:
    for line in ifile:
        tokens=line.strip().split(' ')
        data.append([float(tk) for tk in tokens[:-1]])
        labels.append(tokens[-1])
        #將其中每行的數值型屬性加入到列表中
        #將最後的分類結果加入到labels列表中
x=np.array(data)
labels=np.array(labels)
y=np.zeros(labels.shape)
#將標籤轉化爲0,1變量
y[labels=='fat']=1
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
#生成訓練集以及交叉驗證集,test_size是交叉驗證點百分比

#基於信息熵作爲劃分類別標準對決策樹進行訓練

clf=tree.DecisionTreeClassifier(criterion='entropy')
print(clf)
#DecisionTreeClassifier(class_weight=None, criterion='entropy', max_depth=None,
#                       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')
clf.fit(x_train,y_train)
with open(r'C:\Users\asus\Desktop\tree.dot','w') as f:
    f=tree.export_graphviz(clf,out_file=f)
#這裏由於tree。dot文件沒有安裝graphviz是打不開的,因此這裏直接
#引入pydotplus庫將其轉換爲pdf
import pydotplus
dot_data = tree.export_graphviz(clf, out_file=None)
graph = pydotplus.graph_from_dot_data(dot_data)
graph.write_pdf(r'C:\Users\asus\Desktop\tree.pdf')
    #係數反映每個特徵的影響力。越大表示該特徵在分類中起到的作用越大
print(clf.feature_importances_)
answer=clf.predict(x_train)
print(x_train)
print(answer)
print(y_train)
print(np.mean(answer==y_train))
precision, recall, thresholds = precision_recall_curve(y_train,clf.predict(x_train))
#計算準確率,召回率以及用於計算二者的閾值
#準確率與召回率 #準確率:某個類別在測試結果中被正確測試的比率 
#召回率:某個類別在真實結果中被正確預測的比率 
#假設測試結果如下
#測試結果:array([ 0., 1., 0., 1., 0., 1., 0., 1., 0., 0.]) 
#真實結果:array([ 0., 1., 0., 1., 0., 1., 0., 1., 0., 1.]) 
#分爲thin的準確率爲0.83。是因爲分類器分出了6個thin,其中正確的有5個,因此分爲thin的準確率爲5/6=0.83。 
#分爲thin的召回率爲1.00。是因爲數據集中共有5個thin,而分類器把他們都分對了(雖然把一個fat分成了thin!),召回率5/5=1。 
#分爲fat的準確率爲1.00。不再贅述。 #分爲fat的召回率爲0.80。是因爲數據集中共有5個fat,而分類器只分出了4個(把一個fat分成了thin!),召回率4/5=0.80。 
#本例中,目標是儘可能保證找出來的胖子是真胖子(準確率),還是保證儘可能找到更多的胖子(召回率)。
answer_proba = clf.predict_proba(x)
#  predict_proba返回的是一個 n 行 k 列的數組,
# 第 i 行 第 j 列上的數值是模型預測 第 i 個預測樣本爲某個標籤的概率,
#並且每一行的概率和爲1。
#這裏就存在一個問題,我怎樣知道我的第j列對於於thin與fat屬性呢
#這裏將用到clf.classes_對象返回對應的屬性索引

import pandas as pd
pd.DataFrame(answer_proba,columns=clf.classes_)
#   0.0  1.0
#0  1.0  0.0
#1  0.0  1.0
#2  1.0  0.0
#3  0.0  1.0
#4  1.0  0.0
#5  0.0  1.0
#6  1.0  0.0
#7  0.0  1.0
#8  1.0  0.0
#9  0.0  1.0

answer1= clf.predict_proba(x)[:,1]

print(classification_report(y, answer1, target_names = ['thin', 'fat']))
#classification_report
#classification_report(y_true, y_pred, target_names=target_names)
#y_true:1維數組,或標籤指示器數組/稀疏矩陣,目標值。 
#y_pred:1維數組,或標籤指示器數組/稀疏矩陣,分類器返回的估計值。 
#labels:array,shape = [n_labels],報表中包含的標籤索引的可選列表。 
#target_names:字符串列表,與標籤匹配的可選顯示名稱(相同順序)。 
#sample_weight:類似於shape = [n_samples]的數組,可選項,樣本權重。 
#digits:int,輸出浮點值的位數.

其中classification_report是輸出的最終分類評價的報告
在這裏插入圖片描述
其中,左邊第一列—分類的標籤名,support列—每個標籤的出現次數,precision—各個類別的精確度,recall—召回率,
f1-score—F1值,avg / total行(最後一行)----各列的的加權平均值均值
(support列爲權值).
F1值:(綜合評價指標)精確率和召回率的調和均值(harmonic mean),或加權平均值,也稱爲F-measure或F-score。F-measure 平衡了精確率和召回率。當F-measure較高的時候,說明模型效果比較好。(精確率和召回率都越高越好,但在一些極端情況下,兩者是矛盾的)計算公式如下:
F-measure = 2 * Precision * Recall / (Precision + Recall)
本代碼中大部分來自於書中,但由於python版本的更新等原因潘老師又對原來書中代碼進行了部分更改,加上了其他註釋使得更加容易讀懂
其中代碼主要用sklearn的機器學習庫 以及常用的數據分析numpy,pandas庫,由於要將決策樹的最終結果進行可視化,dot文件要在graphviz文件中進行轉化,後面會參考鏈接來對各個步驟做出解釋
此次代碼決策樹的結果是:

最上面的參與決策的標籤是x1,x0分別代表的是體重身高
entropy是基於ID3算法的信息增益
samples是這個決策下的樣本總數目
values是一個pairs:表示的是最終胖與瘦的數目

3總結

本次決策樹的學習收益匪淺,從電子版的書中與參考的一些博客之中也學習到了不少東西,也是相當於對sklearn有了基礎的瞭解,可以看出python的庫函數都有比較“調包”的特點,但是要在瞭解原理的基礎上來進行每個參數的傳入傳出,在附錄我會放入參考鏈接以及電子版的資源僅供參考。

4參考鏈接

常用數據挖掘方法及python實現-決策樹

鏈接:https://pan.baidu.com/s/1mQG8aJ1w3iGM1UpndZcsUw
提取碼:wpbu

GraphViz安裝與配置指南

https://blog.csdn.net/chai_zheng/article/details/78226194
https://blog.csdn.net/lilyouyanglove/article/details/79518600
https://graphviz.gitlab.io/_pages/Download/Download_windows.html

Python決策樹可視化:GraphViz’s executables not found的解決方法

https://blog.csdn.net/qq_40304090/article/details/88594813

sklearn決策樹可視化

http://ywtail.github.io/2017/06/08/sklearn%E5%86%B3%E7%AD%96%E6%A0%91%E5%8F%AF%E8%A7%86%E5%8C%96/

sklearn中lr模型—評價指標函數/評價報告classification_report,含義及應用代碼示例

https://blog.csdn.net/jianjiaoxiaolu/article/details/82937673

classification_report解釋

https://blog.csdn.net/genghaihua/article/details/81155200

機器學習classification_report方法及precision精確率和recall召回率 說明

https://www.cnblogs.com/178mz/p/8558435.html

How to find the corresponding class in clf.predict_proba()

https://stackoverrun.com/cn/q/4586155

sklearn中的predict_proba方法的返回值的意義

http://sofasofa.io/forum_main_post.php?postid=1000600

sklearn.metrics.precision_recall_curve

https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_curve.html

sklearn: model_selection

https://blog.csdn.net/qq_39037910/article/details/73333206

python文件讀寫,以後就用with open語句

https://www.cnblogs.com/ymjyqsx/p/6554817.html

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