import numpy as np from graphviz import Digraph from pandas import rea

  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
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import numpy as np
from graphviz import Digraph
from pandas import read_table
from math import log
from collections import defaultdict
dot = Digraph(comment='TREE')
def H(*values):
values = np.asarray(values) * 1.0
values = values / sum(values)
return sum((-value * log(value, 2) for value in values if value > 0.0))
def calc_pn(p, n, P, N):
return (
H(P, N),
H(p, n),
H(P - p, N - n),
H(P, N) - (p + n) * 1.0 / (P + N) * H(p, n) - (P + N - p - n) * 1.0 / (P + N) * H(P - p, N - n),
)
def read_csv():
return read_table(open('./train.csv', 'r'), header=0, sep=r",\s*", index_col=False)
class Tree:
def __init__(self):
self.data = {}
self.childs = {}
self.class_ = ''
def __str__(self):
return ' '.join([
str(self.data['Name']),
'id =', str(id(self)),
'\n samples', str(self.data['Pos']) + ":" + str(self.data['Neg']),
'\n' + self.class_
])
def is_list(self):
return len(self.childs) == 0
def is_restudy(self, c):
return self.data['Pos'] < c and self.data['Neg'] < c
def maj_class(self):
return '>50K' if self.data['Pos'] > self.data['Neg'] else '<=50K'
def build_tree(df):
tree = Tree()
return build_tree_recursive(df, tree)
def build_tree_recursive(df, node):
val = dict(df.groupby(['Class'])['Class'].count())
P = val['>50K'] if '>50K' in val else 0
N = val['<=50K'] if '<=50K' in val else 0
gain = {}
max_column = df.columns.values[0]
for column in df.columns.values[:-1]:
features = defaultdict(lambda: 0)
features.update(dict(df.groupby([column, 'Class'])['Class'].count()))
val = set([x[0] for x in features.keys()])
sub_gain = []
for x in val:
sub_gain.append(calc_pn(features[(x, '>50K')], features[(x, '<=50K')], P, N)[3])
gain[column] = max(sub_gain)
max_column = column if gain[column] > gain[max_column] else max_column
for x in dict(df.groupby(max_column)[max_column].count()).keys():
query_string = max_column + " == " + str(x) if df.dtypes[max_column] == "int64" or df.dtypes[max_column] == "int32" else max_column + " == '" + str(x) + "'"
if len(df.query(query_string).columns.values) == 1 or x == "?": continue
node.childs[x] = Tree()
query_to_go = df.query(query_string)
value = dict(query_to_go.groupby(['Class'])['Class'].count())
p = value['>50K'] if '>50K' in value else 0
n = value['<=50K'] if '<=50K' in value else 0
if calc_pn(p, n, P, N)[2] == 1.0 or p == 0 or n == 0 or len(df.query(query_string).columns.values) == 2:
node.childs[x].data['Name'] = x
node.childs[x].data['Pos'] = p
node.childs[x].data['Neg'] = n
node.childs[x].class_ = '<=50K' if n > p else '>50K'
continue
del query_to_go[max_column]
build_tree_recursive(query_to_go, node.childs[x])
node.data['Name'] = max_column
node.data['Pos'] = P
node.data['Neg'] = N
return node
def tree_pruning_rare(parent, node, c):
if node.data['Pos'] < c and node.data['Neg'] < c:
node.childs = {}
node.class_ = parent.maj_class()
node.data['Name'] += ' restudy'
for x in node.childs:
tree_pruning_rare(node, node.childs[x], c)
def tree_pruning_rep(node, c):
def ordinal_child(node, cl):
yes = node.class_ == cl if node.is_list() else True
for child in node.childs:
yes &= node.childs[child].class_ == cl if node.childs[child].is_list() else ordinal_child(node.childs[child], cl)
return yes
for x in node.childs:
class1_dominate = ordinal_child(node.childs[x], '>50K')
class2_dominate = ordinal_child(node.childs[x], '<=50K')
if class1_dominate or class2_dominate:
node.childs[x].childs = {}
node.childs[x].class_ = node.maj_class() if node.childs[x].is_restudy(c) else node.childs[x].maj_class()
tree_pruning_rep(node.childs[x], c)
def tree_pruning(tree, sample=7):
tree_pruning_rare(tree, tree, sample)
tree_pruning_rep(tree, sample)
def print_tree(tree):
print_tree_recursive(tree)
def print_tree_recursive(node):
dot.node(str(node), str(node))
for x in node.childs:
dot_str = str(node.childs[x])
dot.node(dot_str, dot_str)
dot.edge(str(node), dot_str, label=str(x))
print_tree_recursive(node.childs[x])
return
def main():
tree = build_tree(read_csv())
tree_pruning(tree)
print_tree(tree)
dot.render('tree.gv', view=True)
if __name__ == "__main__": main()