Skip to content

Instantly share code, notes, and snippets.

@kalelc
Last active October 20, 2016 13:35
Show Gist options
  • Save kalelc/dc50d95b323dc4af44961c74719bb617 to your computer and use it in GitHub Desktop.
Save kalelc/dc50d95b323dc4af44961c74719bb617 to your computer and use it in GitHub Desktop.
module Kmeans
class Demo
# data list and clusters
attr_accessor :data, :k
def initialize(data, k, i = 10)
@data = data
@k = k
clusters = []
(1..@k).each do |cluster|
index = (@data.length * rand).to_i
point = Kmeans::Point.new(@data[index].first, @data[index].last)
clusters << Kmeans::Cluster.new(point)
end
group_elements(clusters)
(1..i).each do |iteration|
clusters.each do |c|
puts c.centroid.to_a.inspect
puts c.centroid!
end
end
end
#group elements by minimal distance
def group_elements(clusters)
@data.each do |d|
distance = []
clusters.each_with_index do |cluster, index|
distance[index] = GpsWaypoints.distance(cluster.centroid.to_a, d)
end
a, b = distance.each_with_index.min
clusters[b].points << Kmeans::Point.new(d.first, d.last)
end
return clusters
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment