基于企鵝數(shù)據(jù)集的決策樹分類預測
1 邏決策樹的介紹和應用
1.1 決策樹的介紹
決策樹是一種常見的分類模型,在金融風控、醫(yī)療輔助診斷等諸多行業(yè)具有較為廣泛的應用。決策樹的核心思想是基于樹結構對數(shù)據(jù)進行劃分,這種思想是人類處理問題時的本能方法。例如在婚戀市場中,女方通常會先詢問男方是否有房產(chǎn),如果有房產(chǎn)再了解是否有車產(chǎn),如果有車產(chǎn)再看是否有穩(wěn)定工作……最后得出是否要深入了解的判斷。
主要應用:
由于決策樹模型中自變量與因變量的非線性關系以及決策樹簡單的計算方法,使得它成為集成學習中最為廣泛使用的基模型。梯度提升樹(GBDT),XGBoost以及LightGBM等先進的集成模型都采用了決策樹作為基模型,在廣告計算、CTR預估、金融風控等領域大放異彩,成為當今與神經(jīng)網(wǎng)絡相提并論的復雜模型,更是數(shù)據(jù)挖掘比賽中的???。在新的研究中,南京大學周志華教授提出一種多粒度級聯(lián)森林模型,創(chuàng)造了一種全新的基于決策樹的深度集成方法,為我們提供了決策樹發(fā)展的另一種可能。
同時決策樹在一些明確需要可解釋性或者提取分類規(guī)則的場景中被廣泛應用,而其他機器學習模型在這一點很難做到。例如在醫(yī)療輔助系統(tǒng)中,為了方便專業(yè)人員發(fā)現(xiàn)錯誤,常常將決策樹算法用于輔助病癥檢測。例如在一個預測哮喘患者的模型中,醫(yī)生發(fā)現(xiàn)測試的許多高級模型的效果非常差。在他們運行了一個決策樹模型后發(fā)現(xiàn),算法認為劇烈咳嗽的病人患哮喘的風險很小。但醫(yī)生非常清楚劇烈咳嗽一般都會被立刻檢查治療,這意味著患有劇烈咳嗽的哮喘病人都會馬上得到收治。用于建模的數(shù)據(jù)認為這類病人風險很小,是因為所有這類病人都得到了及時治療,所以極少有人在此之后患病或死亡。
1.2 相關流程
了解 決策樹 的理論知識
掌握 決策樹 的 sklearn 函數(shù)調(diào)用并將其運用在企鵝數(shù)據(jù)集的預測中
Part1 Demo實踐
Step1:庫函數(shù)導入
Step2:模型訓練
Step3:數(shù)據(jù)和模型可視化
Step4:模型預測
Part2 基于企鵝(penguins)數(shù)據(jù)集的決策樹分類實踐
Step1:庫函數(shù)導入
Step2:數(shù)據(jù)讀取/載入
Step3:數(shù)據(jù)信息簡單查看
Step4:可視化描述
Step5:利用 決策樹模型 在二分類上 進行訓練和預測
Step6:利用 決策樹模型 在三分類(多分類)上 進行訓練和預測
3 算法實戰(zhàn)
3.1Demo實踐
Step1: 庫函數(shù)導入
## ?基礎函數(shù)庫import numpy as np
## 導入畫圖庫import matplotlib.pyplot as pltimport seaborn as sns## 導入決策樹模型函數(shù)from sklearn.tree import DecisionTreeClassifierfrom sklearn import tree
Step2: 訓練模型
##Demo演示LogisticRegression分類## 構造數(shù)據(jù)集x_fearures = np.array([[-1, -2], [-2, -1], [-3, -2], [1, 3], [2, 1], [3, 2]])
y_label = np.array([0, 1, 0, 1, 0, 1])## 調(diào)用決策樹回歸模型tree_clf = DecisionTreeClassifier()## 調(diào)用決策樹模型擬合構造的數(shù)據(jù)集tree_clf = tree_clf.fit(x_fearures, y_label)
Step3: 數(shù)據(jù)和模型可視化(需要用到graphviz可視化庫)
## 可視化構造的數(shù)據(jù)樣本點plt.figure()
plt.scatter(x_fearures[:,0],x_fearures[:,1], c=y_label, s=50, cmap='viridis')
plt.title('Dataset')
plt.show()

