This repository has been archived by the owner on Oct 31, 2024. It is now read-only.
forked from coder/hnsw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
distance.go
61 lines (52 loc) · 1.48 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
51
52
53
54
55
56
57
58
59
60
61
package hnsw
import (
"fmt"
"reflect"
"github.com/chewxy/math32"
"github.com/viterin/vek/vek32"
)
// DistanceFunc is a function that computes the distance between two vectors.
type DistanceFunc func(a, b []float32) (float32, error)
var (
ErrDifferentVectorLengths = fmt.Errorf("vectors have different lengths")
)
// CosineDistance computes the cosine distance between two vectors.
func CosineDistance(a, b []float32) (float32, error) {
if len(a) != len(b) {
return 0, ErrDifferentVectorLengths
}
return 1 - vek32.CosineSimilarity(a, b), nil
}
// EuclideanDistance computes the Euclidean distance between two vectors.
func EuclideanDistance(a, b []float32) (float32, error) {
if len(a) != len(b) {
return 0, ErrDifferentVectorLengths
}
// TODO: can we speedup with vek?
var sum float32 = 0
for i := range a {
diff := a[i] - b[i]
sum += diff * diff
}
return math32.Sqrt(sum), nil
}
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
}