天天看點

python 決策樹_如何利用Python建立決策樹模型?

Python的機器學習包中的DecisionTreeClassifier可以進行決策樹分類。

1.輸入資料集。

import pandas as pddf=pd.DataFrame({'name':['Lily','Lucy','Jim','Tom','Anna','Jack','Sam'],'weight':[42,38,78,67,52,80,92],'height':[162,158,169,170,166,175,178],'is_fat':[0,0,1,0,1,0,1]})

2.導入決策樹工具包。

from sklearn.tree import DecisionTreeClassifier

3.準備訓練集,is_fat為目标變量,'weight'和'height'為自變量。

X=df.loc[:,['weight','height']]

y=df['is_fat']

python 決策樹_如何利用Python建立決策樹模型?

4.建立模型,并進行模型訓練。

clf=DecisionTreeClassifier()

clf.fit(X,y)

5.利用模型進行預測。

y_pred=clf.predict(X)

print(y_pred)

python 決策樹_如何利用Python建立決策樹模型?

6.根據預測結果繪制散點圖。

import matplotlib.pyplot as plt

plt.figure()

df['is_fat_pred']=y_pred

df_0=df[df['is_fat_pred']==0]

df_1=df[df['is_fat_pred']==1]

plt.scatter(df_0['weight'],df_0['height'],c='y',s=50,label='normal')

plt.scatter(df_1['weight'],df_1['height'],c='lightblue',s=100,label='fat')

for k in range(len(X)): 

  plt.text(X['weight'][k],X['height'][k],df['name'][k]) #設定散點标簽

  plt.legend() 

plt.show()

python 決策樹_如何利用Python建立決策樹模型?

繼續閱讀