-
Notifications
You must be signed in to change notification settings - Fork 6
/
exhaustive.go
49 lines (40 loc) · 1 KB
/
exhaustive.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
package ann
import (
mat "github.com/gonum/matrix/mat64"
"github.com/rikonor/go-ann/ksmall"
)
type exhaustive struct {
xs [][]float64
}
// NewExhaustiveNNer creates a new ANNer that uses exhaustive search
// Obviously you should use this for all your performance sensitive tasks
func NewExhaustiveNNer(xs [][]float64) ANNer {
return &exhaustive{xs: xs}
}
func (nn *exhaustive) ANN(q []float64, k int) []int {
if len(nn.xs) == 0 {
return []int{}
}
n, d := len(nn.xs), len(nn.xs[0])
// Put the query value into a vector
qVec := mat.NewVector(len(q), q)
// Put our data into a matrix
X := mat.NewDense(d, n, nil)
for i := 0; i < n; i++ {
X.SetCol(i, nn.xs[i])
}
// Calculate distances
distsVec := mat.NewVector(n, nil)
for i := 0; i < n; i++ {
distVec := mat.NewVector(d, nil)
distVec.SubVec(
X.ColView(i),
qVec,
)
dist := mat.Norm(distVec, 2)
distsVec.SetVec(i, dist)
}
// Get k closest results
distances := mat.Col(nil, 0, distsVec)
return ksmall.KSmallestIndices(distances, k)
}