Class: Carmenere::KMeans::Algorithm
- Defined in:
- lib/carmenere/kmeans/algorithm.rb
Instance Attribute Summary collapse
-
#centroids ⇒ Object
readonly
Returns the value of attribute centroids.
Attributes inherited from Algorithm
Instance Method Summary collapse
-
#initialize(centroids, nodes, &mean) ⇒ Algorithm
constructor
A new instance of Algorithm.
- #run ⇒ Object
Constructor Details
#initialize(centroids, nodes, &mean) ⇒ Algorithm
Returns a new instance of Algorithm.
22 23 24 25 26 |
# File 'lib/carmenere/kmeans/algorithm.rb', line 22 def initialize centroids, nodes, &mean super centroids.count, nodes @mean = mean @centroids = centroids end |
Instance Attribute Details
#centroids ⇒ Object (readonly)
Returns the value of attribute centroids.
20 21 22 |
# File 'lib/carmenere/kmeans/algorithm.rb', line 20 def centroids @centroids end |
Instance Method Details
#run ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/carmenere/kmeans/algorithm.rb', line 28 def run old_centroids = Set.new centroids = Set.new @centroids centroid_clusters = {nil => nil} until Carmenere::KMeans::centroids_eql? old_centroids, centroids old_centroids = centroids node_centroids = @nodes.each.with_object({}) do |node, h| h[node] = centroids.min_by do |c| node.distance(c) end end centroid_clusters = centroids.each.with_object({}) do |centroid, h| nodes = node_centroids.lazy.select do |_, c| c.attr_eql?(centroid) end.map do |n, c| n end h[centroid] = Carmenere::KMeans::Cluster.new nodes end yield centroid_clusters if block_given? centroids = Set.new centroid_clusters.values.map do |cluster| @mean.call(cluster) end end centroid_clusters end |