## 可視化決策樹import graphviz
dot_data = tree.export_graphviz(tree_clf, out_file=None)
graph = graphviz.Source(dot_data)
graph.render("pengunis")
'pengunis.pdf'
Step4:模型預測
## 創(chuàng)建新樣本x_fearures_new1 = np.array([[0, -1]])
x_fearures_new2 = np.array([[2, 1]])## 在訓練集和測試集上分布利用訓練好的模型進行預測y_label_new1_predict = tree_clf.predict(x_fearures_new1)
y_label_new2_predict = tree_clf.predict(x_fearures_new2)print('The New point 1 predict class:\n',y_label_new1_predict)print('The New point 2 predict class:\n',y_label_new2_predict)
The New point 1 predict class: [1]The New point 2 predict class: [0]
3.2 基于penguins_raw數(shù)據(jù)集的決策樹實戰(zhàn)
在實踐的最開始,我們首先需要導入一些基礎的函數(shù)庫包括:numpy (Python進行科學計算的基礎軟件包),pandas(pandas是一種快速,強大,靈活且易于使用的開源數(shù)據(jù)分析和處理工具),matplotlib和seaborn繪圖。
#下載需要用到的數(shù)據(jù)集!wget https://tianchi-media.oss-cn-beijing.aliyuncs.com/DSW/6tree/penguins_raw.csv
--2023-03-22 16:21:32-- ?https://tianchi-media.oss-cn-beijing.aliyuncs.com/DSW/6tree/penguins_raw.csv
正在解析主機 tianchi-media.oss-cn-beijing.aliyuncs.com (tianchi-media.oss-cn-beijing.aliyuncs.com)... 49.7.22.39
正在連接 tianchi-media.oss-cn-beijing.aliyuncs.com (tianchi-media.oss-cn-beijing.aliyuncs.com)|49.7.22.39|:443... 已連接。
已發(fā)出 HTTP 請求,正在等待回應... 200 OK
長度: 53098 (52K) [text/csv]
正在保存至: “penguins_raw.csv”
penguins_raw.csv ? ?100%[===================>] ?51.85K ?--.-KB/s ? ?in 0.04s ?
2023-03-22 16:21:33 (1.23 MB/s) - 已保存 “penguins_raw.csv” [53098/53098])
Step1:函數(shù)庫導入
## ?基礎函數(shù)庫import numpy as np
import pandas as pd## 繪圖函數(shù)庫import matplotlib.pyplot as pltimport seaborn as sns
本次我們選擇企鵝數(shù)據(jù)(palmerpenguins)進行方法的嘗試訓練,該數(shù)據(jù)集一共包含8個變量,其中7個特征變量,1個目標分類變量。共有150個樣本,目標變量為 企鵝的類別 其都屬于企鵝類的三個亞屬,分別是(Adélie, Chinstrap and Gentoo)。包含的三種種企鵝的七個特征,分別是所在島嶼,嘴巴長度,嘴巴深度,腳蹼長度,身體體積,性別以及年齡。
變量描述speciesa factor denoting penguin speciesislanda factor denoting island in Palmer Archipelago, Antarcticabill_length_mma number denoting bill lengthbill_depth_mma number denoting bill depthflipper_length_mman integer denoting flipper lengthbody_mass_gan integer denoting body masssexa factor denoting penguin sexyearan integer denoting the study year
Step2:數(shù)據(jù)讀取/載入
## 我們利用Pandas自帶的read_csv函數(shù)讀取并轉化為DataFrame格式data = pd.read_csv('./penguins_raw.csv')
## 為了方便我們僅選取四個簡單的特征,有興趣的同學可以研究下其他特征的含義以及使用方法data = data[['Species','Culmen Length (mm)','Culmen Depth (mm)', ? ? ? ? ? ?'Flipper Length (mm)','Body Mass (g)']]
Step3:數(shù)據(jù)信息簡單查看
## 利用.info()查看數(shù)據(jù)的整體信息data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 344 entries, 0 to 343Data columns (total 5 columns):
# ? Column ? ? ? ? ? ? ? Non-Null Count ?Dtype ?--- ?------ ? ? ? ? ? ? ? -------------- ?----- ?
0 ? Species ? ? ? ? ? ? ?344 non-null ? ?object
1 ? Culmen Length (mm) ? 342 non-null ? ?float64 2 ? Culmen Depth (mm) ? ?342 non-null ? ?float64 3 ? Flipper Length (mm) ?342 non-null ? ?float64 4 ? Body Mass (g) ? ? ? ?342 non-null ? ?float64
dtypes: float64(4), object(1)
memory usage: 13.6+ KB
## 進行簡單的數(shù)據(jù)查看,我們可以利用 .head() 頭部.tail()尾部data.head()
SpeciesCulmen Length (mm)Culmen Depth (mm)Flipper Length (mm)Body Mass (g)0Adelie Penguin (Pygoscelis adeliae)39.118.7181.03750.01Adelie Penguin (Pygoscelis adeliae)39.517.4186.03800.02Adelie Penguin (Pygoscelis adeliae)40.318.0195.03250.03Adelie Penguin (Pygoscelis adeliae)NaNNaNNaNNaN4Adelie Penguin (Pygoscelis adeliae)36.719.3193.03450.0
這里我們發(fā)現(xiàn)數(shù)據(jù)集中存在NaN,一般的我們認為NaN在數(shù)據(jù)集中代表了缺失值,可能是數(shù)據(jù)采集或處理時產(chǎn)生的一種錯誤。這里我們采用-1將缺失值進行填補,還有其他例如“中位數(shù)填補、平均數(shù)填補”的缺失值處理方法有興趣的同學也可以嘗試。