github.com/weaviate/weaviate@v1.24.6/usecases/vectorizer/distance_test.go (about) 1 // _ _ 2 // __ _____ __ ___ ___ __ _| |_ ___ 3 // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ 4 // \ V V / __/ (_| |\ V /| | (_| | || __/ 5 // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| 6 // 7 // Copyright © 2016 - 2024 Weaviate B.V. All rights reserved. 8 // 9 // CONTACT: hello@weaviate.io 10 // 11 12 package vectorizer 13 14 import ( 15 "reflect" 16 "testing" 17 ) 18 19 func TestCosineSimilarity(t *testing.T) { 20 type args struct { 21 a, b []float32 22 } 23 tests := []struct { 24 name string 25 args args 26 want float32 27 }{ 28 { 29 "Distance between identical vectors", 30 args{ 31 a: []float32{1, 2, 3}, 32 b: []float32{1, 2, 3}, 33 }, 34 1.0, 35 }, 36 { 37 "Distance between similar vectors", 38 args{ 39 a: []float32{1, 2, 3}, 40 b: []float32{2, 3, 4}, 41 }, 42 0.99258333, 43 }, 44 { 45 "Distance between opposite vectors", 46 args{ 47 a: []float32{0, 1}, 48 b: []float32{0, -1}, 49 }, 50 -1.0, 51 }, 52 { 53 "Distance between perpendicular vectors", 54 args{ 55 a: []float32{0, 1}, 56 b: []float32{1, 0}, 57 }, 58 0.0, 59 }, 60 } 61 for _, tt := range tests { 62 t.Run(tt.name, func(t *testing.T) { 63 if got, _ := cosineSim(tt.args.a, tt.args.b); !reflect.DeepEqual(got, tt.want) { 64 t.Errorf("CombineVectors() = %v, want %v", got, tt.want) 65 } 66 }) 67 } 68 } 69 70 func TestCosineSim_DifferentDimensions(t *testing.T) { 71 a := []float32{1, 2, 3} 72 b := []float32{4, 5} 73 _, err := cosineSim(a, b) 74 if err == nil { 75 t.Errorf("expected error, got nil") 76 } 77 } 78 79 func BenchmarkCosineSimilarity(b *testing.B) { 80 for i := 0; i < b.N; i++ { 81 cosineSim([]float32{-0.214571, -0.605529, -0.335769, -0.185277, -0.212256, 0.478032, -0.536662, 0.298211}, 82 []float32{-0.14713769, -0.06872862, 0.09911085, -0.06342313, 0.10092197, -0.06624051, -0.06812558, 0.07360107}, 83 ) 84 } 85 }