forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathKMeans.swift
80 lines (64 loc) · 1.79 KB
/
KMeans.swift
1
2
3
4
5
6
7
8
9
10
11
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//
// KMeans.swift
//
// Created by John Gill on 2/25/16.
import Foundation
class KMeans {
let numCenters: Int
let convergeDist: Double
init(numCenters: Int, convergeDist: Double) {
self.numCenters = numCenters
self.convergeDist = convergeDist
}
private func nearestCenter(x: Vector, centers: [Vector]) -> Int {
var nearestDist = DBL_MAX
var minIndex = 0
for (idx, c) in centers.enumerate() {
let dist = x.distTo(c)
if dist < nearestDist {
minIndex = idx
nearestDist = dist
}
}
return minIndex
}
func findCenters(points: [Vector]) -> [Vector] {
var centerMoveDist = 0.0
let zeros = [Double](count: points[0].length, repeatedValue: 0.0)
var kCenters = reservoirSample(points, k: numCenters)
repeat {
var cnts = [Double](count: numCenters, repeatedValue: 0.0)
var newCenters = [Vector](count:numCenters, repeatedValue: Vector(d:zeros))
for p in points {
let c = nearestCenter(p, centers: kCenters)
cnts[c] += 1
newCenters[c] += p
}
for idx in 0..<numCenters {
newCenters[idx] /= cnts[idx]
}
centerMoveDist = 0.0
for idx in 0..<numCenters {
centerMoveDist += kCenters[idx].distTo(newCenters[idx])
}
kCenters = newCenters
} while centerMoveDist > convergeDist
return kCenters
}
}
// Pick k random elements from samples
func reservoirSample<T>(samples:[T], k:Int) -> [T] {
var result = [T]()
// Fill the result array with first k elements
for i in 0..<k {
result.append(samples[i])
}
// randomly replace elements from remaining pool
for i in (k+1)..<samples.count {
let j = random() % (i+1)
if j < k {
result[j] = samples[i]
}
}
return result
}