You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

search_default_util.go 1.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2023 The casbin Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package object
  15. import (
  16. "math"
  17. "sort"
  18. )
  19. func dot(vec1, vec2 []float32) float32 {
  20. if len(vec1) != len(vec2) {
  21. panic("Vector lengths do not match")
  22. }
  23. dotProduct := float32(0.0)
  24. for i := range vec1 {
  25. dotProduct += vec1[i] * vec2[i]
  26. }
  27. return dotProduct
  28. }
  29. func norm(vec []float32) float32 {
  30. normSquared := float32(0.0)
  31. for _, val := range vec {
  32. normSquared += val * val
  33. }
  34. return float32(math.Sqrt(float64(normSquared)))
  35. }
  36. func cosineSimilarity(vec1, vec2 []float32, vec1Norm float32) float32 {
  37. dotProduct := dot(vec1, vec2)
  38. vec2Norm := norm(vec2)
  39. if vec2Norm == 0 {
  40. return 0.0
  41. }
  42. return dotProduct / (vec1Norm * vec2Norm)
  43. }
  44. type SimilarityIndex struct {
  45. Similarity float32
  46. Index int
  47. }
  48. func getNearestVectors(target []float32, vectors [][]float32, n int) []SimilarityIndex {
  49. targetNorm := norm(target)
  50. similarities := []SimilarityIndex{}
  51. for i, vector := range vectors {
  52. similarity := cosineSimilarity(target, vector, targetNorm)
  53. similarities = append(similarities, SimilarityIndex{similarity, i})
  54. }
  55. sort.Slice(similarities, func(i, j int) bool {
  56. return similarities[i].Similarity > similarities[j].Similarity
  57. })
  58. if len(vectors) < n {
  59. n = len(vectors)
  60. }
  61. res := similarities[:n]
  62. return res
  63. }