class Perceptron

The multiclass perceptron class with customizable number of iterations and folds.

Attributes

folds[R]
iterations[R]
labels[R]
weights[R]

Public Class Methods

new(iterations = 100, folds = 5) click to toggle source
# File lib/rubyml/perceptron.rb, line 11
def initialize(iterations = 100, folds = 5)
  @iterations = iterations
  @epsilon = nil
  @folds = folds
  @labels = []
  @weights = {}
end

Public Instance Methods

cold_start() click to toggle source
# File lib/rubyml/perceptron.rb, line 60
def cold_start
  @labels = []
  @weights = {}
end
fit(x, y, cs = true) click to toggle source
# File lib/rubyml/perceptron.rb, line 29
def fit(x, y, cs = true)
  cold_start if cs
  setup_weights(y)
  @iterations.times do
    x.row_count.times do |r|
      clbl = get_best_guess(x, r)
      next unless y[r, 0] != clbl
      x.column_count.times { |c| update_weights(clbl, y[r, 0], c, x[r, c]) }
    end
  end
end
get_best_guess(x, r) click to toggle source
# File lib/rubyml/perceptron.rb, line 47
def get_best_guess(x, r)
  clbl, cmax = nil
  @labels.each do |lbl|
    csum = 0.0
    x.column_count.times { |c| csum += @weights[lbl][c] * x[r, c] }
    if cmax.nil? || cmax <= csum
      cmax = csum
      clbl = lbl
    end
  end
  clbl
end
predict(x) click to toggle source
# File lib/rubyml/perceptron.rb, line 41
def predict(x)
  preds = []
  x.row_count.times { |r| preds << get_best_guess(x, r) }
  Matrix.columns([preds])
end
setup_weights(y) click to toggle source
# File lib/rubyml/perceptron.rb, line 19
def setup_weights(y)
  @labels = mat_to_array(y).uniq { |e| e }
  @labels.each { |lbl| @weights[lbl] = Hash.new(0) }
end
update_weights(guess, real, c, w) click to toggle source
# File lib/rubyml/perceptron.rb, line 24
def update_weights(guess, real, c, w)
  @weights[guess][c] -= w
  @weights[real][c] += w
end