Skip to content

Commit

Permalink
Further simplifcation of the code.
Browse files Browse the repository at this point in the history
  • Loading branch information
joshvfleming committed Jan 30, 2012
1 parent 6b58927 commit e833e31
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 30 deletions.
26 changes: 13 additions & 13 deletions README.md
Expand Up @@ -18,21 +18,21 @@ Output
------

Results of running k-means clustering on file: resources/kmeans-data-1.txt

Cluster with centroid: [8.333333 6.0]
[8.0 5.0]
[8.0 6.0]
[9.0 7.0]

Cluster with centroid: [22.5 20.0]
[23.0 25.0]
[22.0 15.0]


Cluster with centroid: [2.0 3.25]
[4.0 6.0]
[2.0 4.0]
[1.0 2.0]
[1.0 1.0]
[1.0 2.0]
[2.0 4.0]
[4.0 6.0]

Cluster with centroid: [22.5 20.0]
[22.0 15.0]
[23.0 25.0]

Cluster with centroid: [8.333333 6.0]
[9.0 7.0]
[8.0 6.0]
[8.0 5.0]

License
-------
Expand Down
24 changes: 7 additions & 17 deletions src/clujter/kmeans.clj
Expand Up @@ -16,30 +16,20 @@
(defn nearest-centroid
"Finds the nearest centroid to the vector."
[vector centroids]
((apply min-key :distance
(for [c centroids]
{:distance (get-distance vector c)
:centroid c}))
:centroid))
(apply min-key
#(get-distance vector %)
centroids))

(defn group-with-nearest-centroid
"Returns a map containing points grouped with their nearest centroid."
[vectors centroids]
(loop [remaining vectors
clusters {}]
(if (empty? remaining)
clusters
(let [vector (first remaining)
nearest (nearest-centroid vector centroids)
new-clusters (assoc clusters nearest
(conj (clusters nearest) vector))]
(recur (rest remaining) new-clusters)))))
(group-by #(nearest-centroid % centroids) vectors))

(defn calculate-centroid
"Calculates the central point of the given points."
[nodes]
(let [c (count nodes)]
(map #(float (/ % c)) (apply map + nodes))))
[vectors]
(let [c (count vectors)]
(map #(float (/ % c)) (apply map + vectors))))

(defn k-cluster
"Performs the k-means clustering on the vectors, and returns a map of
Expand Down

0 comments on commit e833e31

Please sign in to comment.