Class: Arroz::KNN

Inherits:
Object
  • Object
show all
Defined in:
lib/arroz/knn.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, k = 1) ⇒ KNN

The label attribute in the data array must be in the first position



7
8
9
10
# File 'lib/arroz/knn.rb', line 7

def initialize(data, k=1)
  @data = data
  @k = k
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



4
5
6
# File 'lib/arroz/knn.rb', line 4

def data
  @data
end

#kObject (readonly)

Returns the value of attribute k.



4
5
6
# File 'lib/arroz/knn.rb', line 4

def k
  @k
end

Instance Method Details

#classify(element) ⇒ Object

Returns the predicted class of the element passed



13
14
15
16
17
18
19
20
21
# File 'lib/arroz/knn.rb', line 13

def classify(element)
  neighbors = nearest_neighbors(element)

  neighbor_classes = neighbors.map(&:last)
  classes = neighbor_classes.uniq

  classes.zip(classes.map { |c| neighbor_classes.count(c) }).
    sort_by(&:last).last.first
end