Class: Pedicab::RANK::KNN
- Inherits:
-
Object
- Object
- Pedicab::RANK::KNN
- Defined in:
- lib/pedicab/rank.rb
Instance Method Summary collapse
-
#initialize(strings) ⇒ KNN
constructor
Initialize with a collection of strings.
-
#rank(id, query, k = 5, method: :levenshtein) ⇒ Object
Find k nearest neighbors to the query string Returns array of hashes with :string, :distance, and :similarity.
Constructor Details
#initialize(strings) ⇒ KNN
Initialize with a collection of strings
5 6 7 |
# File 'lib/pedicab/rank.rb', line 5 def initialize(strings) @strings = strings end |
Instance Method Details
#rank(id, query, k = 5, method: :levenshtein) ⇒ Object
Find k nearest neighbors to the query string Returns array of hashes with :string, :distance, and :similarity
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/pedicab/rank.rb', line 11 def rank(id, query, k = 5, method: :levenshtein) a, t = id.split("-") return [] if @strings.empty? # Calculate distances for all strings distances = @strings.map do |str| dist = levenshtein_distance(query, str) { book: id, author: a, title: t, string: str.strip, distance: dist, similarity: 1.0 / (1.0 + dist) } end # Sort by distance (ascending) and take k nearest distances.sort_by { |d| d[:distance] }.take([k, @strings.length].min) end |