mirror of
https://github.com/sjwhitworth/golearn.git
synced 2025-04-26 13:49:14 +08:00
Add manhattan distance.
This commit is contained in:
parent
6517c838c4
commit
b045cf83a5
27
metrics/pairwise/manhattan.go
Normal file
27
metrics/pairwise/manhattan.go
Normal file
@ -0,0 +1,27 @@
|
||||
package pairwise
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
"github.com/gonum/matrix/mat64"
|
||||
)
|
||||
|
||||
type Manhattan struct{}
|
||||
|
||||
func NewManhattan() *Manhattan {
|
||||
return &Manhattan{}
|
||||
}
|
||||
|
||||
func (self *Manhattan) Distance(vectorX *mat64.Dense, vectorY *mat64.Dense) float64 {
|
||||
subVector := mat64.NewDense(0, 0, nil)
|
||||
subVector.Sub(vectorX, vectorY)
|
||||
|
||||
r, _ := subVector.Dims()
|
||||
|
||||
result := .0
|
||||
for i := 0; i < r; i++ {
|
||||
result += math.Abs(subVector.At(i, 0))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
27
metrics/pairwise/manhattan_test.go
Normal file
27
metrics/pairwise/manhattan_test.go
Normal file
@ -0,0 +1,27 @@
|
||||
package pairwise
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/gonum/matrix/mat64"
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
)
|
||||
|
||||
func TestManhattan(t *testing.T) {
|
||||
manhattan := NewManhattan()
|
||||
|
||||
Convey("Given two vectors", t, func() {
|
||||
vectorX := mat64.NewDense(3, 1, []float64{2, 2, 3})
|
||||
vectorY := mat64.NewDense(3, 1, []float64{1, 4, 5})
|
||||
|
||||
Convey("When calculating distance", func() {
|
||||
result := manhattan.Distance(vectorX, vectorY)
|
||||
|
||||
Convey("The result should be 5", func() {
|
||||
So(result, ShouldEqual, 5)
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
})
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user