Class: ML::Learner::PerceptronLearner

Inherits:
Object
  • Object
show all
Includes:
LinearToolbox, Toolbox
Defined in:
lib/method/perceptron.rb

Overview

Implementation of Perceptron Learning Algorithm

Direct Known Subclasses

AdaptivePerceptronLearner, PocketLearner

Instance Attribute Summary

Attributes included from LinearToolbox

#current_vector

Instance Method Summary collapse

Methods included from LinearToolbox

#line, #predict

Methods included from Toolbox

#classify_error, #predict

Constructor Details

#initialize(dim) ⇒ PerceptronLearner

Initialize a perceptron learner

Parameters:

  • dim (Integer)

    the number of dimension



13
14
15
16
# File 'lib/method/perceptron.rb', line 13

def initialize dim
  @dim = dim
  self.current_vector = Matrix.column_vector(Array.new(dim + 1, 0))
end

Instance Method Details

#train!(data, threshold = 1.0/0) ⇒ Hash

Train with supervised data

Parameters:

  • data (Hash)

    supervised input data (mapping from array to integer)

  • threshold (Numeric) (defaults to: 1.0/0)

    the upper bound of the traning iteration

Returns:

  • (Hash)

    update_count error in traning and update numbers used



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/method/perceptron.rb', line 23

def train! data, threshold = 1.0/0
  pool = data.to_a
  update = 0

  while true
    break if update >= threshold
    misclassified = false
    order = (0...(pool.size)).to_a.shuffle

    for i in order
      dat, result = pool[i]
      aug_data = Matrix.column_vector(dat)

      if wrongly_classify aug_data, result
        misclassified = true

        update_vector aug_data, result
        update += 1
        break
      end
    end

    break unless misclassified
  end
end