-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclassification_tree_basic.py
79 lines (47 loc) · 2.35 KB
/
classification_tree_basic.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
##############################################################################
# IMPORT REQUIRED PACKAGES
##############################################################################
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
##############################################################################
# IMPORT SAMPLE DATA
##############################################################################
my_df = pd.read_csv("data/sample_data_classification.csv")
##############################################################################
# SPLIT INPUT VARIABLES & OUTPUT VARIABLES
##############################################################################
X = my_df.drop(["output"], axis = 1)
y = my_df["output"]
##############################################################################
# SPLIT OUT TRAINING & TEST SETS
##############################################################################
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42, stratify = y)
##############################################################################
# INSTANTIATE MODEL
##############################################################################
clf = DecisionTreeClassifier(random_state = 42, min_samples_leaf = 7)
##############################################################################
# MODEL TRAINING
##############################################################################
clf.fit(X_train, y_train)
##############################################################################
# MODEL ASSESSMENT
##############################################################################
y_pred = clf.predict(X_test)
accuracy_score(y_test, y_pred)
##############################################################################
# A DEMONSTRATION OF OVERFITTING
##############################################################################
y_pred_training = clf.predict(X_train)
accuracy_score(y_train, y_pred_training)
# Plot Decision Tree
plt.figure(figsize=(25,15))
tree = plot_tree(clf,
feature_names = X.columns,
filled = True,
rounded = True,
fontsize = 24)