Skip to content

Commit ce78581

Browse files
committed
Merge pull request kodecocodes#51 from johnsgill3/k-means
Implement K-Means algorithm
2 parents 5a4fac9 + 90aa71c commit ce78581

10 files changed

+589
-1
lines changed

K-Means/Images/k_means_bad1.png

15.9 KB
Loading

K-Means/Images/k_means_bad2.png

15.5 KB
Loading

K-Means/Images/k_means_good.png

15.6 KB
Loading

K-Means/KMeans.swift

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
//
2+
// KMeans.swift
3+
//
4+
// Created by John Gill on 2/25/16.
5+
6+
import Foundation
7+
8+
class KMeans {
9+
var numCenters:Int
10+
var convergeDist:Double
11+
12+
init(numCenters:Int, convergeDist:Double) {
13+
self.numCenters = numCenters
14+
self.convergeDist = convergeDist
15+
}
16+
17+
private func nearestCenter(x: Vector, Centers: [Vector]) -> Int {
18+
var nearestDist = DBL_MAX
19+
var minIndex = 0;
20+
21+
for (idx, c) in Centers.enumerate() {
22+
let dist = x.distTo(c)
23+
if dist < nearestDist {
24+
minIndex = idx
25+
nearestDist = dist
26+
}
27+
}
28+
return minIndex
29+
}
30+
31+
func findCenters(points: [Vector]) -> [Vector] {
32+
var centerMoveDist = 0.0
33+
let zeros = [Double](count: points[0].length, repeatedValue: 0.0)
34+
35+
var kCenters = reservoirSample(points, k: numCenters)
36+
37+
repeat {
38+
var cnts = [Double](count: numCenters, repeatedValue: 0.0)
39+
var newCenters = [Vector](count:numCenters, repeatedValue: Vector(d:zeros))
40+
41+
for p in points {
42+
let c = nearestCenter(p, Centers: kCenters)
43+
cnts[c]++
44+
newCenters[c] += p
45+
}
46+
47+
for idx in 0..<numCenters {
48+
newCenters[idx] /= cnts[idx]
49+
}
50+
51+
centerMoveDist = 0.0
52+
for idx in 0..<numCenters {
53+
centerMoveDist += kCenters[idx].distTo(newCenters[idx])
54+
}
55+
56+
kCenters = newCenters
57+
} while(centerMoveDist > convergeDist)
58+
return kCenters
59+
}
60+
}
61+
62+
// Pick k random elements from samples
63+
func reservoirSample<T>(samples:[T], k:Int) -> [T] {
64+
var result = [T]()
65+
66+
// Fill the result array with first k elements
67+
for i in 0..<k {
68+
result.append(samples[i])
69+
}
70+
// randomly replace elements from remaining pool
71+
for i in (k+1)..<samples.count {
72+
let j = random()%(i+1)
73+
if j < k {
74+
result[j] = samples[i]
75+
}
76+
}
77+
return result
78+
}
79+

