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 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. "fmt"
  17. "math"
  18. "sort"
  19. )
  20. func dot(vec1, vec2 []float32) float32 {
  21. if len(vec1) != len(vec2) {
  22. panic("Vector lengths do not match")
  23. }
  24. dotProduct := float32(0.0)
  25. for i := range vec1 {
  26. dotProduct += vec1[i] * vec2[i]
  27. }
  28. return dotProduct
  29. }
  30. func norm(vec []float32) float32 {
  31. normSquared := float32(0.0)
  32. for _, val := range vec {
  33. normSquared += val * val
  34. }
  35. return float32(math.Sqrt(float64(normSquared)))
  36. }
  37. func cosineSimilarity(vec1, vec2 []float32, vec1Norm float32) float32 {
  38. dotProduct := dot(vec1, vec2)
  39. vec2Norm := norm(vec2)
  40. if vec2Norm == 0 {
  41. return 0.0
  42. }
  43. return dotProduct / (vec1Norm * vec2Norm)
  44. }
  45. type SimilarityIndex struct {
  46. Similarity float32
  47. Index int
  48. }
  49. func getNearestVectors(target []float32, vectors [][]float32, n int) ([]SimilarityIndex, error) {
  50. targetNorm := norm(target)
  51. similarities := []SimilarityIndex{}
  52. for i, vector := range vectors {
  53. if len(target) != len(vector) {
  54. return nil, fmt.Errorf("The target vector's length: [%d] should equal to knowledge vector's length: [%d], target vector = %v, knowledge vector = %v", len(target), len(vector), target, vector)
  55. }
  56. similarity := cosineSimilarity(target, vector, targetNorm)
  57. similarities = append(similarities, SimilarityIndex{similarity, i})
  58. }
  59. sort.Slice(similarities, func(i, j int) bool {
  60. return similarities[i].Similarity > similarities[j].Similarity
  61. })
  62. if n > len(similarities) {
  63. n = len(similarities)
  64. }
  65. res := similarities[:n]
  66. return res, nil
  67. }