-
Notifications
You must be signed in to change notification settings - Fork 30
/
dtree.py
executable file
·1956 lines (1701 loc) · 67 KB
/
dtree.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
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
2012.1.24 CKS
Algorithms for building and using a decision tree for classification or regression.
"""
from __future__ import print_function
from collections import defaultdict
from decimal import Decimal
from pprint import pprint
import copy
import csv
import math
from math import pi
import os
import random
import re
import unittest
import pickle
VERSION = (2, 0, 0)
__version__ = '.'.join(map(str, VERSION))
# Traditional entropy.
ENTROPY1 = 'entropy1'
# Modified entropy that penalizes universally unique values.
ENTROPY2 = 'entropy2'
# Modified entropy that penalizes universally unique values
# as well as features with large numbers of values.
ENTROPY3 = 'entropy3'
DISCRETE_METRICS = [
ENTROPY1,
ENTROPY2,
ENTROPY3,
]
# Simple statistical variance, the measure of how far a set of numbers
# is spread out.
VARIANCE1 = 'variance1'
# Like ENTROPY2, is the variance weighted to penalize attributes with
# universally unique values.
VARIANCE2 = 'variance2'
CONTINUOUS_METRICS = [
VARIANCE1,
VARIANCE2,
]
DEFAULT_DISCRETE_METRIC = ENTROPY1
DEFAULT_CONTINUOUS_METRIC = VARIANCE1
# Methods for aggregating the predictions of trees in a forest.
EQUAL_MEAN = 'equal-mean'
WEIGHTED_MEAN = 'weighted-mean'
BEST = 'best'
AGGREGATION_METHODS = [
EQUAL_MEAN,
WEIGHTED_MEAN,
BEST,
]
# Forest growth algorithms.
GROW_RANDOM = 'random'
GROW_AUTO_MINI_BATCH = 'auto-mini-batch'
GROW_AUTO_INCREMENTAL = 'auto-incremental'
GROW_METHODS = [
GROW_RANDOM,
GROW_AUTO_MINI_BATCH,
GROW_AUTO_INCREMENTAL,
]
# Data format names.
ATTR_TYPE_NOMINAL = NOM = 'nominal'
ATTR_TYPE_DISCRETE = DIS = 'discrete'
ATTR_TYPE_CONTINUOUS = CON = 'continuous'
ATTR_MODE_CLASS = CLS = 'class'
ATTR_HEADER_PATTERN = re.compile("([^,:]+):(nominal|discrete|continuous)(?::(class))?")
def get_mean(seq):
"""
Batch mean calculation.
"""
return sum(seq)/float(len(seq))
def get_variance(seq):
"""
Batch variance calculation.
"""
m = get_mean(seq)
return sum((v-m)**2 for v in seq)/float(len(seq))
def standard_deviation(seq):
return math.sqrt(get_variance(seq))
def mean_absolute_error(seq, correct):
"""
Batch mean absolute error calculation.
"""
assert len(seq) == len(correct)
diffs = [abs(a-b) for a, b in zip(seq, correct)]
return sum(diffs)/float(len(diffs))
def normalize(seq):
"""
Scales each number in the sequence so that the sum of all numbers equals 1.
"""
s = float(sum(seq))
return [v/s for v in seq]
def erfcc(x):
"""
Complementary error function.
"""
z = abs(x)
t = 1. / (1. + 0.5*z)
r = t * math.exp(-z*z-1.26551223+t*(1.00002368+t*(.37409196+
t*(.09678418+t*(-.18628806+t*(.27886807+
t*(-1.13520398+t*(1.48851587+t*(-.82215223+
t*.17087277)))))))))
if (x >= 0.):
return r
else:
return 2. - r
def normcdf(x, mu, sigma):
"""
Describes the probability that a real-valued random variable X with a given
probability distribution will be found at a value less than or equal to X
in a normal distribution.
http://en.wikipedia.org/wiki/Cumulative_distribution_function
"""
t = x-mu
y = 0.5*erfcc(-t/(sigma*math.sqrt(2.0)))
if y > 1.0:
y = 1.0
return y
def normpdf(x, mu, sigma):
"""
Describes the relative likelihood that a real-valued random variable X will
take on a given value.
http://en.wikipedia.org/wiki/Probability_density_function
"""
u = (x-mu)/abs(sigma)
y = (1/(math.sqrt(2*pi)*abs(sigma)))*math.exp(-u*u/2)
return y
def normdist(x, mu, sigma, f=True):
if f:
y = normcdf(x, mu, sigma)
else:
y = normpdf(x, mu, sigma)
return y
def normrange(x1, x2, mu, sigma, f=True):
p1 = normdist(x1, mu, sigma, f)
p2 = normdist(x2, mu, sigma, f)
return abs(p1-p2)
def cmp(a, b): # pylint: disable=redefined-builtin
return (a > b) - (a < b)
class DDist:
"""
Incrementally tracks the probability distribution of discrete elements.
"""
def __init__(self, seq=None):
self.clear()
if seq:
for k in seq:
self.counts[k] += 1
self.total += 1
def __cmp__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return cmp(
(frozenset(self.counts.items()), self.total),
(frozenset(other.counts.items()), other.total)
)
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return (frozenset(self.counts.items()), self.total) == \
(frozenset(other.counts.items()), other.total)
def __getitem__(self, k):
"""
Returns the probability for the given element.
"""
cnt = 0
if k in self.counts:
cnt = self.counts[k]
return cnt/float(self.total)
def __hash__(self):
return hash((frozenset(self.counts.items()), self.total))
def __repr__(self):
s = []
for k, prob in self.probs:
s.append("%s=%s" % (k, prob))
return "<%s %s>" % (type(self).__name__, ', '.join(s))
def add(self, k, count=1):
"""
Increments the count for the given element.
"""
self.counts[k] += count
self.total += count
@property
def best(self):
"""
Returns the element with the highest probability.
"""
b = (-1e999999, None)
for k, c in self.counts.items():
b = max(b, (c, k))
return b[1]
@property
def best_prob(self):
probs = self.probs
if not probs:
return
best = -1e999999
for _, prob in probs:
best = max(best, prob)
return best
def clear(self):
self.counts = defaultdict(int)
self.total = 0
def copy(self):
return copy.deepcopy(self)
@property
def count(self):
"""
The total number of samples forming this distribution.
"""
return self.total
def keys(self):
return self.counts.keys()
@property
def probs(self):
"""
Returns a list of probabilities for all elements in the form
[(value1,prob1),(value2,prob2),...].
"""
return [
(k, self.counts[k]/float(self.total))
for k in self.counts.keys()
]
def update(self, dist):
"""
Adds the given distribution's counts to the current distribution.
"""
assert isinstance(dist, DDist)
for k, c in dist.counts.items():
self.counts[k] += c
self.total += dist.total
class CDist:
"""
Incrementally tracks the probability distribution of continuous numbers.
"""
def __init__(self, seq=None, mean=None, var=None, stdev=None):
self.clear()
if mean is not None:
self.mean_sum = mean
self.mean_count = 1
if var is not None:
self.last_variance = var
self.mean_count = 1
if stdev is not None:
self.last_variance = stdev**2
self.mean_count = 1
if seq:
for n in seq:
self += n
def clear(self):
self.mean_sum = 0
self.mean_count = 0
self.last_variance = 0
def copy(self):
return copy.deepcopy(self)
def __repr__(self):
return "<%s mean=%s variance=%s>" % (type(self).__name__, self.mean, self.variance)
def __iadd__(self, value):
last_mean = self.mean
self.mean_sum += value
self.mean_count += 1
if last_mean is not None:
self.last_variance = self.last_variance \
+ (value - last_mean)*(value - self.mean)
return self
@property
def count(self):
"""
The total number of samples forming this distribution.
"""
return self.mean_count
@property
def mean(self):
if self.mean_count:
return self.mean_sum/float(self.mean_count)
@property
def variance(self):
if self.mean_count:
return self.last_variance/float(self.mean_count)
@property
def standard_deviation(self):
var = self.variance
if var is None:
return
return math.sqrt(var)
def probability_lt(self, x):
"""
Returns the probability of a random variable being less than the
given value.
"""
if self.mean is None:
return
return normdist(x=x, mu=self.mean, sigma=self.standard_deviation)
def probability_in(self, a, b):
"""
Returns the probability of a random variable falling between the given
values.
"""
if self.mean is None:
return
p1 = normdist(x=a, mu=self.mean, sigma=self.standard_deviation)
p2 = normdist(x=b, mu=self.mean, sigma=self.standard_deviation)
return abs(p1 - p2)
def probability_gt(self, x):
"""
Returns the probability of a random variable being greater than the
given value.
"""
if self.mean is None:
return
p = normdist(x=x, mu=self.mean, sigma=self.standard_deviation)
return 1-p
def entropy(data, class_attr=None, method=DEFAULT_DISCRETE_METRIC):
"""
Calculates the entropy of the attribute attr in given data set data.
Parameters:
data<dict|list> :=
if dict, treated as value counts of the given attribute name
if list, treated as a raw list from which the value counts will be generated
attr<string> := the name of the class attribute
"""
assert (class_attr is None and isinstance(data, dict)) or (class_attr is not None and isinstance(data, list))
if isinstance(data, dict):
counts = data
else:
counts = defaultdict(float) # {attr:count}
for record in data:
# Note: A missing attribute is treated like an attribute with a value
# of None, representing the attribute is "irrelevant".
counts[record.get(class_attr)] += 1.0
len_data = float(sum(cnt for _, cnt in counts.items()))
n = max(2, len(counts))
total = float(sum(counts.values()))
assert total, "There must be at least one non-zero count."
if method == ENTROPY1:
return -sum((count/len_data)*math.log(count/len_data, n)
for count in counts.values() if count)
elif method == ENTROPY2:
return -sum((count/len_data)*math.log(count/len_data, n)
for count in counts.values() if count) - ((len(counts)-1)/float(total))
elif method == ENTROPY3:
return -sum((count/len_data)*math.log(count/len_data, n)
for count in counts.values() if count) - 100*((len(counts)-1)/float(total))
else:
raise Exception("Unknown entropy method %s." % method)
def entropy_variance(data, class_attr=None,
method=DEFAULT_CONTINUOUS_METRIC):
"""
Calculates the variance fo a continuous class attribute, to be used as an
entropy metric.
"""
assert method in CONTINUOUS_METRICS, "Unknown entropy variance metric: %s" % (method,)
assert (class_attr is None and isinstance(data, dict)) or (class_attr is not None and isinstance(data, list))
if isinstance(data, dict):
lst = data
else:
lst = [record.get(class_attr) for record in data]
return get_variance(lst)
def get_gain(data, attr, class_attr,
method=DEFAULT_DISCRETE_METRIC,
only_sub=0, prefer_fewer_values=False, entropy_func=None):
"""
Calculates the information gain (reduction in entropy) that would
result by splitting the data on the chosen attribute (attr).
Parameters:
prefer_fewer_values := Weights the gain by the count of the attribute's
unique values. If multiple attributes have the same gain, but one has
slightly fewer attributes, this will cause the one with fewer
attributes to be preferred.
"""
entropy_func = entropy_func or entropy
val_freq = defaultdict(float)
subset_entropy = 0.0
# Calculate the frequency of each of the values in the target attribute
for record in data:
val_freq[record.get(attr)] += 1.0
# Calculate the sum of the entropy for each subset of records weighted
# by their probability of occuring in the training set.
for val in val_freq.keys():
val_prob = val_freq[val] / sum(val_freq.values())
data_subset = [record for record in data if record.get(attr) == val]
e = entropy_func(data_subset, class_attr, method=method)
subset_entropy += val_prob * e
if only_sub:
return subset_entropy
# Subtract the entropy of the chosen attribute from the entropy of the
# whole data set with respect to the target attribute (and return it)
main_entropy = entropy_func(data, class_attr, method=method)
# Prefer gains on attributes with fewer values.
if prefer_fewer_values:
return ((main_entropy - subset_entropy), 1./len(val_freq))
else:
return (main_entropy - subset_entropy)
def gain_variance(*args, **kwargs):
"""
Calculates information gain using variance as the comparison metric.
"""
return get_gain(entropy_func=entropy_variance, *args, **kwargs)
def majority_value(data, class_attr):
"""
Creates a list of all values in the target attribute for each record
in the data list object, and returns the value that appears in this list
the most frequently.
"""
if is_continuous(data[0][class_attr]):
return CDist(seq=[record[class_attr] for record in data])
else:
return most_frequent([record[class_attr] for record in data])
def most_frequent(lst):
"""
Returns the item that appears most frequently in the given list.
"""
lst = lst[:]
highest_freq = 0
most_freq = None
for val in unique(lst):
if lst.count(val) > highest_freq:
most_freq = val
highest_freq = lst.count(val)
return most_freq
def unique(lst):
"""
Returns a list made up of the unique values found in lst. i.e., it
removes the redundant values in lst.
"""
lst = lst[:]
unique_lst = []
# Cycle through the list and add each value to the unique list only once.
for item in lst:
if unique_lst.count(item) <= 0:
unique_lst.append(item)
# Return the list with all redundant values removed.
return unique_lst
def get_values(data, attr):
"""
Creates a list of values in the chosen attribut for each record in data,
prunes out all of the redundant values, and return the list.
"""
return unique([record[attr] for record in data])
def choose_attribute(data, attributes, class_attr, fitness, method):
"""
Cycles through all the attributes and returns the attribute with the
highest information gain (or lowest entropy).
"""
best = (-1e999999, None)
for attr in attributes:
if attr == class_attr:
continue
gain = fitness(data, attr, class_attr, method=method)
best = max(best, (gain, attr))
return best[1]
def is_continuous(v):
return isinstance(v, (float, Decimal))
def create_decision_tree(data, attributes, class_attr, fitness_func, wrapper, **kwargs):
"""
Returns a new decision tree based on the examples given.
"""
split_attr = kwargs.get('split_attr', None)
split_val = kwargs.get('split_val', None)
assert class_attr not in attributes
node = None
data = list(data) if isinstance(data, Data) else data
if wrapper.is_continuous_class:
stop_value = CDist(seq=[r[class_attr] for r in data])
# For a continuous class case, stop if all the remaining records have
# a variance below the given threshold.
stop = wrapper.leaf_threshold is not None \
and stop_value.variance <= wrapper.leaf_threshold
else:
stop_value = DDist(seq=[r[class_attr] for r in data])
# For a discrete class, stop if all remaining records have the same
# classification.
stop = len(stop_value.counts) <= 1
if not data or len(attributes) <= 0:
# If the dataset is empty or the attributes list is empty, return the
# default value. The target attribute is not in the attributes list, so
# we need not subtract 1 to account for the target attribute.
if wrapper:
wrapper.leaf_count += 1
return stop_value
elif stop:
# If all the records in the dataset have the same classification,
# return that classification.
if wrapper:
wrapper.leaf_count += 1
return stop_value
else:
# Choose the next best attribute to best classify our data
best = choose_attribute(
data,
attributes,
class_attr,
fitness_func,
method=wrapper.metric)
# Create a new decision tree/node with the best attribute and an empty
# dictionary object--we'll fill that up next.
node = Node(tree=wrapper, attr_name=best)
node.n += len(data)
# Create a new decision tree/sub-node for each of the values in the
# best attribute field
for val in get_values(data, best):
# Create a subtree for the current value under the "best" field
subtree = create_decision_tree(
[r for r in data if r[best] == val],
[attr for attr in attributes if attr != best],
class_attr,
fitness_func,
split_attr=best,
split_val=val,
wrapper=wrapper)
# Add the new subtree to the empty dictionary object in our new
# tree/node we just created.
if isinstance(subtree, Node):
node._branches[val] = subtree
elif isinstance(subtree, (CDist, DDist)):
node.set_leaf_dist(attr_value=val, dist=subtree)
else:
raise Exception("Unknown subtree type: %s" % (type(subtree),))
return node
class Data:
"""
Parses, validates and iterates over tabular data in a file
or an generic iterator.
This does not store the actual data rows. It only stores the row schema.
"""
def __init__(self, inp, order=None, types=None, modes=None):
self.header_types = types or {} # {attr_name:type}
self.header_modes = modes or {} # {attr_name:mode}
if isinstance(order, str):
order = order.split(',')
self.header_order = order or [] # [attr_name,...]
# Validate header type.
if isinstance(self.header_types, (tuple, list)):
assert self.header_order, 'If header type names were not given, an explicit order must be specified.'
assert len(self.header_types) == len(self.header_order), 'Header order length must match header type length.'
self.header_types = dict(zip(self.header_order, self.header_types))
self.filename = None
self.data = None
if isinstance(inp, str):
filename = inp
assert os.path.isfile(filename), "File \"%s\" does not exist." % filename
self.filename = filename
else:
assert self.header_types, "No attribute types specified."
assert self.header_modes, "No attribute modes specified."
self.data = inp
self._class_attr_name = None
if self.header_modes:
for k, v in self.header_modes.items():
if v != CLS:
continue
self._class_attr_name = k
break
assert self._class_attr_name, "No class attribute specified."
def copy_no_data(self):
"""
Returns a copy of the object without any data.
"""
return type(self)(
[],
order=list(self.header_modes),
types=self.header_types.copy(),
modes=self.header_modes.copy())
def __len__(self):
if self.filename:
return max(0, open(self.filename).read().strip().count('\n'))
elif hasattr(self.data, '__len__'):
return len(self.data)
def __bool__(self):
return bool(len(self))
__nonzero__ = __bool__
@property
def class_attribute_name(self):
return self._class_attr_name
@property
def attribute_names(self):
self._read_header()
return [
n for n in self.header_types.keys()
if n != self._class_attr_name
]
def get_attribute_type(self, name):
if not self.header_types:
self._read_header()
return self.header_types[name]
@property
def is_continuous_class(self):
self._read_header()
return self.get_attribute_type(self._class_attr_name) == ATTR_TYPE_CONTINUOUS
def is_valid(self, name, value):
"""
Returns true if the given value matches the type for the given name
according to the schema.
Returns false otherwise.
"""
if name not in self.header_types:
return False
t = self.header_types[name]
if t == ATTR_TYPE_DISCRETE:
return isinstance(value, int)
elif t == ATTR_TYPE_CONTINUOUS:
return isinstance(value, (float, Decimal))
return True
def _read_header(self):
"""
When a CSV file is given, extracts header information the file.
Otherwise, this header data must be explicitly given when the object
is instantiated.
"""
if not self.filename or self.header_types:
return
rows = csv.reader(open(self.filename))
header = next(rows)
self.header_types = {} # {attr_name:type}
self._class_attr_name = None
self.header_order = [] # [attr_name,...]
for el in header:
matches = ATTR_HEADER_PATTERN.findall(el)
assert matches, "Invalid header element: %s" % (el,)
el_name, el_type, el_mode = matches[0]
el_name = el_name.strip()
self.header_order.append(el_name)
self.header_types[el_name] = el_type
if el_mode == ATTR_MODE_CLASS:
assert self._class_attr_name is None, "Multiple class attributes are not supported."
self._class_attr_name = el_name
else:
assert self.header_types[el_name] != ATTR_TYPE_CONTINUOUS, "Non-class continuous attributes are not supported."
assert self._class_attr_name, "A class attribute must be specified."
def validate_row(self, row):
"""
Ensure each element in the row matches the schema.
"""
clean_row = {}
if isinstance(row, (tuple, list)):
assert self.header_order, "No attribute order specified."
assert len(row) == len(self.header_order), "Row length does not match header length."
itr = zip(self.header_order, row)
else:
assert isinstance(row, dict)
itr = row.items()
for el_name, el_value in itr:
if self.header_types[el_name] == ATTR_TYPE_DISCRETE:
clean_row[el_name] = int(el_value)
elif self.header_types[el_name] == ATTR_TYPE_CONTINUOUS:
clean_row[el_name] = float(el_value)
else:
clean_row[el_name] = el_value
return clean_row
def _get_iterator(self):
if self.filename:
self._read_header()
itr = csv.reader(open(self.filename))
next(itr) # Skip header.
return itr
return self.data
def __iter__(self):
for row in self._get_iterator():
if not row:
continue
yield self.validate_row(row)
def split(self, ratio=0.5, leave_one_out=False):
"""
Returns two Data instances, containing the data randomly split between
the two according to the given ratio.
The first instance will contain the ratio of data specified.
The second instance will contain the remaining ratio of data.
If leave_one_out is True, the ratio will be ignored and the first
instance will contain exactly one record for each class label, and
the second instance will contain all remaining data.
"""
a_labels = set()
a = self.copy_no_data()
b = self.copy_no_data()
for row in self:
if leave_one_out and not self.is_continuous_class:
label = row[self.class_attribute_name]
if label not in a_labels:
a_labels.add(label)
a.data.append(row)
else:
b.data.append(row)
elif not a:
a.data.append(row)
elif not b:
b.data.append(row)
elif random.random() <= ratio:
a.data.append(row)
else:
b.data.append(row)
return a, b
USE_NEAREST = 'use_nearest'
MISSING_VALUE_POLICIES = set([
USE_NEAREST,
])
def _get_dd_int():
return defaultdict(int)
def _get_dd_dd_int():
return defaultdict(_get_dd_int)
def _get_dd_cdist():
return defaultdict(CDist)
class NodeNotReadyToPredict(Exception):
pass
class Node:
"""
Represents a specific split or branch in the tree.
"""
def __init__(self, tree, attr_name=None):
# The number of samples this node has been trained on.
self.n = 0
# A reference to the container tree instance.
self._tree = tree
# The splitting attribute at this node.
self.attr_name = attr_name
#### Discrete values.
# Counts of each observed attribute value, used to calculate an
# attribute value's probability.
# {attr_name:{attr_value:count}}
self._attr_value_counts = defaultdict(_get_dd_int)
# {attr_name:total}
self._attr_value_count_totals = defaultdict(int)
# Counts of each observed class value and attribute value in
# combination, used to calculate an attribute value's entropy.
# {attr_name:{attr_value:{class_value:count}}}
self._attr_class_value_counts = defaultdict(_get_dd_dd_int)
#### Continuous values.
# Counts of each observed class value, used to calculate a class
# value's probability.
# {class_value:count}
self._class_ddist = DDist()
# {attr_name:{attr_value:CDist(variance)}}
self._attr_value_cdist = defaultdict(_get_dd_cdist)
self._class_cdist = CDist()
self._branches = {} # {v:Node}
def __getitem__(self, attr_name):
assert attr_name == self.attr_name
branches = self._branches.copy()
for value in self.get_values(attr_name):
if value in branches:
continue
if self.tree.data.is_continuous_class:
branches[value] = self._attr_value_cdist[self.attr_name][value].copy()
else:
branches[value] = self.get_value_ddist(self.attr_name, value)
return branches
def _get_attribute_value_for_node(self, record):
"""
Gets the closest value for the current node's attribute matching the
given record.
"""
# Abort if this node has not get split on an attribute.
if self.attr_name is None:
return
# Otherwise, lookup the attribute value for this node in the given record.
attr = self.attr_name
attr_value = record[attr]
attr_values = self.get_values(attr)
if attr_value in attr_values:
return attr_value
else:
# The value of the attribute in the given record does not directly
# map to any previously known values, so apply a missing value
# policy.
policy = self.tree.missing_value_policy.get(attr)
assert policy, "No missing value policy specified for attribute %s." % (attr,)
if policy == USE_NEAREST:
# Use the value that the tree has seen that's also has the
# smallest Euclidean distance to the actual value.
assert self.tree.data.header_types[attr] in (ATTR_TYPE_DISCRETE, ATTR_TYPE_CONTINUOUS), "The use-nearest policy is invalid for nominal types."
nearest = (1e999999, None)
for _value in attr_values:
nearest = min(nearest, (abs(_value - attr_value), _value))
_, nearest_value = nearest
return nearest_value
else:
raise Exception("Unknown missing value policy: %s" % (policy,))
@property
def attributes(self):
return self._attr_value_counts.keys()
def get_values(self, attr_name):
"""
Retrieves the unique set of values seen for the given attribute
at this node.
"""
ret = list(self._attr_value_cdist[attr_name].keys()) \
+ list(self._attr_value_counts[attr_name].keys()) \
+ list(self._branches.keys())
ret = set(ret)
return ret
@property
def is_continuous_class(self):
return self._tree.is_continuous_class
def get_best_splitting_attr(self):
"""
Returns the name of the attribute with the highest gain.
"""
best = (-1e999999, None)
for attr in self.attributes:
best = max(best, (self.get_gain(attr), attr))
best_gain, best_attr = best
return best_attr
def get_entropy(self, attr_name=None, attr_value=None):
"""
Calculates the entropy of a specific attribute/value combination.
"""
is_con = self.tree.data.is_continuous_class
if is_con:
if attr_name is None:
# Calculate variance of class attribute.
var = self._class_cdist.variance
else:
# Calculate variance of the given attribute.
var = self._attr_value_cdist[attr_name][attr_value].variance
if self.tree.metric == VARIANCE1 or attr_name is None:
return var
elif self.tree.metric == VARIANCE2:
unique_value_count = len(self._attr_value_counts[attr_name])
attr_total = float(self._attr_value_count_totals[attr_name])
return var*(unique_value_count/attr_total)
else:
if attr_name is None:
# The total number of times this attr/value pair has been seen.
total = float(self._class_ddist.total)
# The total number of times each class value has been seen for
# this attr/value pair.
counts = self._class_ddist.counts
# The total number of unique values seen for this attribute.
unique_value_count = len(self._class_ddist.counts)
# The total number of times this attribute has been seen.
attr_total = total
else:
total = float(self._attr_value_counts[attr_name][attr_value])
counts = self._attr_class_value_counts[attr_name][attr_value]
unique_value_count = len(self._attr_value_counts[attr_name])
attr_total = float(self._attr_value_count_totals[attr_name])
assert total, "There must be at least one non-zero count."
n = max(2, len(counts))
if self._tree.metric == ENTROPY1:
# Traditional entropy.
return -sum(
(count/total)*math.log(count/total, n)
for count in counts.values()
)
elif self._tree.metric == ENTROPY2:
# Modified entropy that down-weights universally unique values.
# e.g. If the number of unique attribute values equals the total
# count of the attribute, then it has the maximum amount of unique
# values.
return -sum(
(count/total)*math.log(count/total, n)
for count in counts.values()
) + (unique_value_count/attr_total)
elif self._tree.metric == ENTROPY3:
# Modified entropy that down-weights universally unique values
# as well as features with large numbers of values.
return -sum(
(count/total)*math.log(count/total, n)
for count in counts.values()
) + 100*(unique_value_count/attr_total)
def get_gain(self, attr_name):
"""
Calculates the information gain from splitting on the given attribute.
"""