小夥伴們大家好~o( ̄▽ ̄)ブ,首先聲明一下,我的開發環境是Jupyter lab,所用的庫和版本大家參考:
Python 3.7.1(你的版本至少要3.4以上
Scikit-learn 0.20.0 (你的版本至少要0.20
Graphviz 0.8.4 (沒有畫不出決策樹哦,安裝代碼conda install python-graphviz
Numpy 1.15.3, Pandas 0.23.4, Matplotlib 3.0.1, SciPy 1.1.0
用SKlearn 建立一棵決策樹
這裡採用的數據集是SKlearn中的紅酒數據集。
1 導入需要的算法庫和模塊
<pre spellcheck="false" contenteditable="true" cid="n11" mdtype="fences" >from sklearn import tree #導入tree模塊from sklearn.datasets import load_wine #導入紅酒數據集from sklearn.model_selection import train_test_split #導入訓練集和測試集切分包</pre>
2 探索數據
<pre spellcheck="false" lang="python " contenteditable="true" cid="n13" mdtype="fences" >wine = load_wine()wine.datawine.data.shapewine.targetwine.target.shape</pre>
運行的結果是這樣子的:
data就是該數據集的特徵矩陣,從運行結果可以看出,該紅酒數據集一共有178條記錄,13個特徵。
特徵矩陣中有178條記錄,相對應的標籤Y就有178個數據。
如果wine是一張表,應該長這樣:
<pre spellcheck="false" contenteditable="true" cid="n20" mdtype="fences" >import pandas as pdpd.concat([pd.DataFrame(wine.data),pd.DataFrame(wine.target)],axis=1)</pre>
這是數據集特徵列名和標籤分類
<pre spellcheck="false" contenteditable="true" cid="n23" mdtype="fences" >wine.feature_nameswine.target_names</pre>
3 分訓練集和測試集
這裡選取30%作為測試集。切分好之後,訓練集有124條數據,測試集有54條數據。
<pre spellcheck="false" contenteditable="true" cid="n28" mdtype="fences" >Xtrain, Xtest, Ytrain, Ytest = train_test_split(wine.data,wine.target,test_size=0.3)Xtrain.shapeXtest.shape</pre>
4 建立模型
<pre spellcheck="false" contenteditable="true" cid="n32" mdtype="fences" >clf = tree.DecisionTreeClassifier(criterion="entropy") #初始化樹模型clf = clf.fit(Xtrain, Ytrain) #實例化訓練集score = clf.score(Xtest, Ytest) #返回預測的準確度score</pre>
5 畫出一棵樹吧
<pre spellcheck="false" contenteditable="true" cid="n36" mdtype="fences" >feature_name = ['酒精','蘋果酸','灰','灰的鹼性','鎂','總酚','類黃酮','非黃烷類酚類','花青素','顏色強度','色調','od280/od315稀釋葡萄酒','脯氨酸']import graphvizdot_data = tree.export_graphviz(clf,out_file=None,feature_names= feature_name,class_names=["琴酒","雪莉","貝爾摩德"],filled=True,rounded=True)graph = graphviz.Source(dot_data)graph</pre>
6 探索決策樹
<pre spellcheck="false" contenteditable="true" cid="n40" mdtype="fences" >#特徵重要性clf.feature_importances_[*zip(feature_name,clf.feature_importances_)]</pre>
到現在為止,我們已經學會建立一棵完整的決策樹了。有興趣的話,動手建立一棵屬於自己的決策樹吧~