Class: DecisionTree::Ruleset

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Ruleset.



253
254
255
256
257
258
259
# File 'lib/decisiontree/id3_tree.rb', line 253

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.



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

def rules
  @rules
end

Instance Method Details

#predict(test) ⇒ Object



287
288
289
290
291
292
293
# File 'lib/decisiontree/id3_tree.rb', line 287

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



269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/decisiontree/id3_tree.rb', line 269

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



282
283
284
285
# File 'lib/decisiontree/id3_tree.rb', line 282

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

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



261
262
263
264
265
266
267
# File 'lib/decisiontree/id3_tree.rb', line 261

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