Class: AprendizajeMaquina::DecisionTree

Inherits:
Object
  • Object
show all
Defined in:
lib/aprendizaje_maquina/decision_tree.rb

Instance Method Summary collapse

Constructor Details

#initialize(dataset) ⇒ DecisionTree

Returns a new instance of DecisionTree.


3
4
5
# File 'lib/aprendizaje_maquina/decision_tree.rb', line 3

def initialize(dataset)
  @dataset = dataset
end

Instance Method Details

#display_treeObject


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
# File 'lib/aprendizaje_maquina/decision_tree.rb', line 7

def display_tree
  node_root = build_tree(@dataset)
  colection = [node_root]
  branches = []
  tree = "root --> #{node_root[1][0]}:#{node_root[1][1]}?\n"
  for node in 0...node_root[2].length
    branches << build_tree(node_root[2][node])
    colection << branches
    1000.times do 
      subbranches = []
      true_or_false = lambda { |node| node == 0 ? true : false }
      branches.each do |branch|
        if branch.is_a?(Array)
          tree << "#{true_or_false.call(node)} --> "+"#{branch[1][0]}:#{branch[1][1]}?\n"
          for node in 0...branch[2].length
            if build_tree(branch[2][node]).is_a? Hash
              tree << "#{true_or_false.call(node)} --> "+"#{build_tree(branch[2][node])}\n"
            else
              subbranches << build_tree(branch[2][node])
            end
          end
        elsif branch.is_a?(Hash)
          tree << "#{true_or_false.call(node)} --> "+"#{branch}\n"
        end
      end
      branches = subbranches
      colection << branches
      if colection.last.empty?
        colection.pop
        break
      end
    end
  end
  return tree
end

#predict(observation) ⇒ Object


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/aprendizaje_maquina/decision_tree.rb', line 43

def predict(observation)
  node_root = build_tree(@dataset)
  until node_root.is_a?(Hash)
    if observation[node_root[1][0]].is_a?(Integer) or observation[node_root[1][0]].is_a?(Float)
      if observation[node_root[1][0]] >= node_root[1][1]
        branch = build_tree(node_root[2][0])
      else 
        branch = build_tree(node_root[2][1])
      end
    else
      if observation[node_root[1][0]] == node_root[1][1]
        branch = build_tree(node_root[2][0])
      else 
        branch = build_tree(node_root[2][1])
      end
    end
    node_root = branch
  end
  return node_root
end