2014-05-02 20:09:54 +08:00
|
|
|
package pairwise
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math"
|
|
|
|
|
2014-05-03 01:19:12 +08:00
|
|
|
"github.com/gonum/matrix/mat64"
|
2014-05-02 20:09:54 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type PolyKernel struct {
|
|
|
|
degree int
|
|
|
|
}
|
|
|
|
|
2014-07-18 13:48:28 +03:00
|
|
|
// NewPolyKernel returns a d-degree polynomial kernel
|
2014-05-02 20:09:54 +08:00
|
|
|
func NewPolyKernel(degree int) *PolyKernel {
|
|
|
|
return &PolyKernel{degree: degree}
|
|
|
|
}
|
|
|
|
|
2014-07-18 13:48:28 +03:00
|
|
|
// InnerProduct computes the inner product through a kernel trick
|
2014-05-03 23:05:24 +08:00
|
|
|
// K(x, y) = (x^T y + 1)^d
|
2014-07-18 13:58:07 +03:00
|
|
|
func (p *PolyKernel) InnerProduct(vectorX *mat64.Dense, vectorY *mat64.Dense) float64 {
|
2016-09-28 15:12:32 +01:00
|
|
|
subVectorX := vectorX.ColView(0)
|
|
|
|
subVectorY := vectorY.ColView(0)
|
|
|
|
result := mat64.Dot(subVectorX, subVectorY)
|
|
|
|
result = math.Pow(result+1, float64(p.degree))
|
2014-05-02 20:09:54 +08:00
|
|
|
|
2014-05-03 01:19:12 +08:00
|
|
|
return result
|
2014-05-02 20:09:54 +08:00
|
|
|
}
|
|
|
|
|
2014-07-18 13:48:28 +03:00
|
|
|
// Distance computes distance under the polynomial kernel (maybe not needed?)
|
2014-07-18 13:58:07 +03:00
|
|
|
func (p *PolyKernel) Distance(vectorX *mat64.Dense, vectorY *mat64.Dense) float64 {
|
2014-05-03 01:19:12 +08:00
|
|
|
subVector := mat64.NewDense(0, 0, nil)
|
|
|
|
subVector.Sub(vectorX, vectorY)
|
2014-07-18 13:58:07 +03:00
|
|
|
result := p.InnerProduct(subVector, subVector)
|
2014-05-02 20:09:54 +08:00
|
|
|
|
2014-05-03 01:19:12 +08:00
|
|
|
return math.Sqrt(result)
|
2014-05-02 20:09:54 +08:00
|
|
|
}
|