Class: Callidus::KNN

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ip = [], op = []) ⇒ KNN

Returns a new instance of KNN.



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

def initialize(ip = [], op = [])
    @input = ip
    @output = op
end

Instance Attribute Details

#inputObject

Returns the value of attribute input.



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

def input
  @input
end

#outputObject

Returns the value of attribute output.



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

def output
  @output
end

Instance Method Details

#predict(x, k = 1) ⇒ Object



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

def predict(x, k = 1)
    diffs = @input.map { |i| Math.sqrt(x.each_with_index.map { |val, ind| (i[ind] - val) ** 2 }.sum) }
    tdiffs = diffs.dup

    mins = []

    k.times do |i|
        ind = tdiffs.index(tdiffs.min)
        mins << tdiffs[ind]
        tdiffs.pop(ind)
    end

    @output[diffs.index(Comp::Arrays.MostFrequent(mins))];
end