-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobservation.go
75 lines (62 loc) · 1.54 KB
/
observation.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
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
package kmeans
import (
"fmt"
"math"
)
// Coordinates is a slice of float64
type Coordinates []float64
// Observation is a data point (float64 between 0.0 and 1.0) in n dimensions
type Observation interface {
Coordinates() Coordinates
Distance(point Coordinates) float64
}
// Observations is a slice of observations
type Observations []Observation
// Coordinates implements the Observation interface for a plain set of float64
// coordinates
func (c Coordinates) Coordinates() Coordinates {
return Coordinates(c)
}
// Distance returns the euclidean distance between two coordinates
func (c Coordinates) Distance(p2 Coordinates) float64 {
var r float64
for i, v := range c {
r += math.Pow(v-p2[i], 2)
}
return r
}
// Center returns the center coordinates of a set of Observations
func (c Observations) Center() (Coordinates, error) {
var l = len(c)
if l == 0 {
return nil, fmt.Errorf("there is no mean for an empty set of points")
}
cc := make([]float64, len(c[0].Coordinates()))
for _, point := range c {
for j, v := range point.Coordinates() {
cc[j] += v
}
}
var mean Coordinates
for _, v := range cc {
mean = append(mean, v/float64(l))
}
return mean, nil
}
// AverageDistance returns the average distance between o and all observations
func AverageDistance(o Observation, observations Observations) float64 {
var d float64
var l int
for _, observation := range observations {
dist := o.Distance(observation.Coordinates())
if dist == 0 {
continue
}
l++
d += dist
}
if l == 0 {
return 0
}
return d / float64(l)
}