-
Notifications
You must be signed in to change notification settings - Fork 5
/
distance.go
50 lines (42 loc) · 1.23 KB
/
distance.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
package hnsw
import (
"math"
"reflect"
"github.com/viterin/vek/vek32"
)
// DistanceFunc is a function that computes the distance between two vectors.
type DistanceFunc func(a, b []float32) float32
// CosineDistance computes the cosine distance between two vectors.
func CosineDistance(a, b []float32) float32 {
return 1 - vek32.CosineSimilarity(a, b)
}
// EuclideanDistance computes the Euclidean distance between two vectors.
func EuclideanDistance(a, b []float32) float32 {
// TODO: can we speedup with vek?
var sum float32 = 0
for i := range a {
diff := a[i] - b[i]
sum += diff * diff
}
return float32(math.Sqrt(float64(sum)))
}
var distanceFuncs = map[string]DistanceFunc{
"euclidean": EuclideanDistance,
"cosine": CosineDistance,
}
func distanceFuncToName(fn DistanceFunc) (string, bool) {
for name, f := range distanceFuncs {
fnptr := reflect.ValueOf(fn).Pointer()
fptr := reflect.ValueOf(f).Pointer()
if fptr == fnptr {
return name, true
}
}
return "", false
}
// RegisterDistanceFunc registers a distance function with a name.
// A distance function must be registered here before a graph can be
// exported and imported.
func RegisterDistanceFunc(name string, fn DistanceFunc) {
distanceFuncs[name] = fn
}