Python Machine Learning

Decision Tree

OutlookTemperatureHumidityWindyPlay
sunnyhothighWeakno
sunnyhothighStrongno
overcasthothighWeakyes
rainymildhighWeakyes
rainycoolnormalWeakyes
rainycoolnormalStrongno
overcastcoolnormalStrongyes
sunnymildhighWeakno
sunnycoolnormalWeakyes
rainymildnormalWeakyes
sunnymildnormalStrongyes
overcastmildhighStrongyes
overcasthotnormalWeakyes
rainymildhighStrongno
OutlookTemperatureHumidityWindyPlay
2101no
2100no
0101yes
1201yes
1011yes
1010no
0010yes
2201no
2011yes
1211yes
2210yes
0200yes
0111yes
1200no
PlayyesnosumEntropy
9514$$-\frac{9}{14}log(\frac{9}{14})--\frac{5}{14}log(\frac{5}{14})=0.940285959 $$

$$Gain(Outlook(0.5))=Entropy(Play)-\frac{4}{14}*Entropy(Outlook_{<=0.5})-\frac{10}{14}entropy(Outlook_{>0.5})$$

OutlookyesnosumEntropyGain
≤ 0.540400.226000244
> 0.555101
≤ 1.57290.7642045070.102243564
> 1.52350.970950594
Temperatureyesnosumentropygain
≤ 0.53140.8112781240.01495607
> 0.564100.970950594
≤ 1.55380.9544340030.001339742
> 1.54260.918295834
Humidityyesnosumentropygain
≤ 0.53470.9852281360.151835501
> 0.56170.591672779
Windyyesnosumentropygain
≤ 0.533610.04812703
> 0.56280.811278124

Entropy

$$entropy = -\sum{p_ilog_2(p_i)}$$

from scipy.stats import entropy
entropy([9, 5], base=2)

Preprocessing

from sklearn.preprocessing import OrdinalEncoder
from pandas import read_csv
df = read_csv('play.csv')
encoder = OrdinalEncoder(dtype=int)
X = encoder.fit_transform(df[df.columns[:-1]])
y = df['Play']

Build Model

from sklearn.tree import DecisionTreeClassifier
classifier = DecisionTreeClassifier(criterion='entropy')
classifier.fit(X, y)

Plot Tree

from sklearn.tree import plot_tree
from matplotlib import pyplot
plot_tree(classifier, feature_names=df.columns[:-1], class_names=["no", "yes"])
pyplot.show()

Accuracy Score

classifier.score(X, y)

Gini

$$G=1-\sum_k{p_k^2}$$

Reference

Decision Treehttps://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html