K-Means/README.md

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# K-Means
2+
3+
Goal: Partition data into k clusters based on nearest means
4+
5+
The idea behind K-Means is to try and take data that has no formal classification to it and determine if there are any natural clusters within the data.
6+
7+
K-Means assumes that there are **k-centers** within the data. The data that is then closest to these *centroids* become classified or grouped together. K-Means doesn't tell you what the classifier is for that particular data group, but it assists in trying to find what clusters potentially exist.
8+
9+
## Algorithm
10+
The k-means algorithm is really quite simple at it's core:
11+
1. Choose k random points to be the initial centers
12+
2. Repeat the following two steps until the *centroid* reach convergence
13+
1. Assign each point to it's nearest *centroid*
14+
2. Update the *centroid* to the mean of it's nearest points
15+
16+
Convergence is said to be reached when all of the *centroids* have not changed.
17+
18+
This brings about a few of the parameters that are required for k-means:
19+
- **k** - This is the number of *centroids* to attempt to locate
20+
- **convergence distance** - This is minimum distance that the centers are allowed to moved after a particular update step.
21+
- **distance function** - There are a number of distance functions that can be used, but mostly commonly the euclidean distance function is adequate. But often can lead to convergence not being reached in higher dimensionally.
22+
23+
This is what the algorithm would look like in swift
24+
```swift
25+
func kMeans(numCenters: Int, convergeDist: Double, points: [Vector]) -> [Vector] {
26+
var centerMoveDist = 0.0
27+
let zeros = [Double](count: points[0].getLength(), repeatedValue: 0.0)
28+
29+
var kCenters = reservoirSample(points, k: numCenters)
30+
31+
repeat {
32+
var cnts = [Double](count: numCenters, repeatedValue: 0.0)
33+
var newCenters = [Vector](count:numCenters, repeatedValue: Vector(d:zeros))
34+
for p in points {
35+
let c = nearestCenter(p, Centers: kCenters)
36+
cnts[c]++
37+
newCenters[c] += p
38+
}
39+
for idx in 0..<numCenters {
40+
newCenters[idx] /= cnts[idx]
41+
}
42+
centerMoveDist = 0.0
43+
for idx in 0..<numCenters {
44+
centerMoveDist += euclidean(kCenters[idx], v2: newCenters[idx])
45+
}
46+
kCenters = newCenters
47+
} while(centerMoveDist > convergeDist)
48+
return kCenters
49+
}
50+
```
51+
52+
## Example
53+
These examples are contrived to show the exact nature of K-Means and finding clusters. These clusters are very easily identified by human eyes, we see there is one in the lower left corner, one in the upper right corner and maybe one in the middle.
54+
55+
In all these examples the stars represent the *centroids* and the squares are the points.
56+
57+
##### Good clusters
58+
This first example shows K-Means finding all three clusters:
59+
![Good Clustering](Images/k_means_good.png)
60+
61+
The selection of initial centroids found that lower left (indicated by red) and did pretty good on the center and upper left clusters.
62+
63+
#### Bad Clustering
64+
The next two examples highlight the unpredictability of k-Means and how not always does it find the best clustering.
65+
![Bad Clustering 1](Images/k_means_bad1.png)
66+
As you can see in this one the initial *centroids* were all a little two close and the 'blue' didn't quite get to a good place. By adjusting the convergence distance should be able to get it better.
67+
68+
![Bad Clustering 1](Images/k_means_bad2.png)
69+
This one the blue cluster never really could separate from the red cluster and as such sort of got stuck down there.
70+
71+
## Performance
72+
The first thing to recognize is that k-Means is classified as an NP-Hard type of problem. The selection of the initial *centroids* has a big effect on how the resulting clusters may end up. This means that trying to find an exact solution is not likely - even in 2 dimensional space.
73+
74+
As seem from the steps above the complexity really isn't that bad - it is often considered to be on the order of O(kndi), where **k** is the number of *centroids*, **n** is the number of **d** dimensional vectors and **i** is the number of iterations for convergence.
75+
76+
The amount of data has a big linear effect on the running time of k-means, but tuning how far you want the *centroids* to converge can have a big impact how many iterations will be done - **k** should be relatively small compared to the number of vectors.
77+
78+
Often times as more data is added certain points may lie in the boundary between two *centroids* and as such those centroids would continue to bounce back and forth and the **convergence** distance would need to be tuned to prevent that.
79+
80+
## See Also
81+
See also [Wikipedia](https://en.wikipedia.org/wiki/K-means_clustering)
82+
83+
*Written by John Gill*

K-Means/Tests/Info.plist

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+
<plist version="1.0">
4+
<dict>
5+
<key>CFBundleDevelopmentRegion</key>
6+
<string>en</string>
7+
<key>CFBundleExecutable</key>
8+
<string>$(EXECUTABLE_NAME)</string>
9+
<key>CFBundleIdentifier</key>
10+
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
11+
<key>CFBundleInfoDictionaryVersion</key>
12+
<string>6.0</string>
13+
<key>CFBundleName</key>
14+
<string>$(PRODUCT_NAME)</string>
15+
<key>CFBundlePackageType</key>
16+
<string>BNDL</string>
17+
<key>CFBundleShortVersionString</key>
18+
<string>1.0</string>
19+
<key>CFBundleSignature</key>
20+
<string>????</string>
21+
<key>CFBundleVersion</key>
22+
<string>1</string>
23+
</dict>
24+
</plist>

K-Means/Tests/KMeansTests.swift

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
//
2+
// Tests.swift
3+
// Tests
4+
//
5+
// Created by John Gill on 2/29/16.
6+
//
7+
//
8+
9+
import Foundation
10+
import XCTest
11+
12+
class KMeansTests: XCTestCase {
13+
var points = [Vector]()
14+
15+
func genPoints(numPoints:Int, numDimmensions:Int) {
16+
for _ in 0..<numPoints {
17+
var data = [Double]()
18+
for _ in 0..<numDimmensions {
19+
data.append(Double(arc4random_uniform(UInt32(numPoints*numDimmensions))))
20+
}
21+
points.append(Vector(d: data))
22+
}
23+
24+
}
25+
26+
func testSmall_2D() {
27+
genPoints(10, numDimmensions: 2)
28+
29+
print("\nCenters")
30+
let kmm = KMeans(numCenters: 3, convergeDist: 0.01)
31+
for c in kmm.findCenters(points) {
32+
print(c)
33+
}
34+
}
35+
36+
func testSmall_10D() {
37+
genPoints(10, numDimmensions: 10)
38+
39+
print("\nCenters")
40+
let kmm = KMeans(numCenters: 3, convergeDist: 0.01)
41+
for c in kmm.findCenters(points) {
42+
print(c)
43+
}
44+
}
45+
46+
func testLarge_2D() {
47+
genPoints(10000, numDimmensions: 2)
48+
49+
print("\nCenters")
50+
let kmm = KMeans(numCenters: 5, convergeDist: 0.01)
51+
for c in kmm.findCenters(points) {
52+
print(c)
53+
}
54+
}
55+
56+
func testLarge_10D() {
57+
genPoints(10000, numDimmensions: 10)
58+
59+
print("\nCenters")
60+
let kmm = KMeans(numCenters: 5, convergeDist: 0.01)
61+
for c in kmm.findCenters(points) {
62+
print(c)
63+
}
64+
}
65+
}

0 commit comments

Comments
 (0)