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.



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

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

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes.



202
203
204
# File 'lib/decisiontree/id3_tree.rb', line 202

def attributes
  @attributes
end

#conclusionObject

Returns the value of attribute conclusion.



201
202
203
# File 'lib/decisiontree/id3_tree.rb', line 201

def conclusion
  @conclusion
end

#premisesObject

Returns the value of attribute premises.



200
201
202
# File 'lib/decisiontree/id3_tree.rb', line 200

def premises
  @premises
end

Instance Method Details

#accuracy(data = nil) ⇒ Object



245
246
247
# File 'lib/decisiontree/id3_tree.rb', line 245

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

#get_accuracy(data) ⇒ Object



235
236
237
238
239
240
241
242
243
# File 'lib/decisiontree/id3_tree.rb', line 235

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



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/decisiontree/id3_tree.rb', line 218

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



208
209
210
211
212
213
214
215
216
# File 'lib/decisiontree/id3_tree.rb', line 208

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