Class: DecisionTree::Ruleset

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes, data, default, type) ⇒ Ruleset

Returns a new instance of Ruleset.



332
333
334
335
336
337
338
# File 'lib/SelfModifiedDecisionTree.rb', line 332

def initialize(attributes, data, default, type)
  @attributes, @default, @type = attributes, default, type
  mixed_data = data.sort_by {rand}
  cut = (mixed_data.size.to_f * 0.67).to_i
  @train_data = mixed_data.slice(0..cut-1)
  @prune_data = mixed_data.slice(cut..-1)
end

Instance Attribute Details

#rulesObject

Returns the value of attribute rules.



330
331
332
# File 'lib/SelfModifiedDecisionTree.rb', line 330

def rules
  @rules
end

Instance Method Details

#predict(test) ⇒ Object



366
367
368
369
370
371
372
# File 'lib/SelfModifiedDecisionTree.rb', line 366

def predict(test)
  @rules.each do |r|
    prediction = r.predict(test)
    return prediction, r.accuracy unless prediction.nil?
  end
  return @default, 0.0
end

#prune(data = @prune_data) ⇒ Object



348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/SelfModifiedDecisionTree.rb', line 348

def prune(data=@prune_data)
  @rules.each do |r|
    (1..r.premises.size).each do
      acc1 = r.accuracy(data)
      p = r.premises.pop
      if acc1 > r.get_accuracy(data) then
        r.premises.push(p); break
      end
    end
  end
  @rules = @rules.sort_by{|r| -r.accuracy(data)}
end

#to_sObject



361
362
363
364
# File 'lib/SelfModifiedDecisionTree.rb', line 361

def to_s
  str = ''; @rules.each { |rule| str += "#{rule}\n\n" }
  str
end

#train(train_data = @train_data, attributes = @attributes, default = @default) ⇒ Object



340
341
342
343
344
345
346
# File 'lib/SelfModifiedDecisionTree.rb', line 340

def train(train_data=@train_data, attributes=@attributes, default=@default)
  dec_tree = DecisionTree::ID3Tree.new(attributes, train_data, default, @type)
  dec_tree.train
  @rules = dec_tree.build_rules
  @rules.each { |r| r.accuracy(train_data) } # Calculate accuracy
  prune
end