Class: Arroz::KNN
- Inherits:
-
Object
- Object
- Arroz::KNN
- Defined in:
- lib/arroz/knn.rb
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Returns the value of attribute data.
-
#k ⇒ Object
readonly
Returns the value of attribute k.
Instance Method Summary collapse
-
#classify(element) ⇒ Object
Returns the predicted class of the element passed.
-
#initialize(data, k = 1) ⇒ KNN
constructor
The label attribute in the data array must be in the first position.
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
#data ⇒ Object (readonly)
Returns the value of attribute data.
4 5 6 |
# File 'lib/arroz/knn.rb', line 4 def data @data end |
#k ⇒ Object (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 |