1
0
Эх сурвалжийг харах

添加 cosine

Signed-off-by: allan716 <[email protected]>
allan716 3 жил өмнө
parent
commit
ca980957f8

+ 38 - 0
pkg/cosine/cosine.go

@@ -0,0 +1,38 @@
+package cosine
+
+import (
+	"errors"
+	"math"
+)
+
+// https://github.com/gaspiman/cosine_similarity/blob/master/cosine.go
+func Cosine(a []float64, b []float64) (cosine float64, err error) {
+	count := 0
+	length_a := len(a)
+	length_b := len(b)
+	if length_a > length_b {
+		count = length_a
+	} else {
+		count = length_b
+	}
+	sumA := 0.0
+	s1 := 0.0
+	s2 := 0.0
+	for k := 0; k < count; k++ {
+		if k >= length_a {
+			s2 += math.Pow(b[k], 2)
+			continue
+		}
+		if k >= length_b {
+			s1 += math.Pow(a[k], 2)
+			continue
+		}
+		sumA += a[k] * b[k]
+		s1 += math.Pow(a[k], 2)
+		s2 += math.Pow(b[k], 2)
+	}
+	if s1 == 0 || s2 == 0 {
+		return 0.0, errors.New("Vectors should not be null (all zeros)")
+	}
+	return sumA / (math.Sqrt(s1) * math.Sqrt(s2)), nil
+}

+ 45 - 0
pkg/cosine/cosine_test.go

@@ -0,0 +1,45 @@
+package cosine
+
+import (
+	"testing"
+)
+
+func TestCosine(t *testing.T) {
+
+	a := []float64{1, 1, 0, 0, 1}
+	b := []float64{1, 1, 0, 0, 1}
+	cos, err := Cosine(a, b)
+	if err != nil {
+		t.Error(err)
+	}
+	if cos < 0.99 {
+		t.Error("Expected similarity of 1, got instead ", cos)
+	}
+	a = []float64{0, 1, 0, 1, 1}
+	b = []float64{1, 0, 1, 0, 0}
+	cos, err = Cosine(a, b)
+	if err != nil {
+		t.Error(err)
+	}
+	if cos != 0 {
+		t.Error("Expected similarity of 0, got instead ", cos)
+	}
+	a = []float64{1, 1, 0}
+	b = []float64{1, 0, 1}
+	cos, err = Cosine(a, b)
+	if err != nil {
+		t.Error(err)
+	}
+	if cos < 0.49999 || cos > 0.5 {
+		t.Error("Expected similarity of 0.5, got instead ", cos)
+	}
+	a = []float64{0, 1, 1, 1, 0}
+	b = []float64{1, 0}
+	cos, err = Cosine(a, b)
+	if err != nil {
+		t.Error(err)
+	}
+	if cos != 0 {
+		t.Error("Expected similarity of 0, got instead ", cos)
+	}
+}