Class: DecisionTree::Rule

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes, premises = [], conclusion = nil) ⇒ Rule

Returns a new instance of Rule.



283
284
285
# File 'lib/SelfModifiedDecisionTree.rb', line 283

def initialize(attributes,premises=[],conclusion=nil)
  @attributes, @premises, @conclusion = attributes, premises, conclusion
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



281
282
283
# File 'lib/SelfModifiedDecisionTree.rb', line 281

def attributes
  @attributes
end

#conclusionObject

Returns the value of attribute conclusion.



280
281
282
# File 'lib/SelfModifiedDecisionTree.rb', line 280

def conclusion
  @conclusion
end

#premisesObject

Returns the value of attribute premises.



279
280
281
# File 'lib/SelfModifiedDecisionTree.rb', line 279

def premises
  @premises
end

Instance Method Details

#accuracy(data = nil) ⇒ Object



324
325
326
# File 'lib/SelfModifiedDecisionTree.rb', line 324

def accuracy(data=nil)
  data.nil? ? @accuracy : @accuracy = get_accuracy(data)
end

#get_accuracy(data) ⇒ Object



314
315
316
317
318
319
320
321
322
# File 'lib/SelfModifiedDecisionTree.rb', line 314

def get_accuracy(data)
  correct = 0; total = 0
  data.each do |d|
    prediction = predict(d)
    correct += 1 if d.last == prediction
    total += 1 if !prediction.nil?
  end
  (correct.to_f + 1) / (total.to_f + 2)
end

#predict(test) ⇒ Object



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/SelfModifiedDecisionTree.rb', line 297

def predict(test)
  verifies = true;
  @premises.each do |p|
    if p.first.threshold then # Continuous
      if !(p.last == '>=' && test[@attributes.index(p.first.attribute)] >= p.first.threshold) && !(p.last == '<' && test[@attributes.index(p.first.attribute)] < p.first.threshold) then
        verifies = false; break
      end
    else # Discrete
      if test[@attributes.index(p.first.attribute)] != p.last then
        verifies = false; break
      end
    end
  end
  return @conclusion if verifies
  return nil
end

#to_sObject



287
288
289
290
291
292
293
294
295
# File 'lib/SelfModifiedDecisionTree.rb', line 287

def to_s
  str = ''
  @premises.each do |p|
    str += "#{p.first.attribute} #{p.last} #{p.first.threshold}" if p.first.threshold
    str += "#{p.first.attribute} = #{p.last}" if !p.first.threshold
    str += "\n"
  end
  str += "=> #{@conclusion} (#{accuracy})"
end