Class: Borealis::KMeans

Inherits:
Object
  • Object
show all
Defined in:
lib/borealis/kmeans.rb

Instance Method Summary collapse

Constructor Details

#initialize(colors, options = {}) ⇒ KMeans

Returns a new instance of KMeans.



3
4
5
6
7
8
9
10
11
12
# File 'lib/borealis/kmeans.rb', line 3

def initialize(colors, options = {})
  @colors = colors
  @number_of_clusters = options[:number_of_clusters] || 3
  @delta = options[:delta] || 0.01
  @static = options.has_key?(:static) ? options[:static] : true

  if @number_of_clusters > @colors.length
    raise 'You may not have more clusters than colors.'
  end
end

Instance Method Details

#runObject



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/borealis/kmeans.rb', line 14

def run
  if @colors.length == @number_of_clusters
    @colors.map { |color| Cluster.new(color) }
  else
    max_delta = 0
    while max_delta <= @delta do
      @colors.each { |color| add_to_closest_cluster(color) }
      max_delta = clusters.map { |cluster| cluster.recenter! }.max
    end

    clusters
  end
end