mirror of
https://github.com/fumiama/paper-manager.git
synced 2026-06-09 10:21:00 +08:00
add cosine similarity & 完善 PaperType
This commit is contained in:
19
backend/utils/cosimi.go
Normal file
19
backend/utils/cosimi.go
Normal file
@@ -0,0 +1,19 @@
|
||||
// edit from https://github.com/kabychow/go-cosinesimilarity
|
||||
|
||||
package utils
|
||||
|
||||
import "math"
|
||||
|
||||
// Similarity len(x) must eq len(y)
|
||||
func Similarity(x, y []uint8) float64 {
|
||||
var sum, s1, s2 uint64
|
||||
for i := 0; i < len(x); i++ {
|
||||
sum += uint64(x[i]) * uint64(y[i])
|
||||
s1 += uint64(x[i]) * uint64(x[i])
|
||||
s2 += uint64(y[i]) * uint64(y[i])
|
||||
}
|
||||
if s1 == 0 || s2 == 0 {
|
||||
return 0.0
|
||||
}
|
||||
return float64(sum) / (math.Sqrt(float64(s1)) * math.Sqrt(float64(s2)))
|
||||
}
|
||||
19
backend/utils/cosimi_test.go
Normal file
19
backend/utils/cosimi_test.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSimilarity(t *testing.T) {
|
||||
r := Similarity([]uint8{1, 2, 3}, []uint8{1, 3, 4})
|
||||
t.Log(r)
|
||||
if math.Abs(r-0.9958705948858224) > 1e-6 {
|
||||
t.Fail()
|
||||
}
|
||||
r = Similarity([]uint8{3, 2, 1}, []uint8{1, 3, 4})
|
||||
t.Log(r)
|
||||
if math.Abs(r-0.6813851438692469) > 1e-6 {
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user