Class: Clusterable::Cluster
- Inherits:
-
Object
- Object
- Clusterable::Cluster
- Defined in:
- lib/clusterable/cluster.rb
Instance Attribute Summary collapse
-
#center ⇒ Object
Returns the value of attribute center.
-
#points ⇒ Object
Returns the value of attribute points.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(points = [], center = nil) ⇒ Cluster
constructor
A new instance of Cluster.
- #update(points) ⇒ Object
Constructor Details
#initialize(points = [], center = nil) ⇒ Cluster
Returns a new instance of Cluster.
5 6 7 8 9 |
# File 'lib/clusterable/cluster.rb', line 5 def initialize(points = [], center = nil) raise "can't initialize an empty cluster" unless points.size > 0 self.points = points self.center = center || calculate_center end |
Instance Attribute Details
#center ⇒ Object
Returns the value of attribute center.
3 4 5 |
# File 'lib/clusterable/cluster.rb', line 3 def center @center end |
#points ⇒ Object
Returns the value of attribute points.
3 4 5 |
# File 'lib/clusterable/cluster.rb', line 3 def points @points end |
Class Method Details
.kmeans(points, sample_size, distance_cutoff) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/clusterable/cluster.rb', line 12 def self.kmeans(points, sample_size, distance_cutoff) initial = pick_random(points, sample_size) clusters = initial.map do |point| new([point], point) end while true lists = [] clusters.each { lists << [] } points.each do |point| smallest_distance = point.distance_to(clusters.first.center) index = 0 clusters[1..clusters.length].each.with_index do |cluster, i| distance = point.distance_to(cluster.center) if distance < smallest_distance smalles_distance = distance index = i + 1 end end lists[index] << point end biggest_shift = 0.0 clusters.each.with_index do |cluster, index| if lists[index].size > 0 shift = cluster.update(lists[index]) biggest_shift = [shift, biggest_shift].max end end break if biggest_shift < distance_cutoff end clusters end |
Instance Method Details
#update(points) ⇒ Object
52 53 54 55 56 57 58 |
# File 'lib/clusterable/cluster.rb', line 52 def update(points) self.points = points.compact old_center = center.dup self.center = calculate_center center.distance_to(old_center) end |