forked from memoiry/LightML.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decisionTree.jl
402 lines (331 loc) · 10.8 KB
/
decisionTree.jl
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
abstract LossFunction
type LogisticLoss <: LossFunction
obj::Function
gradient::Function
hessian::Function
function obj(y::Array, y_pred::Array)
logistic_pred = sigmoid(y_pred)
l = - y .* log(logistic_pred)
r = - (1-y) .* log(1-logistic_pred)
loss = 1/size(y,1) * (l + r)
return loss
end
function gradient(y::Array, y_pred::Array)
return (sigmoid(y_pred) - y)
end
function hessian(y::Array, y_pred::Array)
logitsc_pred = sigmoid(y_pred)
val = logitsc_pred .* ( 1 - logitsc_pred)
return val
end
function LogisticLoss()
loss = new(obj, gradient, hessian)
return loss
end
end
type SquareLoss <: LossFunction
obj::Function
gradient::Function
hessian::Function
function obj(y::Array, y_pred::Array)
return 0.5 * sumabs2(y - y_pred)
end
function gradient(y::Array, y_pred::Array)
return (y_pred - y)
end
function hessian(y::Array, y_pred::Array)
n_sample = size(y,1)
return ones(n_sample)
end
function SquareLoss()
loss = new(obj, gradient, hessian)
return loss
end
end
type DecisionNode
label::Union{Array, Int64, String, Float64}
feature_index::Integer
threshold::Features
true_branch::Union{DecisionNode,String}
false_branch::Union{DecisionNode, String}
y_num::Int64
end
function DecisionNode(;
label = "nothing",
feature_index = 0,
threshold = Inf,
true_branch = "nothing",
false_branch = "nothing",
y_num = 1)
return DecisionNode(label, feature_index, threshold,true_branch, false_branch, y_num)
end
abstract DecisionTree
type RegressionTree <: DecisionTree
root::Union{DecisionNode,String}
max_depth::Integer
min_gain::Float64
min_samples_split::Integer
current_depth::Integer
y_num::Integer
end
type ClassificationTree <: DecisionTree
root::Union{DecisionNode,String}
max_depth::Integer
min_gain::Float64
min_samples_split::Integer
current_depth::Integer
y_num::Integer
end
type XGBoostRegressionTree <: DecisionTree
root::Union{DecisionNode,String}
max_depth::Int64
min_gain::Float64
min_samples_split::Int64
current_depth::Int64
loss::LogisticLoss
y_num::Integer
end
function XGBoostRegressionTree(;
root = "nothing",
min_samples_split = 2,
min_gain = 1e-7,
max_depth = 1e7,
current_depth::Int64 = 0,
loss::LogisticLoss = LogisticLoss(),
y_num = 1)
return XGBoostRegressionTree(root, max_depth, min_gain,
min_samples_split, current_depth, loss, y_num)
end
function ClassificationTree(;
root = "nothing",
min_samples_split = 2,
min_gain = 1e-7,
max_depth = 1e7,
current_depth = 0,
y_num = 1)
return ClassificationTree(root, max_depth, min_gain,
min_samples_split, current_depth, y_num)
end
function RegressionTree(;
root = "nothing",
min_samples_split = 2,
min_gain = 1e-7,
max_depth = 1e7,
current_depth = 0,
y_num = 1)
return RegressionTree(root, max_depth, min_gain,
min_samples_split, current_depth, y_num)
end
function train!(model::DecisionTree, X::Matrix, y::Array)
model.current_depth = 0
#Normalize
#X_y = [X y]
#X_y = normalize_(X_y)
#X = X_y[:, 1:(end-1)]
#y = X_y[:, end]
model.root = build_tree(model, X, y)
end
function build_tree(model::DecisionTree, X::Matrix, y::Array)
if typeof(model) <: XGBoostRegressionTree
model.y_num = trunc(Int,size(y,2)/2)
else
model.y_num = size(y,2)
end
entropy = calc_entropy(y)
largest_impurity = 0
best_criteria = 0
best_sets = 0
n_features = size(X, 2)
X_y = hcat(X, y)
n_samples = size(X_y,1)
if n_samples >= model.min_samples_split
for i = 1:n_features
feature_values = X_y[:, i]
unique_values = unique(feature_values)
#For large regression problem
if typeof(model) == XGBoostRegressionTree
num = 8
if length(unique_values) >= num
num_ = length(unique_values)
indd = randperm(num_)[1:num]
unique_values = unique_values[indd]
end
end
for threshold in unique_values
Xy_1, Xy_2 = split_at_feature(X_y, i, threshold)
if size(Xy_1,1) > 0 && size(Xy_2,1) > 0
y1 = Xy_1[:, (n_features+1):end]
y2 = Xy_2[:, (n_features+1):end]
impurity = impurity_calc(model, y, y1, y2)
if impurity > largest_impurity
#println("$(impurity)")
largest_impurity = impurity
best_criteria = Dict("feature_i" => i, "threshold" => threshold)
best_sets = Dict("left_branch" => Xy_1, "right_branch" => Xy_2)
end
end
end
end
end
if model.current_depth < model.max_depth && largest_impurity > model.min_gain
leftX, leftY = best_sets["left_branch"][:, 1:n_features], best_sets["left_branch"][:, (n_features+1):end]
rightX, rightY = best_sets["right_branch"][:, 1:n_features], best_sets["right_branch"][:, (n_features+1):end]
true_branch = build_tree(model, leftX, leftY)
false_branch = build_tree(model, rightX, rightY)
model.current_depth += 1
return DecisionNode(feature_index = best_criteria["feature_i"],
threshold = best_criteria["threshold"], true_branch = true_branch,
false_branch = false_branch)
end
## if not constructed
leaf_value = leaf_value_calc(model, y)
return DecisionNode(label = leaf_value)
end
function leaf_value_calc(model::XGBoostRegressionTree, y::Array)
y, y_pred = split_(y)
nominator = sum(model.loss.gradient(y, y_pred),1)
denominator = sum(model.loss.hessian(y, y_pred),1)
return nominator ./ denominator
end
function leaf_value_calc(model::RegressionTree, y::Array)
return mean(y)
end
function leaf_value_calc(model::ClassificationTree, y::Array)
labels = size(y,2)
if labels > 1
y = unhot(y)
end
feature = unique(y)
most_common = nothing
count_max = 0
for i in feature
count = sum(y .== i)
if count > count_max
count_max = count
most_common = i
end
end
if labels > 1
most_common = trunc(Int64, most_common[1])
most_common = eye(labels)[most_common,:]
end
return most_common
end
function split_(y)
col = trunc(Int,size(y,2)/2)
return y[:,1:col],y[:,(col+1):end]
end
function _gain_(model::XGBoostRegressionTree, y, y_pred)
grad = sum(model.loss.gradient(y, y_pred))
nominator = grad .* grad
denominator = sum(model.loss.hessian(y, y_pred))
return 0.5 * nominator / denominator
end
function impurity_calc(model::XGBoostRegressionTree, y, y1, y2)
y, y_pred = split_(y)
y1, y1_pred = split_(y1)
y2, y2_pred = split_(y2)
true_gain = _gain_(model, y1,y1_pred)
false_gain = _gain_(model, y2,y2_pred)
gain = _gain_(model, y, y_pred)
return true_gain + false_gain - gain
end
function impurity_calc(model::RegressionTree, y, y1, y2)
var_total = var(y)
var_y1 = var(y1)
var_y2 = var(y2)
frac_1 = length(y1) / length(y)
frac_2 = length(y2) / length(y)
variance_reduction = var_total - (frac_1 * var_y1 + frac_2 * var_y2)
return variance_reduction
end
function impurity_calc(model::ClassificationTree, y, y1, y2)
p = size(y1,1)/size(y,1)
entro = calc_entropy(y)
#println("entro: $(entro), p: $(p), res: $(entro - (p * calc_entropy(y1) + (1-p) * calc_entropy(y2)))")
return entro - (p * calc_entropy(y1) + (1-p) * calc_entropy(y2))
end
function predict(model::DecisionTree,
x::Matrix)
n = size(x,1)
res = zeros(n)
if model.y_num == 1
for i = 1:n
res[i] = predict(model.root, x[i,:])
end
else
res = zeros(n, model.y_num)
for i = 1:n
res[i,:] = predict(model.root, x[i,:])
end
end
return res
end
function predict(model::DecisionNode,
x::Vector)
if model.label != "nothing"
return model.label
end
feature_current = x[model.feature_index]
if typeof(feature_current) <:String
if feature_current == model.threshold
return predict(model.true_branch, x)
else
return predict(model.false_branch, x)
end
elseif typeof(feature_current) <: Real
if feature_current <= model.threshold
return predict(model.true_branch, x)
else
return predict(model.false_branch, x)
end
end
end
function print_tree(model::DecisionTree)
if model.lable != "nothing"
println($(model.label))
else
println("$(model.feature_index):$(model.threshold)?")
println(" T->")
print_tree(model.true_branch)
println(" F->")
print_tree(model.true_branch)
end
end
function split_at_feature(X, feature_i, threshold)
if typeof(threshold) <: Real
ind1 = find(X[:,feature_i] .<= threshold)
ind2 = find(X[:,feature_i] .> threshold)
elseif typeof(threshhold) <: String
ind1 = find(X[:,feature_i] .== threshold)
ind2 = find(X[:,feature_i] .!= threshold)
end
X_1 = X[ind1,:]
X_2 = X[ind2,:]
return X_1, X_2
end
function test_ClassificationTree()
X_train, X_test, y_train, y_test = make_iris()
y_train = one_hot(y_train)
y_test = one_hot(y_test)
model = ClassificationTree()
train!(model,X_train, y_train)
predictions = predict(model,X_test)
y_test = unhot(y_test)
predictions = unhot(predictions)
print("classification accuracy", accuracy(y_test, predictions))
#PCA
#pca_model = PCA()
#train!(pca_model, X_test)
#plot_in_2d(pca_model, X_test, predictions, "ClassificationTree")
end
function test_RegressionTree()
X_train, X_test, y_train, y_test = make_reg(n_features = 1)
model = RegressionTree()
train!(model,X_train, y_train)
predictions = predict(model,X_test)
print("regression msea", mean_squared_error(y_test, predictions))
PyPlot.scatter(X_test, y_test, color = "black")
PyPlot.scatter(X_test, predictions, color = "green")
legend(loc="upper right",fancybox="true")
end