forked from sjwhitworth/golearn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
poly_kernel.go
34 lines (26 loc) · 849 Bytes
/
poly_kernel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package pairwise
import (
"math"
"github.com/gonum/matrix/mat64"
)
type PolyKernel struct {
degree int
}
// NewPolyKernel returns a d-degree polynomial kernel
func NewPolyKernel(degree int) *PolyKernel {
return &PolyKernel{degree: degree}
}
// InnerProduct computes the inner product through a kernel trick
// K(x, y) = (x^T y + 1)^d
func (p *PolyKernel) InnerProduct(vectorX *mat64.Dense, vectorY *mat64.Dense) float64 {
result := mat64.Dot(vectorX, vectorY)
result = math.Pow(result+1, float64(p.degree))
return result
}
// Distance computes distance under the polynomial kernel (maybe not needed?)
func (p *PolyKernel) Distance(vectorX *mat64.Dense, vectorY *mat64.Dense) float64 {
subVector := mat64.NewDense(0, 0, nil)
subVector.Sub(vectorX, vectorY)
result := p.InnerProduct(subVector, subVector)
return math.Sqrt(result)
}