1
0
mirror of https://github.com/sjwhitworth/golearn.git synced 2025-04-26 13:49:14 +08:00

add Cosine Distance

This commit is contained in:
FrozenKP 2017-04-07 21:11:20 +08:00
parent b2f8539172
commit 8791b6a751
2 changed files with 70 additions and 0 deletions

View File

@ -0,0 +1,34 @@
package pairwise
import (
"math"
"github.com/gonum/matrix/mat64"
)
type Cosine struct{}
func NewCosine() *Cosine {
return &Cosine{}
}
// Dot computes dot value of vectorX and vectorY.
func (c *Cosine) Dot(vectorX *mat64.Dense, vectorY *mat64.Dense) float64 {
subVector := mat64.NewDense(0, 0, nil)
subVector.MulElem(vectorX, vectorY)
result := mat64.Sum(subVector)
return result
}
// Distance computes Cosine distance.
// It will return distance which represented as 1-cos() (ranged from 0 to 2).
func (c *Cosine) Distance(vectorX *mat64.Dense, vectorY *mat64.Dense) float64 {
dotXY := c.Dot(vectorX, vectorY)
lengthX := math.Sqrt(c.Dot(vectorX, vectorX))
lengthY := math.Sqrt(c.Dot(vectorY, vectorY))
cos := dotXY / (lengthX*lengthY)
return 1-cos
}

View File

@ -0,0 +1,36 @@
package pairwise
import (
"testing"
"github.com/gonum/matrix/mat64"
. "github.com/smartystreets/goconvey/convey"
)
func TestCosine(t *testing.T) {
var vectorX, vectorY *mat64.Dense
cosine := NewCosine()
Convey("Given two vectors", t, func() {
vectorX = mat64.NewDense(3, 1, []float64{1, 2, 3})
vectorY = mat64.NewDense(3, 1, []float64{2, 4, 6})
Convey("When doing inner Dot", func() {
result := cosine.Dot(vectorX, vectorY)
Convey("The result should be 25", func() {
So(result, ShouldEqual, 28)
})
})
Convey("When calculating distance", func() {
result := cosine.Distance(vectorX, vectorY)
Convey("The result should be 0", func() {
So(result, ShouldEqual, 0)
})
})
})
}