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.



258
259
260
261
262
263
264
# File 'lib/decisiontree/id3_tree.rb', line 258

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.



256
257
258
# File 'lib/decisiontree/id3_tree.rb', line 256

def rules
  @rules
end

Instance Method Details

#predict(test) ⇒ Object



292
293
294
295
296
297
298
# File 'lib/decisiontree/id3_tree.rb', line 292

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



274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/decisiontree/id3_tree.rb', line 274

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



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

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

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



266
267
268
269
270
271
272
# File 'lib/decisiontree/id3_tree.rb', line 266

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