Class: DecisionTree::Rule

Inherits:
Object show all
Defined in:
lib/decisiontree/id3_tree.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Rule



209
210
211
# File 'lib/decisiontree/id3_tree.rb', line 209

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

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes



207
208
209
# File 'lib/decisiontree/id3_tree.rb', line 207

def attributes
  @attributes
end

#conclusionObject

Returns the value of attribute conclusion



206
207
208
# File 'lib/decisiontree/id3_tree.rb', line 206

def conclusion
  @conclusion
end

#premisesObject

Returns the value of attribute premises



205
206
207
# File 'lib/decisiontree/id3_tree.rb', line 205

def premises
  @premises
end

Instance Method Details

#accuracy(data = nil) ⇒ Object



250
251
252
# File 'lib/decisiontree/id3_tree.rb', line 250

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

#get_accuracy(data) ⇒ Object



240
241
242
243
244
245
246
247
248
# File 'lib/decisiontree/id3_tree.rb', line 240

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



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/decisiontree/id3_tree.rb', line 223

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



213
214
215
216
217
218
219
220
221
# File 'lib/decisiontree/id3_tree.rb', line 213

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