Class: HybridForest::RandomForest

Inherits:
Object
  • Object
show all
Defined in:
lib/hybridforest/forests/random_forest.rb

Instance Method Summary collapse

Constructor Details

#initialize(number_of_trees:, ensemble_type: :hybrid) ⇒ RandomForest

Creates a new random forest.

number_of_trees dictates the size of the tree ensemble.

ensemble_type dictates the composition of the tree ensemble. Valid options are :hybrid, :cart, :id3.

Raises:

  • (ArgumentError)


15
16
17
18
19
20
# File 'lib/hybridforest/forests/random_forest.rb', line 15

def initialize(number_of_trees:, ensemble_type: :hybrid)
  raise ArgumentError, "Invalid ensemble type" unless Forests::GrowerFactory.types.include? ensemble_type

  @number_of_trees = number_of_trees
  @ensemble_type = ensemble_type
end

Instance Method Details

#fit(instances) ⇒ Object

Fits a model to the given dataset instances and returns self.



25
26
27
28
29
30
# File 'lib/hybridforest/forests/random_forest.rb', line 25

def fit(instances)
  instances = HybridForest::Utils.to_dataframe(instances)
  forest_grower = Forests::GrowerFactory.for(@ensemble_type)
  @forest = forest_grower.grow_forest(instances, @number_of_trees)
  self
end

#predict(instances) ⇒ Object

Predicts a label for each instance in the dataset instances and returns an array of labels.



35
36
37
38
39
40
41
# File 'lib/hybridforest/forests/random_forest.rb', line 35

def predict(instances)
  raise Errors::InvalidStateError, "You must call #fit before you call #predict" if @forest.nil?

  instances = HybridForest::Utils.to_dataframe(instances)
  predictions = tree_predictions(instances)
  predictions.collect { |votes| majority_vote(votes) }
end

#to_sObject



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

def to_s
  return "Empty random forest: \n#{super()}" if @forest.nil?

  title = case @ensemble_type
          when :hybrid then "Hybrid random forest"
          else "Uniform random forest"
  end

  table = Terminal::Table.new do |t|
    t.title = title
    t.headings = %w[Tree Count]
    tally_ensemble.each do |tree_type, count|
      t << [tree_type, count]
      t << :separator
    end
    t << ["Total", @number_of_trees]
  end
  table.to_s
end