-
Notifications
You must be signed in to change notification settings - Fork 0
/
distances.go
42 lines (35 loc) · 924 Bytes
/
distances.go
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
package go_k_means
func nearestDataToDatum(data []Datum, target Datum) int {
nearestIndex := 0
nearestDatum := data[nearestIndex]
minDistance := nearestDatum.Vector.Distance(target.Vector)
for i := range data[1:] {
distance := data[i+1].Vector.Distance(target.Vector)
if distance < minDistance {
minDistance = distance
nearestIndex = i + 1
nearestDatum = data[i]
}
}
return nearestIndex
}
func avgDistance(data []Datum, target Datum) float64 {
var sum float64
for _, datum := range data {
sum += datum.Vector.Distance(target.Vector)
}
return sum / float64(len(data))
}
func avgDistanceToNearestForeignCluster(clusters [][]Datum, target Datum) float64 {
distance := 1e10
for i, cluster := range clusters {
if i == target.cluster {
continue
}
foreignDistance := avgDistance(cluster, target)
if foreignDistance < distance {
distance = foreignDistance
}
}
return distance
}