Class: Callidus::Winnow

Inherits:
Object
  • Object
show all
Defined in:
lib/src/Winnow.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ip = [], op = [], options = {}) ⇒ Winnow

Returns a new instance of Winnow.



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/src/Winnow.rb', line 13

def initialize(ip = [], op = [], options = {})
    @input = ip
    @output = op

    @default_weight = options[:default_weight] || 1
    @a = options[:a] || 2;
    @mode = options[:mode] || 0 # 0 is demote, 1 is reset

    @weights = []
    @trained = false
end

Instance Attribute Details

#aObject

Returns the value of attribute a.



8
9
10
# File 'lib/src/Winnow.rb', line 8

def a
  @a
end

#inputObject

Returns the value of attribute input.



5
6
7
# File 'lib/src/Winnow.rb', line 5

def input
  @input
end

#modeObject

Returns the value of attribute mode.



9
10
11
# File 'lib/src/Winnow.rb', line 9

def mode
  @mode
end

#outputObject

Returns the value of attribute output.



6
7
8
# File 'lib/src/Winnow.rb', line 6

def output
  @output
end

#weightsObject (readonly)

Returns the value of attribute weights.



11
12
13
# File 'lib/src/Winnow.rb', line 11

def weights
  @weights
end

Instance Method Details

#predict(x, options = {}) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/src/Winnow.rb', line 49

def predict(x, options = {})
    assert_trained()

    bias = options[:bias] || 0
    threshold = options[:threshold] || (@input.size / 2).to_i
    
    probability = 0;
    
    x.each_index do |i|
        probability += @weights[i] * x[i] + bias
    end
    
    (probability > threshold ? 1 : 0)
end

#train(a = @a) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/src/Winnow.rb', line 31

def train(a = @a)
    if (@input.size > 0 and @input[0] and @input[0].size > 0 and @input[0].size != @weights.size)
        @weights = Array.new(@input[0].size, @default_weight)
    end
    
    @input.each_index do |i|
        @input[i].each_index do |j|
            if @input[i][j] == 1
                @weights[j] *= @output[i] == 0 ? (@mode == 0 ? 1 / a : 0) : a
            end
        end
    end
    
    @trained = true
    
    self
end