...
1 package chromem
2
3 import "math"
4
5 func cosine_similarities(a, b [][]float32) [][]float32 {
6 result := make([][]float32, len(a))
7 for iX, x := range a {
8 result[iX] = make([]float32, len(b))
9 for iY, y := range b {
10 result[iX][iY] = cosine_similarity(x, y)
11 }
12 }
13 return result
14 }
15
16 func cosine_similarity(x, y []float32) float32 {
17 var sum, s1, s2 float64
18 for i := 0; i < len(x); i++ {
19 sum += float64(x[i] * y[i])
20 s1 += math.Pow(float64(x[i]), 2)
21 s2 += math.Pow(float64(y[i]), 2)
22 }
23 if s1 == 0 || s2 == 0 {
24 return 0.0
25 }
26 return float32(sum / (math.Sqrt(s1) * math.Sqrt(s2)))
27 }
28
View as plain text