|
| 1 | +from __future__ import division |
| 2 | +from collections import Counter, defaultdict |
| 3 | +from functools import partial |
| 4 | +import math, random |
| 5 | + |
| 6 | +def entropy(class_probabilities): |
| 7 | + """given a list of class probabilities, compute the entropy""" |
| 8 | + return sum(-p * math.log(p, 2) for p in class_probabilities if p) |
| 9 | + |
| 10 | +def class_probabilities(labels): |
| 11 | + total_count = len(labels) |
| 12 | + return [count / total_count |
| 13 | + for count in Counter(labels).values()] |
| 14 | + |
| 15 | +def data_entropy(labeled_data): |
| 16 | + return entropy(class_probabilities([label |
| 17 | + for _, label in labeled_data])) |
| 18 | + |
| 19 | +def partition_entropy(subsets): |
| 20 | + """find the entropy from this partition of data into subsets""" |
| 21 | + total_count = sum(len(subset) for subset in subsets) |
| 22 | + |
| 23 | + return sum( data_entropy(subset) * len(subset) / total_count |
| 24 | + for subset in subsets ) |
| 25 | + |
| 26 | +def group_by(items, key_fn): |
| 27 | + """returns a defaultdict(list), where each input item |
| 28 | + is in the list whose key is key_fn(item)""" |
| 29 | + groups = defaultdict(list) |
| 30 | + for item in items: |
| 31 | + key = key_fn(item) |
| 32 | + groups[key].append(item) |
| 33 | + return groups |
| 34 | + |
| 35 | +def partition_by(inputs, attribute): |
| 36 | + """returns a dict of inputs partitioned by the attribute |
| 37 | + each input is a pair (attribute_dict, label)""" |
| 38 | + return group_by(inputs, lambda x: x[0][attribute]) |
| 39 | + |
| 40 | +def partition_entropy_by(inputs,attribute): |
| 41 | + """computes the entropy corresponding to the given partition""" |
| 42 | + partitions = partition_by(inputs, attribute) |
| 43 | + return partition_entropy(partitions.values()) |
| 44 | + |
| 45 | +def classify(tree, input): |
| 46 | + """classify the input using the given decision tree""" |
| 47 | + |
| 48 | + # if this is a leaf node, return its value |
| 49 | + if tree in [True, False]: |
| 50 | + return tree |
| 51 | + |
| 52 | + # otherwise find the correct subtree |
| 53 | + attribute, subtree_dict = tree |
| 54 | + value = input[attribute] |
| 55 | + subtree = subtree_dict[value] |
| 56 | + |
| 57 | + # and use it to classify the input |
| 58 | + return classify(subtree, input) |
| 59 | + |
| 60 | +def build_tree_id3(inputs, split_candidates=None): |
| 61 | + |
| 62 | + # if this is our first pass, |
| 63 | + # all keys of the first input are split candidates |
| 64 | + if split_candidates is None: |
| 65 | + split_candidates = inputs[0][0].keys() |
| 66 | + |
| 67 | + # count Trues and Falses in the inputs |
| 68 | + num_inputs = len(inputs) |
| 69 | + num_trues = len([label for item, label in inputs if label]) |
| 70 | + num_falses = num_inputs - num_trues |
| 71 | + |
| 72 | + if num_trues == 0: # if only Falses are left |
| 73 | + return False # return a "False" leaf |
| 74 | + |
| 75 | + if num_falses == 0: # if only Trues are left |
| 76 | + return True # return a "True" leaf |
| 77 | + |
| 78 | + if not split_candidates: # if no split candidates left |
| 79 | + return num_trues >= num_falses # return the majority leaf |
| 80 | + |
| 81 | + # otherwise, split on the best attribute |
| 82 | + best_attribute = min(split_candidates, |
| 83 | + key=partial(partition_entropy_by, inputs)) |
| 84 | + |
| 85 | + partitions = partition_by(inputs, best_attribute) |
| 86 | + new_candidates = [a for a in split_candidates |
| 87 | + if a != best_attribute] |
| 88 | + |
| 89 | + # recursively build the subtrees |
| 90 | + subtrees = { attribute : build_tree_id3(subset, new_candidates) |
| 91 | + for attribute, subset in partitions.iteritems() } |
| 92 | + |
| 93 | + return (best_attribute, subtrees) |
| 94 | + |
| 95 | +def forest_classify(trees, input): |
| 96 | + votes = [classify(tree, input) for tree in trees] |
| 97 | + vote_counts = Counter(votes) |
| 98 | + return vote_counts.most_common(1)[0][0] |
| 99 | + |
| 100 | + |
| 101 | +if __name__ == "__main__": |
| 102 | + |
| 103 | + inputs = [ |
| 104 | + ({'level':'Senior','lang':'Java','tweets':'no','phd':'no'}, False), |
| 105 | + ({'level':'Senior','lang':'Java','tweets':'no','phd':'yes'}, False), |
| 106 | + ({'level':'Mid','lang':'Python','tweets':'no','phd':'no'}, True), |
| 107 | + ({'level':'Junior','lang':'Python','tweets':'no','phd':'no'}, True), |
| 108 | + ({'level':'Junior','lang':'R','tweets':'yes','phd':'no'}, True), |
| 109 | + ({'level':'Junior','lang':'R','tweets':'yes','phd':'yes'}, False), |
| 110 | + ({'level':'Mid','lang':'R','tweets':'yes','phd':'yes'}, True), |
| 111 | + ({'level':'Senior','lang':'Python','tweets':'no','phd':'no'}, False), |
| 112 | + ({'level':'Senior','lang':'R','tweets':'yes','phd':'no'}, True), |
| 113 | + ({'level':'Junior','lang':'Python','tweets':'yes','phd':'no'}, True), |
| 114 | + ({'level':'Senior','lang':'Python','tweets':'yes','phd':'yes'},True), |
| 115 | + ({'level':'Mid','lang':'Python','tweets':'no','phd':'yes'}, True), |
| 116 | + ({'level':'Mid','lang':'Java','tweets':'yes','phd':'no'}, True), |
| 117 | + ({'level':'Junior','lang':'Python','tweets':'no','phd':'yes'},False) |
| 118 | + ] |
| 119 | + |
| 120 | + for key in ['level','lang','tweets','phd']: |
| 121 | + print key, partition_entropy_by(inputs, key) |
| 122 | + print |
| 123 | + |
| 124 | + senior_inputs = [(input, label) |
| 125 | + for input, label in inputs if input["level"] == "Senior"] |
| 126 | + |
| 127 | + for key in ['lang', 'tweets', 'phd']: |
| 128 | + print key, partition_entropy_by(senior_inputs, key) |
| 129 | + print |
| 130 | + |
| 131 | + print "building the tree" |
| 132 | + tree = build_tree_id3(inputs) |
| 133 | + print tree |
| 134 | + |
| 135 | + print "Junior / Java / tweets / no phd", classify(tree, |
| 136 | + { "level" : "Junior", |
| 137 | + "lang" : "Java", |
| 138 | + "tweets" : "yes", |
| 139 | + "phd" : "no"} ) |
| 140 | + |
| 141 | + print "Junior / Java / tweets / phd", classify(tree, |
| 142 | + { "level" : "Junior", |
| 143 | + "lang" : "Java", |
| 144 | + "tweets" : "yes", |
| 145 | + "phd" : "yes"} ) |
| 146 | + |
| 147 | + print "Intern", classify(tree, { "level" : "Intern" } ) |
| 148 | + print "Senior", classify(tree, { "level" : "Senior" } ) |
| 149 | + |
0 commit comments